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
9b0095a6d6d99761b6d1ed921b1980028e41e4b9
f57749ca63d6416f807b770f67559503fdb21001
/library/data/finset/basic.lean
609e4e14bc91bf23fa2a6e24d383bacc833eb762
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,239
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad Finite sets. -/ import data.fintype.basic data.nat data.list.perm data.subtype algebra.binary open nat quot list subtype binary function eq.ops open [declarations] perm definition nodup_list (A : Type) := {l : list A | nodup l} variable {A : Type} definition to_nodup_list_of_nodup {l : list A} (n : nodup l) : nodup_list A := tag l n definition to_nodup_list [h : decidable_eq A] (l : list A) : nodup_list A := @to_nodup_list_of_nodup A (erase_dup l) (nodup_erase_dup l) private definition eqv (l₁ l₂ : nodup_list A) := perm (elt_of l₁) (elt_of l₂) local infix ~ := eqv private definition eqv.refl (l : nodup_list A) : l ~ l := !perm.refl private definition eqv.symm {l₁ l₂ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private definition eqv.trans {l₁ l₂ l₃ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans definition finset.nodup_list_setoid [instance] (A : Type) : setoid (nodup_list A) := setoid.mk (@eqv A) (mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)) definition finset (A : Type) : Type := quot (finset.nodup_list_setoid A) namespace finset definition to_finset_of_nodup (l : list A) (n : nodup l) : finset A := ⟦to_nodup_list_of_nodup n⟧ definition to_finset [h : decidable_eq A] (l : list A) : finset A := ⟦to_nodup_list l⟧ lemma to_finset_eq_of_nodup [h : decidable_eq A] {l : list A} (n : nodup l) : to_finset_of_nodup l n = to_finset l := assert P : to_nodup_list_of_nodup n = to_nodup_list l, from begin rewrite [↑to_nodup_list, ↑to_nodup_list_of_nodup], congruence, rewrite [erase_dup_eq_of_nodup n] end, quot.sound (eq.subst P !setoid.refl) definition has_decidable_eq [instance] [h : decidable_eq A] : decidable_eq (finset A) := λ s₁ s₂, quot.rec_on_subsingleton₂ s₁ s₂ (λ l₁ l₂, match decidable_perm (elt_of l₁) (elt_of l₂) with | decidable.inl e := decidable.inl (quot.sound e) | decidable.inr n := decidable.inr (λ e : ⟦l₁⟧ = ⟦l₂⟧, absurd (quot.exact e) n) end) definition mem (a : A) (s : finset A) : Prop := quot.lift_on s (λ l, a ∈ elt_of l) (λ l₁ l₂ (e : l₁ ~ l₂), propext (iff.intro (λ ainl₁, mem_perm e ainl₁) (λ ainl₂, mem_perm (perm.symm e) ainl₂))) infix `∈` := mem notation a ∉ b := ¬ mem a b theorem mem_of_mem_list {a : A} {l : nodup_list A} : a ∈ elt_of l → a ∈ ⟦l⟧ := λ ainl, ainl theorem mem_list_of_mem {a : A} {l : nodup_list A} : a ∈ ⟦l⟧ → a ∈ elt_of l := λ ainl, ainl /- singleton -/ definition singleton (a : A) : finset A := to_finset_of_nodup [a] !nodup_singleton theorem mem_singleton [simp] (a : A) : a ∈ singleton a := mem_of_mem_list !mem_cons theorem eq_of_mem_singleton {x a : A} : x ∈ singleton a → x = a := list.mem_singleton theorem mem_singleton_eq (x a : A) : (x ∈ singleton a) = (x = a) := propext (iff.intro eq_of_mem_singleton (assume H, eq.subst H !mem_singleton)) lemma eq_of_singleton_eq {a b : A} : singleton a = singleton b → a = b := assume Pseq, eq_of_mem_singleton (Pseq ▸ mem_singleton a) definition decidable_mem [instance] [h : decidable_eq A] : ∀ (a : A) (s : finset A), decidable (a ∈ s) := λ a s, quot.rec_on_subsingleton s (λ l, match list.decidable_mem a (elt_of l) with | decidable.inl p := decidable.inl (mem_of_mem_list p) | decidable.inr n := decidable.inr (λ p, absurd (mem_list_of_mem p) n) end) theorem mem_to_finset [h : decidable_eq A] {a : A} {l : list A} : a ∈ l → a ∈ to_finset l := λ ainl, mem_erase_dup ainl theorem mem_to_finset_of_nodup {a : A} {l : list A} (n : nodup l) : a ∈ l → a ∈ to_finset_of_nodup l n := λ ainl, ainl /- extensionality -/ theorem ext {s₁ s₂ : finset A} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ e, quot.sound (perm_ext (has_property l₁) (has_property l₂) e)) /- empty -/ definition empty : finset A := to_finset_of_nodup [] nodup_nil notation `∅` := !empty theorem not_mem_empty [simp] (a : A) : a ∉ ∅ := λ aine : a ∈ ∅, aine theorem mem_empty_iff [simp] (x : A) : x ∈ ∅ ↔ false := iff_false_intro !not_mem_empty theorem mem_empty_eq (x : A) : x ∈ ∅ = false := propext !mem_empty_iff theorem eq_empty_of_forall_not_mem {s : finset A} (H : ∀x, ¬ x ∈ s) : s = ∅ := ext (take x, iff_false_intro (H x)) /- universe -/ definition univ [h : fintype A] : finset A := to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) theorem mem_univ [h : fintype A] (x : A) : x ∈ univ := fintype.complete x theorem mem_univ_eq [h : fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- card -/ definition card (s : finset A) : nat := quot.lift_on s (λ l, length (elt_of l)) (λ l₁ l₂ p, length_eq_length_of_perm p) theorem card_empty : card (@empty A) = 0 := rfl theorem card_singleton (a : A) : card (singleton a) = 1 := rfl lemma ne_empty_of_card_eq_succ {s : finset A} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- insert -/ section insert variable [h : decidable_eq A] include h definition insert (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (insert a (elt_of l)) (nodup_insert a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (perm_insert a p)) -- set builder notation notation `'{`:max a:(foldr `,` (x b, insert x b) ∅) `}`:0 := a -- notation `⦃` a:(foldr `,` (x b, insert x b) ∅) `⦄` := a theorem mem_insert (a : A) (s : finset A) : a ∈ insert a s := quot.induction_on s (λ l : nodup_list A, mem_to_finset_of_nodup _ !list.mem_insert) theorem mem_insert_of_mem {a : A} {s : finset A} (b : A) : a ∈ s → a ∈ insert b s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), mem_to_finset_of_nodup _ (list.mem_insert_of_mem _ ainl)) theorem eq_or_mem_of_mem_insert {x a : A} {s : finset A} : x ∈ insert a s → x = a ∨ x ∈ s := quot.induction_on s (λ l : nodup_list A, λ H, list.eq_or_mem_of_mem_insert H) theorem mem_of_mem_insert_of_ne {x a : A} {s : finset A} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_eq (x a : A) (s : finset A) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem)) theorem insert_empty_eq (a : A) : '{a} = singleton a := rfl theorem insert_eq_of_mem {a : A} {s : finset A} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) -- useful in proofs by induction theorem forall_of_forall_insert {P : A → Prop} {a : A} {s : finset A} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) theorem insert.comm (x y : A) (s : finset A) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) theorem card_insert_of_mem {a : A} {s : finset A} : a ∈ s → card (insert a s) = card s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), list.length_insert_of_mem ainl) theorem card_insert_of_not_mem {a : A} {s : finset A} : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list A) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le (a : A) (s : finset A) : card (insert a s) ≤ card s + 1 := if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ else by rewrite [card_insert_of_not_mem H] protected theorem induction [recursor 6] {P : finset A → Prop} (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀{s : finset A}, a ∉ s → P s → P (insert a s)) : ∀s, P s := take s, quot.induction_on s (take u, subtype.destruct u (take l, list.induction_on l (assume nodup_l, H1) (take a l', assume IH nodup_al', have a ∉ l', from not_mem_of_nodup_cons nodup_al', assert e : list.insert a l' = a :: l', from insert_eq_of_not_mem this, assert nodup l', from nodup_of_nodup_cons nodup_al', assert P (quot.mk (subtype.tag l' this)), from IH this, assert P (insert a (quot.mk (subtype.tag l' _))), from H2 `a ∉ l'` this, begin revert nodup_al', rewrite [-e], intros, apply this end))) protected theorem induction_on {P : finset A → Prop} (s : finset A) (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀ {s : finset A}, a ∉ s → P s → P (insert a s)) : P s := finset.induction H1 H2 s theorem exists_of_not_empty {s : finset A} : s ≠ ∅ → ∃ a : A, a ∈ s := begin induction s with a s nin ih, {intro h, exact absurd rfl h}, {intro h, existsi a, apply mem_insert} end theorem eq_empty_of_card_eq_zero {s : finset A} (H : card s = 0) : s = ∅ := begin induction s with a s' H1 IH, { reflexivity }, { rewrite (card_insert_of_not_mem H1) at H, apply nat.no_confusion H} end end insert /- erase -/ section erase variable [h : decidable_eq A] include h definition erase (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (erase a (elt_of l)) (nodup_erase_of_nodup a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (erase_perm_erase_of_perm a p)) theorem mem_erase (a : A) (s : finset A) : a ∉ erase a s := quot.induction_on s (λ l, list.mem_erase_of_nodup _ (has_property l)) theorem card_erase_of_mem {a : A} {s : finset A} : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_erase_of_not_mem {a : A} {s : finset A} : a ∉ s → card (erase a s) = card s := quot.induction_on s (λ l nainl, list.length_erase_of_not_mem nainl) theorem erase_empty (a : A) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !mem_erase theorem mem_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ∈ s := quot.induction_on s (λ l bin, mem_of_mem_erase bin) theorem mem_erase_of_ne_of_mem {a b : A} {s : finset A} : a ≠ b → a ∈ s → a ∈ erase b s := quot.induction_on s (λ l n ain, list.mem_erase_of_ne_of_mem n ain) theorem mem_erase_iff (a b : A) (s : finset A) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : A) (s : finset A) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff open decidable theorem erase_insert {a : A} {s : finset A} : a ∉ s → erase a (insert a s) = s := λ anins, finset.ext (λ b, by_cases (λ beqa : b = a, iff.intro (λ bin, by subst b; exact absurd bin !mem_erase) (λ bin, by subst b; contradiction)) (λ bnea : b ≠ a, iff.intro (λ bin, assert b ∈ insert a s, from mem_of_mem_erase bin, mem_of_mem_insert_of_ne this bnea) (λ bin, have b ∈ insert a s, from mem_insert_of_mem _ bin, mem_erase_of_ne_of_mem bnea this))) theorem insert_erase {a : A} {s : finset A} : a ∈ s → insert a (erase a s) = s := λ ains, finset.ext (λ b, by_cases (suppose b = a, iff.intro (λ bin, by subst b; assumption) (λ bin, by subst b; apply mem_insert)) (suppose b ≠ a, iff.intro (λ bin, mem_of_mem_erase (mem_of_mem_insert_of_ne bin `b ≠ a`)) (λ bin, mem_insert_of_mem _ (mem_erase_of_ne_of_mem `b ≠ a` bin)))) end erase /- union -/ section union variable [h : decidable_eq A] include h definition union (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union (elt_of l₁) (elt_of l₂)) (nodup_union_of_nodup_of_nodup (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_union p₁ p₂)) notation s₁ ∪ s₂ := union s₁ s₂ theorem mem_union_left {a : A} {s₁ : finset A} (s₂ : finset A) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁, list.mem_union_left _ ainl₁) theorem mem_union_l {a : A} {s₁ : finset A} {s₂ : finset A} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : A} {s₂ : finset A} (s₁ : finset A) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₂, list.mem_union_right _ ainl₂) theorem mem_union_r {a : A} {s₂ : finset A} {s₁ : finset A} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_or_mem_of_mem_union ainl₁l₂) theorem mem_union_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union.comm (s₁ s₂ : finset A) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union.assoc (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union.left_comm (s₁ s₂ s₃ : finset A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union.comm union.assoc s₁ s₂ s₃ theorem union.right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union.comm union.assoc s₁ s₂ s₃ theorem union_self (s : finset A) : s ∪ s = s := ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : finset A) : s ∪ ∅ = s := ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : finset A) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union.comm ... = s : union_empty theorem insert_eq (a : A) (s : finset A) : insert a s = singleton a ∪ s := ext (take x, calc x ∈ insert a s ↔ x ∈ insert a s : iff.refl ... = (x = a ∨ x ∈ s) : mem_insert_eq ... = (x ∈ singleton a ∨ x ∈ s) : mem_singleton_eq ... = (x ∈ '{a} ∪ s) : mem_union_eq) theorem insert_union (a : A) (s t : finset A) : insert a (s ∪ t) = insert a s ∪ t := by rewrite [*insert_eq, union.assoc] end union /- inter -/ section inter variable [h : decidable_eq A] include h definition inter (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter (elt_of l₁) (elt_of l₂)) (nodup_inter_of_nodup _ (has_property l₁))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_inter p₁ p₂)) notation s₁ ∩ s₂ := inter s₁ s₂ theorem mem_of_mem_inter_left {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_left ainl₁l₂) theorem mem_of_mem_inter_right {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_right ainl₁l₂) theorem mem_inter {a : A} {s₁ s₂ : finset A} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁ ainl₂, list.mem_inter_of_mem_of_mem ainl₁ ainl₂) theorem mem_inter_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter.comm (s₁ s₂ : finset A) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter.assoc (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter.left_comm (s₁ s₂ s₃ : finset A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter.right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter_self (s : finset A) : s ∩ s = s := ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : finset A) : s ∩ ∅ = ∅ := ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : finset A) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter.comm ... = ∅ : inter_empty theorem singleton_inter_of_mem {a : A} {s : finset A} (H : a ∈ s) : singleton a ∩ s = singleton a := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_eq], exact iff.intro (suppose x = a ∧ x ∈ s, and.left this) (suppose x = a, and.intro this (eq.subst (eq.symm this) H)) end) theorem singleton_inter_of_not_mem {a : A} {s : finset A} (H : a ∉ s) : singleton a ∩ s = ∅ := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_eq, mem_empty_eq], exact iff.intro (suppose x = a ∧ x ∈ s, H (eq.subst (and.left this) (and.right this))) (false.elim) end) end inter /- distributivity laws -/ section inter variable [h : decidable_eq A] include h theorem inter.distrib_left (s t u : finset A) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.left_distrib) theorem inter.distrib_right (s t u : finset A) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.right_distrib) theorem union.distrib_left (s t u : finset A) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.left_distrib) theorem union.distrib_right (s t u : finset A) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.right_distrib) end inter /- disjoint -/ -- Mainly for internal use; library will use s₁ ∩ s₂ = ∅. Note that it does not require decidable equality. definition disjoint (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, disjoint (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ d₁ a (ainw₁ : a ∈ elt_of w₁), have a ∈ elt_of v₁, from mem_perm (perm.symm p₁) ainw₁, have a ∉ elt_of v₂, from disjoint_left d₁ this, not_mem_perm p₂ this) (λ d₂ a (ainv₁ : a ∈ elt_of v₁), have a ∈ elt_of w₁, from mem_perm p₁ ainv₁, have a ∉ elt_of w₂, from disjoint_left d₂ this, not_mem_perm (perm.symm p₂) this))) theorem disjoint.elim {s₁ s₂ : finset A} {x : A} : disjoint s₁ s₂ → x ∈ s₁ → x ∈ s₂ → false := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H H1 H2, H x H1 H2) theorem disjoint.intro {s₁ s₂ : finset A} : (∀{x : A}, x ∈ s₁ → x ∈ s₂ → false) → disjoint s₁ s₂ := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H, H) theorem inter_eq_empty_of_disjoint [h : decidable_eq A] {s₁ s₂ : finset A} (H : disjoint s₁ s₂) : s₁ ∩ s₂ = ∅ := ext (take x, iff_false_intro (assume H1, disjoint.elim H (mem_of_mem_inter_left H1) (mem_of_mem_inter_right H1))) theorem disjoint_of_inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : s₁ ∩ s₂ = ∅) : disjoint s₁ s₂ := disjoint.intro (take x H1 H2, have x ∈ s₁ ∩ s₂, from mem_inter H1 H2, !not_mem_empty (eq.subst H this)) theorem disjoint.comm {s₁ s₂ : finset A} : disjoint s₁ s₂ → disjoint s₂ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ d, list.disjoint.comm d) theorem inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : ∀x : A, x ∈ s₁ → x ∈ s₂ → false) : s₁ ∩ s₂ = ∅ := inter_eq_empty_of_disjoint (disjoint.intro H) /- subset -/ definition subset (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, sublist (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, mem_perm p₂ (s₁ a (mem_perm (perm.symm p₁) i))) (λ s₂ a i, mem_perm (perm.symm p₂) (s₂ a (mem_perm p₁ i))))) infix `⊆` := subset theorem empty_subset (s : finset A) : ∅ ⊆ s := quot.induction_on s (λ l, list.nil_sub (elt_of l)) theorem subset_univ [h : fintype A] (s : finset A) : s ⊆ univ := quot.induction_on s (λ l a i, fintype.complete a) theorem subset.refl (s : finset A) : s ⊆ s := quot.induction_on s (λ l, list.sub.refl (elt_of l)) theorem subset.trans {s₁ s₂ s₃ : finset A} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quot.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃ h₁ h₂, list.sub.trans h₁ h₂) theorem mem_of_subset_of_mem {s₁ s₂ : finset A} {a : A} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ a h₂) theorem subset.antisymm {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (take x, iff.intro (assume H, mem_of_subset_of_mem H₁ H) (assume H, mem_of_subset_of_mem H₂ H)) -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : finset A} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H) theorem subset_insert [h : decidable_eq A] (s : finset A) (a : A) : s ⊆ insert a s := subset_of_forall (take x, suppose x ∈ s, mem_insert_of_mem _ this) theorem eq_empty_of_subset_empty {x : finset A} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : finset A) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) section variable [decA : decidable_eq A] include decA theorem erase_subset_erase (a : A) {s t : finset A} (H : s ⊆ t) : erase a s ⊆ erase a t := begin apply subset_of_forall, intro x, rewrite *mem_erase_eq, intro H', show x ∈ t ∧ x ≠ a, from and.intro (mem_of_subset_of_mem H (and.left H')) (and.right H') end theorem erase_subset (a : A) (s : finset A) : erase a s ⊆ s := begin apply subset_of_forall, intro x, rewrite mem_erase_eq, intro H, apply and.left H end theorem erase_eq_of_not_mem {a : A} {s : finset A} (anins : a ∉ s) : erase a s = s := eq_of_subset_of_subset !erase_subset (subset_of_forall (take x, assume xs : x ∈ s, have x ≠ a, from assume H', anins (eq.subst H' xs), mem_erase_of_ne_of_mem this xs)) theorem erase_insert_subset (a : A) (s : finset A) : erase a (insert a s) ⊆ s := decidable.by_cases (assume ains : a ∈ s, by rewrite [insert_eq_of_mem ains]; apply erase_subset) (assume nains : a ∉ s, by rewrite [!erase_insert nains]; apply subset.refl) theorem erase_subset_of_subset_insert {a : A} {s t : finset A} (H : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (!erase_subset_erase H) !erase_insert_subset theorem insert_erase_subset (a : A) (s : finset A) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, by rewrite[erase_eq_of_not_mem nains]; apply subset_insert) theorem insert_subset_insert (a : A) {s t : finset A} (H : s ⊆ t) : insert a s ⊆ insert a t := begin apply subset_of_forall, intro x, rewrite *mem_insert_eq, intro H', cases H' with [xeqa, xins], exact (or.inl xeqa), exact (or.inr (mem_of_subset_of_mem H xins)) end theorem subset_insert_of_erase_subset {s t : finset A} {a : A} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : finset A) (a : A) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset end /- upto -/ section upto definition upto (n : nat) : finset nat := to_finset_of_nodup (list.upto n) (nodup_upto n) theorem card_upto : ∀ n, card (upto n) = n := list.length_upto theorem lt_of_mem_upto {n a : nat} : a ∈ upto n → a < n := list.lt_of_mem_upto theorem mem_upto_succ_of_mem_upto {n a : nat} : a ∈ upto n → a ∈ upto (succ n) := list.mem_upto_succ_of_mem_upto theorem mem_upto_of_lt {n a : nat} : a < n → a ∈ upto n := list.mem_upto_of_lt theorem mem_upto_iff (a n : nat) : a ∈ upto n ↔ a < n := iff.intro lt_of_mem_upto mem_upto_of_lt theorem mem_upto_eq (a n : nat) : a ∈ upto n = (a < n) := propext !mem_upto_iff end upto /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) ↔ false := iff.intro (assume H, obtain x (H1 : x ∈ ∅ ∧ P x), from H, !not_mem_empty (and.left H1)) (assume H, false.elim H) theorem exists_mem_empty_eq {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) = false := propext !exists_mem_empty_iff theorem exists_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) ↔ P a ∨ (∃ x, x ∈ s ∧ P x) := iff.intro (assume H, obtain x [H1 H2], from H, or.elim (eq_or_mem_of_mem_insert H1) (suppose x = a, or.inl (eq.subst this H2)) (suppose x ∈ s, or.inr (exists.intro x (and.intro this H2)))) (assume H, or.elim H (suppose P a, exists.intro a (and.intro !mem_insert this)) (suppose ∃ x, x ∈ s ∧ P x, obtain x [H2 H3], from this, exists.intro x (and.intro (!mem_insert_of_mem H2) H3))) theorem exists_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) = (P a ∨ (∃ x, x ∈ s ∧ P x)) := propext !exists_mem_insert_iff theorem forall_mem_empty_iff {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) ↔ true := iff.intro (assume H, trivial) (assume H, take x, assume H', absurd H' !not_mem_empty) theorem forall_mem_empty_eq {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) = true := propext !forall_mem_empty_iff theorem forall_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) ↔ P a ∧ (∀ x, x ∈ s → P x) := iff.intro (assume H, and.intro (H _ !mem_insert) (take x, assume H', H _ (!mem_insert_of_mem H'))) (assume H, take x, assume H' : x ∈ insert a s, or.elim (eq_or_mem_of_mem_insert H') (suppose x = a, eq.subst (eq.symm this) (and.left H)) (suppose x ∈ s, and.right H _ this)) theorem forall_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) = (P a ∧ (∀ x, x ∈ s → P x)) := propext !forall_mem_insert_iff end finset
718bb772ac5dc3c35e29cb8d63942bbaf7ab7327
87a08a8e9b222ec02f3327dca4ae24590c1b3de9
/src/topology/algebra/ordered.lean
4a36c131a552c3948cb8a1dbeb81820ac91cf47b
[ "Apache-2.0" ]
permissive
naussicaa/mathlib
86d05223517a39e80920549a8052f9cf0e0b77b8
1ef2c2df20cf45c21675d855436228c7ae02d47a
refs/heads/master
1,592,104,950,080
1,562,073,069,000
1,562,073,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,552
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of ordered topology. -/ import order.liminf_limsup import data.set.intervals import topology.algebra.group import topology.constructions open classical set lattice filter topological_space local attribute [instance] classical.prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- (Partially) ordered topology Also called: partially ordered spaces (pospaces). Usually ordered topology is used for a topology on linear ordered spaces, where the open intervals are open sets. This is a generalization as for each linear order where open interals are open sets, the order relation is closed. -/ class ordered_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed (λp:α×α, p.1 ≤ p.2)) instance {α : Type*} : Π [topological_space α], topological_space (order_dual α) := id section ordered_topology section preorder variables [topological_space α] [preorder α] [t : ordered_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id instance : ordered_topology (order_dual α) := ⟨continuous_swap _ (@ordered_topology.is_closed_le' α _ _ _)⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter (is_closed_ge' a) (is_closed_le' b) lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) (h : {b | f b ≤ g b} ∈ b) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (nhds (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from mem_of_closed_of_tendsto hb this t.is_closed_le' h lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | c ≤ b} ∈ x) : a ≤ b := le_of_tendsto_of_tendsto nt lim tendsto_const_nhds h lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | b ≤ c} ∈ x) : b ≤ a := le_of_tendsto_of_tendsto nt tendsto_const_nhds lim h @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := closure_eq_iff_is_closed.mpr $ is_closed_le hf hg end preorder section partial_order variables [topological_space α] [partial_order α] [t : ordered_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) instance ordered_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [t : ordered_topology α] include t lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf lemma is_open_Ioo {a b : α} : is_open (Ioo a b) := is_open_and (is_open_lt continuous_const continuous_id) (is_open_lt continuous_id continuous_const) lemma is_open_Iio {a : α} : is_open (Iio a) := is_open_lt continuous_id continuous_const end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [t : ordered_topology α] [topological_space β] {f g : β → α} include t section variables (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := assume b ⟨hb₁, hb₂⟩, le_antisymm (by simpa [closure_le_eq hf hg] using hb₁) (not_lt.1 $ assume hb : f b < g b, have {b | f b < g b} ⊆ interior {b | f b ≤ g b}, from (subset_interior_iff_subset_of_open $ is_open_lt hf hg).mpr $ assume x, le_of_lt, have b ∈ interior {b | f b ≤ g b}, from this hb, by exact hb₂ this) lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous_max : continuous (λb, max (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, g b = f b, from assume b hb, (frontier_le_subset_eq hf hg hb).symm, continuous_if this hg hf lemma continuous_min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg end lemma tendsto_max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, max (f b) (g b)) b (nhds (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (max a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_max continuous_fst continuous_snd) _ end (hf.prod_mk hg) lemma tendsto_min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, min (f b) (g b)) b (nhds (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (min a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_min continuous_fst continuous_snd) _ end (hf.prod_mk hg) end decidable_linear_order end ordered_topology /-- Topologies generated by the open intervals. This is restricted to linear orders. Only then it is guaranteed that they are also a ordered topology. -/ class orderable_topology (α : Type*) [t : topological_space α] [partial_order α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}}) section orderable_topology instance {α : Type*} [topological_space α] [partial_order α] [orderable_topology α] : orderable_topology (order_dual α) := ⟨by convert @orderable_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : orderable_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : {b | a < b} ∈ nhds b := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : {b | a ≤ b} ∈ nhds b := (nhds b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : {a | a < b} ∈ nhds a := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : {a | a ≤ b} ∈ nhds a := (nhds a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_orderable {a : α} : nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_orderable {f : β → α} {a : α} {x : filter β} : tendsto f x (nhds a) ↔ (∀a'<a, {b | a' < f b} ∈ x) ∧ (∀a'>a, {b | a' > f b} ∈ x) := by simp [@nhds_eq_orderable α _ _, tendsto_inf, tendsto_infi, tendsto_principal] /-- Also known as squeeze or sandwich theorem. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (nhds a)) (hh : tendsto h b (nhds a)) (hgf : {b | g b ≤ f b} ∈ b) (hfh : {b | f b ≤ h b} ∈ b) : tendsto f b (nhds a) := tendsto_orderable.2 ⟨assume a' h', have {b : β | a' < g b} ∈ b, from (tendsto_orderable.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have {b : β | h b < a'} ∈ b, from (tendsto_orderable.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ lemma nhds_orderable_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : nhds a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal {x | l < x ∧ x < u }) := let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in calc nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) : nhds_eq_orderable ... = (⨅b<a, principal {c | b < c} ⊓ (⨅b>a, principal {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, principal {c | c < u} ⊓ principal {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_orderable_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → {b | l < f b ∧ f b < u } ∈ x) : tendsto f x (nhds a) := by rw [nhds_orderable_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_orderable_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @orderable_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced_eq_comap, nhds_generate_from, @nhds_eq_orderable β _ _], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_orderable_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @orderable_topology _ (induced f ta) _ := induced_orderable_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) lemma nhds_top_orderable [topological_space α] [order_top α] [orderable_topology α] : nhds (⊤:α) = (⨅l (h₂ : l < ⊤), principal {x | l < x}) := by rw [@nhds_eq_orderable α _ _]; simp [(>)] lemma nhds_bot_orderable [topological_space α] [order_bot α] [orderable_topology α] : nhds (⊥:α) = (⨅l (h₂ : ⊥ < l), principal {x | x < l}) := by rw [@nhds_eq_orderable α _ _]; simp section linear_order variables [topological_space α] [linear_order α] [t : orderable_topology α] include t lemma mem_nhds_orderable_dest {a : α} {s : set α} (hs : s ∈ nhds a) : ((∃u, u>a) → ∃u, a < u ∧ ∀b, a ≤ b → b < u → b ∈ s) ∧ ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ≤ a → b ∈ s) := let ⟨t₁, ht₁, t₂, ht₂, hts⟩ := mem_inf_sets.mp $ by rw [@nhds_eq_orderable α _ _ _] at hs; exact hs in have ht₁ : ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ∈ t₁) ∧ (∀b, a ≤ b → b ∈ t₁), from infi_sets_induct ht₁ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' < a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨max u a', max_lt hu₁ h, assume b hb, ⟨hs₁ $ lt_of_le_of_lt (le_max_right _ _) hb, hu₂ _ $ lt_of_le_of_lt (le_max_left _ _) hb⟩⟩, assume b hb, ⟨hs₁ $ lt_of_lt_of_le h hb, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), have ht₂ : ((∃u, u>a) → ∃u, a < u ∧ ∀b, b < u → b ∈ t₂) ∧ (∀b, b ≤ a → b ∈ t₂), from infi_sets_induct ht₂ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' > a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨min u a', lt_min hu₁ h, assume b hb, ⟨hs₁ $ lt_of_lt_of_le hb (min_le_right _ _), hu₂ _ $ lt_of_lt_of_le hb (min_le_left _ _)⟩⟩, assume b hb, ⟨hs₁ $ lt_of_le_of_lt hb h, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), and.intro (assume hx, let ⟨u, hu, h⟩ := ht₂.left hx in ⟨u, hu, assume b hb hbu, hts ⟨ht₁.right b hb, h _ hbu⟩⟩) (assume hx, let ⟨l, hl, h⟩ := ht₁.left hx in ⟨l, hl, assume b hbl hb, hts ⟨h _ hbl, ht₂.right b hb⟩⟩) lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ nhds a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have nhds a = (⨅p : {l // l < a} × {u // a < u}, principal {x | p.1.val < x ∧ x < p.2.val }), by simp [nhds_orderable_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete h with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end instance orderable_topology.to_ordered_topology : ordered_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } instance orderable_topology.t2_space : t2_space α := by apply_instance instance orderable_topology.regular_space : regular_space α := { regular := assume s a hs ha, have -s ∈ nhds a, from mem_nhds_sets hs ha, let ⟨h₁, h₂⟩ := mem_nhds_orderable_dest this in have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := h₂ h in match dense_or_discrete hl with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h c (lt_of_lt_of_le hb₁ hbc) (le_of_lt hca) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := h₁ h in match dense_or_discrete hu with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h c (le_of_lt hca) (lt_of_le_of_lt hbc hb₂) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [←sup_principal, inf_sup_left, ht₁a, ht₂a, bot_sup_eq]⟩, ..orderable_topology.t2_space } end linear_order lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_comm_group α] [orderable_topology α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg') $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : mono_image $ image_closure_subset_closure_image continuous_neg' ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [orderable_topology α] [orderable_topology β] lemma nhds_principal_ne_bot_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : nhds a ⊓ principal s ≠ ⊥ := let ⟨a', ha'⟩ := exists_mem_of_ne_empty hs in forall_sets_neq_empty_iff_neq_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in let ⟨hu, hl⟩ := mem_nhds_orderable_dest ht₁ in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ne_empty_iff_exists_mem.mpr ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := hl ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right _ this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ _ ‹l < a'› $ ha.left _ ha', ne_empty_iff_exists_mem.mpr ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma nhds_principal_ne_bot_of_is_glb : ∀ {a : α} {s : set α}, is_glb s a → s ≠ ∅ → nhds a ⊓ principal s ≠ ⊥ := @nhds_principal_ne_bot_of_is_lub (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) (hfa : f ⊓ nhds a ≠ ⊥) : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ nhds a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := inhabited_of_mem_sets hfa this in have b < b, from lt_of_lt_of_le hxb $ hb _ hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → f ⊓ nhds a ≠ ⊥ → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s ≠ ∅) (hb : tendsto f (nhds a ⊓ principal s) (nhds b)) : is_lub (f '' s) b := have hnbot : (nhds a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have {x | x < f a'} ∈ nhds b, from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ha') h.symm, have {x | a' < x} ∈ nhds a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ nhds a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ nhds a ⊓ principal s, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', le_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' _ $ mem_image_of_mem _ hx) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_lub (f '' s) b := @is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_lub ha hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) (sc : is_closed s): a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_glb ha hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) (sc : is_closed s): a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma bdd_below_of_compact {α : Type u} [topological_space α] [linear_order α] [ordered_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases @compact_elim_finite_subcover_image α _ _ _ s (λ x, {b | x < b}) hs (λ x _, is_open_lt continuous_const continuous_id) _ with ⟨t, st, ft, ht⟩, { refine H ((bdd_below_finite ft).imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC _ hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma bdd_above_of_compact {α : Type u} [topological_space α] [linear_order α] [orderable_topology α] : Π [nonempty α] {s : set α}, compact s → bdd_above s := @bdd_below_of_compact (order_dual α) _ _ _ end order_topology section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] [complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Sup s ∈ closure s := mem_closure_of_is_lub is_lub_Sup hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Inf s ∈ closure s := mem_closure_of_is_glb is_glb_Inf hs lemma Sup_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed is_lub_Sup hs hc lemma Inf_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed is_glb_Inf hs hc /-- A continuous monotone function sends supremum to supremum for nonempty sets. -/ lemma Sup_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_iff_Sup_eq.1 (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Cf xy) is_lub_Sup hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending bot to bot sends supremum to supremum. -/ lemma Sup_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (fbot : f ⊥ = ⊥) {s : set α} : f (Sup s) = Sup (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Sup_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed supremum to indexed supremum. -/ lemma supr_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (supr g) = supr (f ∘ g) := by rw [supr, Sup_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum for nonempty sets. -/ lemma Inf_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Inf s) = Inf (f '' s) := (is_glb_iff_Inf_eq.1 (is_glb_of_is_glb_of_tendsto (λ x hx y hy xy, Cf xy) is_glb_Inf hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending top to top sends infimum to infimum. -/ lemma Inf_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (ftop : f ⊤ = ⊤) {s : set α} : f (Inf s) = Inf (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Inf_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed infimum to indexed infimum. -/ lemma infi_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (infi g) = infi (f ∘ g) := by rw [infi, Inf_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] [conditionally_complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma cSup_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma cSup_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma cInf_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- A continuous monotone function sends supremum to supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma cSup_of_cSup_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine (is_lub_iff_eq_of_is_lub _).1 (is_lub_cSup (mt image_eq_empty.1 ne) (bdd_above_of_bdd_above_of_monotone Cf H)), refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Cf xy) (is_lub_cSup ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed supremum to indexed supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma csupr_of_csupr_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_above (range g)) : f (supr g) = supr (f ∘ g) := by rw [supr, cSup_of_cSup_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cInf_of_cInf_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := begin refine (is_glb_iff_eq_of_is_glb _).1 (is_glb_cInf (mt image_eq_empty.1 ne) (bdd_below_of_bdd_below_of_monotone Cf H)), refine is_glb_of_is_glb_of_tendsto (λx hx y hy xy, Cf xy) (is_glb_cInf ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cinfi_of_cinfi_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_below (range g)): f (infi g) = infi (f ∘ g) := by rw [infi, cInf_of_cInf_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma exists_forall_le_of_compact_of_continuous {α : Type u} [topological_space α] (f : α → β) (hf : continuous f) (s : set α) (hs : compact s) (ne_s : s ≠ ∅) : ∃x∈s, ∀y∈s, f x ≤ f y := begin have C : compact (f '' s) := compact_image hs hf, haveI := has_Inf_to_nonempty β, have B : bdd_below (f '' s) := bdd_below_of_compact C, have : Inf (f '' s) ∈ f '' s := cInf_mem_of_is_closed (mt image_eq_empty.1 ne_s) (closed_of_compact _ C) B, rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩, exact ⟨x, xs, λ y hy, hx.symm ▸ cInf_le B ⟨_, hy, rfl⟩⟩ end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma exists_forall_ge_of_compact_of_continuous {α : Type u} [topological_space α] : ∀ f : α → β, continuous f → ∀ s : set α, compact s → s ≠ ∅ → ∃x∈s, ∀y∈s, f y ≤ f x := @exists_forall_le_of_compact_of_continuous (order_dual β) _ _ _ _ _ end conditionally_complete_linear_order section liminf_limsup section ordered_topology variables [semilattice_sup α] [topological_space α] [orderable_topology α] lemma is_bounded_le_nhds (a : α) : (nhds a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, show {x : α | x ≤ a} ∈ nhds a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma is_bounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≤) u := is_bounded_of_le h (is_bounded_le_nhds a) lemma is_cobounded_ge_nhds (a : α) : (nhds a).is_cobounded (≥) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_le_nhds a) lemma is_cobounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≥) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_le_of_tendsto h) end ordered_topology section ordered_topology variables [semilattice_inf α] [topological_space α] [orderable_topology α] lemma is_bounded_ge_nhds (a : α) : (nhds a).is_bounded (≥) := match forall_le_or_exists_lt_inf a with | or.inl h := ⟨a, show {x : α | a ≤ x} ∈ nhds a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, le_mem_nhds hb⟩ end lemma is_bounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≥) u := is_bounded_of_le h (is_bounded_ge_nhds a) lemma is_cobounded_le_nhds (a : α) : (nhds a).is_cobounded (≤) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_ge_nhds a) lemma is_cobounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≤) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_ge_of_tendsto h) end ordered_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : {a | a < b} ∈ f := let ⟨c, (h : {a : α | a ≤ c} ∈ f), hcb⟩ := exists_lt_of_cInf_lt (ne_empty_iff_exists_mem.2 h) l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → f.Liminf > b → {a | a > b} ∈ f := @lt_mem_sets_of_Limsup_lt (order_dual α) _ _ _ /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ nhds a := tendsto_orderable.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (nhds a) = a := cInf_intro (ne_empty_iff_exists_mem.2 $ is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ nhds a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ nhds a), c < b, from match dense_or_discrete hba with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (nhds a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (nhds a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a), have hb_le : is_bounded (≤) f, from is_bounded_of_le h (is_bounded_le_nhds a), le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hf hb_le hb_ge ... ≤ (nhds a).Limsup : Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (nhds a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) (is_cobounded_of_is_bounded hf hb_le)) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α}, f ≠ ⊥ → f ≤ nhds a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (h : liminf f u = a ∧ limsup f u = a) : tendsto u f (nhds a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot h.2 h.1 /-- If a function has a limit, then its limsup coincides with its limit-/ theorem limsup_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : limsup f u = a := Limsup_eq_of_le_nhds (map_ne_bot hf) h /-- If a function has a limit, then its liminf coincides with its limit-/ theorem liminf_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : liminf f u = a := Liminf_eq_of_le_nhds (map_ne_bot hf) h end complete_linear_order end liminf_limsup end orderable_topology lemma orderable_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_comm_group α] [topological_space α] (h_nhds : ∀a:α, nhds a = (⨅r>0, principal {b | abs (a - b) < r})) : orderable_topology α := orderable_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a + -b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, -sub_eq_add_neg, (sub_eq_add_neg _ _).symm, sub_lt, lt_sub_iff_add_lt, and_comm, sub_lt_iff_lt_add']), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : monotone f) : tendsto f at_top (nhds (⨆i, f i)) := tendsto_orderable.2 $ and.intro (assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩) (assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha)) lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (nhds (⨅i, f i)) := @tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (nhds a) → supr f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_supr_nat f hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (nhds a) → infi f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_infi_nat f hf)
8077aa868770f3533159e4c627abf3d560622e7b
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/polynomial/default.lean
b543a6f26b46bd838c97599632ebf34a424444f1
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
141
lean
import data.polynomial.algebra_map import data.polynomial.field_division import data.polynomial.derivative import data.polynomial.identities
d5840e0f54edaf713e611cb2b4dad7b40d40fcc3
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world8/level13.lean
74a969ab1f811d131a79cf5ee1fd6876b1b5f24f
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
657
lean
import mynat.definition import mynat.add import world8.level4 namespace mynat theorem ne_succ_self (n : mynat) : n ≠ succ(n) := begin [nat_num_game] induction n with d hd, { exact zero_ne_succ 0, }, { intro h, apply hd, apply succ_inj, exact h, }, end -- theorem ne_succ_self (n : mynat) : n ≠ succ(n) := -- begin [nat_num_game] -- induction n with d hd, -- { -- exact zero_ne_succ 0, -- }, -- { -- rw ne_from_not_eq at hd, -- rw ← eq_iff_succ_eq_succ at hd, -- rw ← ne_from_not_eq at hd, -- exact hd, -- }, -- end end mynat
e9cbf56882cc6d5c765062e2c260c32823824ac1
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Parser/Syntax.lean
1560f9701bd583196bd1fcaacb75b36e67972dba
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
6,331
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Command namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtinSyntaxParser ``Category.stx .both registerBuiltinDynamicParserAttribute `stxParser `stx builtin_initialize registerBuiltinParserAttribute `builtinPrecParser ``Category.prec .both registerBuiltinDynamicParserAttribute `precParser `prec @[inline] def precedenceParser (rbp : Nat := 0) : Parser := categoryParser `prec rbp @[inline] def syntaxParser (rbp : Nat := 0) : Parser := categoryParser `stx rbp def «precedence» := leading_parser ":" >> precedenceParser maxPrec def optPrecedence := optional (atomic «precedence») namespace Syntax @[builtinPrecParser] def numPrec := checkPrec maxPrec >> numLit @[builtinSyntaxParser] def paren := leading_parser "(" >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def cat := leading_parser ident >> optPrecedence @[builtinSyntaxParser] def unary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def binary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ", " >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def sepBy := leading_parser "sepBy(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")" @[builtinSyntaxParser] def sepBy1 := leading_parser "sepBy1(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")" @[builtinSyntaxParser] def atom := leading_parser strLit @[builtinSyntaxParser] def nonReserved := leading_parser "&" >> strLit end Syntax namespace Term @[builtinTermParser] def stx.quot : Parser := leading_parser "`(stx|" >> incQuotDepth syntaxParser >> ")" @[builtinTermParser] def prec.quot : Parser := leading_parser "`(prec|" >> incQuotDepth precedenceParser >> ")" @[builtinTermParser] def prio.quot : Parser := leading_parser "`(prio|" >> incQuotDepth priorityParser >> ")" end Term namespace Command def namedName := leading_parser (atomic ("(" >> nonReservedSymbol "name") >> " := " >> ident >> ")") def optNamedName := optional namedName def «prefix» := leading_parser "prefix" def «infix» := leading_parser "infix" def «infixl» := leading_parser "infixl" def «infixr» := leading_parser "infixr" def «postfix» := leading_parser "postfix" def mixfixKind := «prefix» <|> «infix» <|> «infixl» <|> «infixr» <|> «postfix» @[builtinCommandParser] def «mixfix» := leading_parser optional docComment >> optional Term.«attributes» >> Term.attrKind >> mixfixKind >> precedence >> optNamedName >> optNamedPrio >> ppSpace >> strLit >> darrow >> termParser -- NOTE: We use `suppressInsideQuot` in the following parsers because quotations inside them are evaluated in the same stage and -- thus should be ignored when we use `checkInsideQuot` to prepare the next stage for a builtin syntax change def identPrec := leading_parser ident >> optPrecedence def optKind : Parser := optional ("(" >> nonReservedSymbol "kind" >> ":=" >> ident >> ")") def notationItem := ppSpace >> withAntiquot (mkAntiquot "notationItem" `Lean.Parser.Command.notationItem) (strLit <|> identPrec) @[builtinCommandParser] def «notation» := leading_parser optional docComment >> optional Term.«attributes» >> Term.attrKind >> "notation" >> optPrecedence >> optNamedName >> optNamedPrio >> many notationItem >> darrow >> termParser @[builtinCommandParser] def «macro_rules» := suppressInsideQuot (leading_parser optional docComment >> optional Term.«attributes» >> Term.attrKind >> "macro_rules" >> optKind >> Term.matchAlts) @[builtinCommandParser] def «syntax» := leading_parser optional docComment >> optional Term.«attributes» >> Term.attrKind >> "syntax " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 (syntaxParser argPrec) >> " : " >> ident @[builtinCommandParser] def syntaxAbbrev := leading_parser optional docComment >> "syntax " >> ident >> " := " >> many1 syntaxParser def catBehaviorBoth := leading_parser nonReservedSymbol "both" def catBehaviorSymbol := leading_parser nonReservedSymbol "symbol" def catBehavior := optional ("(" >> nonReservedSymbol "behavior" >> " := " >> (catBehaviorBoth <|> catBehaviorSymbol) >> ")") @[builtinCommandParser] def syntaxCat := leading_parser optional docComment >> "declare_syntax_cat " >> ident >> catBehavior def macroArg := leading_parser optional (atomic (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> syntaxParser argPrec def macroRhs (quotP : Parser) : Parser := leading_parser "`(" >> incQuotDepth quotP >> ")" <|> withPosition termParser def macroTailTactic : Parser := atomic (" : " >> identEq "tactic") >> darrow >> macroRhs Tactic.seq1 def macroTailCommand : Parser := atomic (" : " >> identEq "command") >> darrow >> macroRhs (many1Unbox commandParser) def macroTailDefault : Parser := atomic (" : " >> ident) >> darrow >> macroRhs (categoryParserOfStack 2) def macroTail := leading_parser macroTailTactic <|> macroTailCommand <|> macroTailDefault @[builtinCommandParser] def «macro» := leading_parser suppressInsideQuot (optional docComment >> optional Term.«attributes» >> Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 macroArg >> macroTail) @[builtinCommandParser] def «elab_rules» := leading_parser suppressInsideQuot (optional docComment >> optional Term.«attributes» >> Term.attrKind >> "elab_rules" >> optKind >> optional (" : " >> ident) >> optional (" <= " >> ident) >> Term.matchAlts) def elabArg := macroArg def elabTail := leading_parser atomic (" : " >> ident >> optional (" <= " >> ident)) >> darrow >> withPosition termParser @[builtinCommandParser] def «elab» := leading_parser suppressInsideQuot (optional docComment >> optional Term.«attributes» >> Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 elabArg >> elabTail) end Command end Parser end Lean
e78f3dc6e3b35ff626d3892e9d6de84f618ceda3
2de8c1580f92bb6c28b60135f589fe9d0513faba
/src/noetherian.lean
d080360043dd22206d1d8abe510c144dd3ebd974
[]
no_license
FCL-lean/verification
44a52e40ab78b18654b8d61bb55c2c912a40d2f4
be02c698c0ca78b18762e3fe7749cdc72a55d197
refs/heads/master
1,585,960,207,309
1,560,259,990,000
1,560,259,990,000
155,650,137
0
0
null
1,541,039,704,000
1,541,038,972,000
Lean
UTF-8
Lean
false
false
1,563
lean
import data.mv_polynomial ring_theory.noetherian ring_theory.polynomial section division_ring variables {α : Type*} [decidable_eq α] [division_ring α] lemma submodule_ne_zero {s : submodule α α} (h : ¬ ↑s = ({0} : set α)) : (1 : α) ∈ s := begin have : ¬ ∀ x ∈ s, x = (0 : α) := λ H, h (begin ext x, refine ⟨by simpa using H x, λ hx, by simp at hx; simp [hx]⟩, end), letI := classical.dec, simp [not_forall, not_imp] at this, rcases this with ⟨x, hx₁, hx₂⟩, simpa [hx₂] using s.smul x⁻¹ hx₁, end instance division_ring_is_noetherian : is_noetherian_ring α := { noetherian := λ s, begin letI := classical.dec, unfold submodule.fg, by_cases s = ⊥, {refine ⟨{0}, by simp [h, submodule.span_eq_bot]⟩}, { refine ⟨{1}, _⟩, ext y, refine ⟨λ _, by simp [submodule.ext'_iff.symm] at h; simpa using s.smul y (submodule_ne_zero h), λ _, by simp [submodule.mem_span]; from λ p hp, by simpa using p.smul _ hp⟩, } end } end division_ring open finsupp namespace mv_polynomial variables {σ : Type*} {α : Type*} [decidable_eq σ] [decidable_eq α] variables [fintype σ] [comm_ring α] [is_noetherian_ring α] lemma ideal_wf : well_founded ((>) : ideal (mv_polynomial σ α) → ideal (mv_polynomial σ α) → Prop) := is_noetherian_iff_well_founded.1 is_noetherian_ring_mv_polynomial_of_fintype end mv_polynomial
de731e19fa0a4ecd663f3cae3b0f8a2f42721cdb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Group/images.lean
38ddb704cead06d92576f8d56824ff54f616c9b4
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,266
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.category.Group.abelian import category_theory.limits.shapes.images /-! # The category of commutative additive groups has images. Note that we don't need to register any of the constructions here as instances, because we get them from the fact that `AddCommGroup` is an abelian category. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup -- Note that because `injective_of_mono` is currently only proved in `Type 0`, -- we restrict to the lowest universe here for now. variables {G H : AddCommGroup.{0}} (f : G ⟶ H) local attribute [ext] subtype.ext_val section -- implementation details of `has_image` for AddCommGroup; use the API, not these /-- the image of a morphism in AddCommGroup is just the bundling of `add_monoid_hom.range f` -/ def image : AddCommGroup := AddCommGroup.of (add_monoid_hom.range f) /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := f.range.subtype instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective /-- the corestriction map to the image -/ def factor_thru_image : G ⟶ image f := f.range_restrict lemma image.fac : factor_thru_image f ≫ image.ι f = f := by { ext, refl, } local attribute [simp] image.fac variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := { to_fun := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I), map_zero' := begin haveI := F'.m_mono, apply injective_of_mono F'.m, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, add_monoid_hom.map_zero], exact (classical.indefinite_description (λ y, f y = 0) _).2, end, map_add' := begin intros x y, haveI := F'.m_mono, apply injective_of_mono F'.m, rw [add_monoid_hom.map_add], change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _, rw [F'.fac], rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, refl, end, } lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := factor_thru_image f } /-- the factorisation of any morphism in AddCommGroup through a mono has the universal property of the image. -/ noncomputable def is_image : is_image (mono_factorisation f) := { lift := image.lift, lift_fac' := image.lift_fac } /-- The categorical image of a morphism in `AddCommGroup` agrees with the usual group-theoretical range. -/ noncomputable def image_iso_range {G H : AddCommGroup.{0}} (f : G ⟶ H) : limits.image f ≅ AddCommGroup.of f.range := is_image.iso_ext (image.is_image f) (is_image f) end AddCommGroup
a0aea2488b5d135fbd2d912d0c2d5e502f458cf7
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world8/level11.lean
bdd7b7445fd945476ca68b6a4b4284cb8ab889f0
[ "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
569
lean
import mynat.definition -- hide import mynat.add -- hide import game.world8.level10 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 11: `add_right_eq_zero` We just proved `add_left_eq_zero (a b : mynat) : a + b = 0 → b = 0`. Hopefully `add_right_eq_zero` shouldn't be too hard now. -/ /- Lemma If $a$ and $b$ are natural numbers such that $$ a + b = 0, $$ then $a = 0$. -/ lemma add_right_eq_zero {a b : mynat} : a + b = 0 → a = 0 := begin [nat_num_game] intro H, rw add_comm at H, exact add_left_eq_zero H, end end mynat -- hide
843ed8e118e0c75d5a77353adec0044844db67b7
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/homology/exact.lean
6f1b0154b59ecd9d017da00a01f10e947d1f038f
[ "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
9,467
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.homology.image_to_kernel /-! # Exact sequences In a category with zero morphisms, images, and equalizers we say that `f : A ⟶ B` and `g : B ⟶ C` are exact if `f ≫ g = 0` and the natural map `image f ⟶ kernel g` is an epimorphism. In any preadditive category this is equivalent to the homology at `B` vanishing. However in general it is weaker than other reasonable definitions of exactness, particularly that 1. the inclusion map `image.ι f` is a kernel of `g` or 2. `image f ⟶ kernel g` is an isomorphism or 3. `image_subobject f = kernel_subobject f`. However when the category is abelian, these all become equivalent; these results are found in `category_theory/abelian/exact.lean`. # Main results * Suppose that cokernels exist and that `f` and `g` are exact. If `s` is any kernel fork over `g` and `t` is any cokernel cofork over `f`, then `fork.ι s ≫ cofork.π t = 0`. * Precomposing the first morphism with an epimorphism retains exactness. Postcomposing the second morphism with a monomorphism retains exactness. * If `f` and `g` are exact and `i` is an isomorphism, then `f ≫ i.hom` and `i.inv ≫ g` are also exact. # Future work * Short exact sequences, split exact sequences, the splitting lemma (maybe only for abelian categories?) * Two adjacent maps in a chain complex are exact iff the homology vanishes -/ universes v u open category_theory open category_theory.limits variables {V : Type u} [category.{v} V] variables [has_images V] namespace category_theory /-- Two morphisms `f : A ⟶ B`, `g : B ⟶ C` are called exact if `w : f ≫ g = 0` and the natural map `image_to_kernel f g w : image_subobject f ⟶ kernel_subobject g` is an epimorphism. In any preadditive category, this is equivalent to `w : f ≫ g = 0` and `homology f g w ≅ 0`. In an abelian category, this is equivalent to `image_to_kernel f g w` being an isomorphism, and hence equivalent to the usual definition, `image_subobject f = kernel_subobject g`. -/ -- One nice feature of this definition is that we have -- `epi f → exact g h → exact (f ≫ g) h` and `exact f g → mono h → exact f (g ≫ h)`, -- which do not necessarily hold in a non-abelian category with the usual definition of `exact`. class exact [has_zero_morphisms V] [has_kernels V] {A B C : V} (f : A ⟶ B) (g : B ⟶ C) : Prop := (w : f ≫ g = 0) (epi : epi (image_to_kernel f g w)) attribute [instance] exact.epi attribute [simp, reassoc] exact.w section variables [has_zero_object V] [preadditive V] [has_kernels V] [has_cokernels V] open_locale zero_object /-- In any preadditive category, composable morphisms `f g` are exact iff they compose to zero and the homology vanishes. -/ lemma preadditive.exact_iff_homology_zero {A B C : V} (f : A ⟶ B) (g : B ⟶ C) : exact f g ↔ ∃ w : f ≫ g = 0, nonempty (homology f g w ≅ 0) := ⟨λ h, ⟨h.w, ⟨cokernel.of_epi _⟩⟩, λ h, begin obtain ⟨w, ⟨i⟩⟩ := h, exact ⟨w, preadditive.epi_of_cokernel_zero ((cancel_mono i.hom).mp (by ext))⟩, end⟩ end section variables [has_zero_morphisms V] [has_kernels V] lemma comp_eq_zero_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (p : image_subobject f = kernel_subobject g) : f ≫ g = 0 := begin rw [←image_subobject_arrow_comp f, category.assoc], convert comp_zero, rw p, simp, end lemma image_to_kernel_is_iso_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (p : image_subobject f = kernel_subobject g) : is_iso (image_to_kernel f g (comp_eq_zero_of_image_eq_kernel f g p)) := begin refine ⟨⟨subobject.of_le _ _ p.ge, _⟩⟩, dsimp [image_to_kernel], simp only [subobject.of_le_comp_of_le, subobject.of_le_refl], simp, end -- We'll prove the converse later, when `V` is abelian. lemma exact_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (p : image_subobject f = kernel_subobject g) : exact f g := { w := comp_eq_zero_of_image_eq_kernel f g p, epi := begin haveI := image_to_kernel_is_iso_of_image_eq_kernel f g p, apply_instance, end } end variables {A B C D : V} {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D} local attribute [instance] epi_comp section variables [has_zero_morphisms V] [has_equalizers V] instance exact_comp_hom_inv_comp [exact f g] (i : B ≅ D) : exact (f ≫ i.hom) (i.inv ≫ g) := begin refine ⟨by simp, _⟩, rw image_to_kernel_comp_hom_inv_comp, apply_instance, end instance exact_comp_inv_hom_comp [exact f g] (i : D ≅ B) : exact (f ≫ i.inv) (i.hom ≫ g) := category_theory.exact_comp_hom_inv_comp i.symm lemma exact_comp_hom_inv_comp_iff (i : B ≅ D) : exact (f ≫ i.hom) (i.inv ≫ g) ↔ exact f g := begin refine ⟨_, by { introI, apply_instance }⟩, introI, have : exact ((f ≫ i.hom) ≫ i.inv) (i.hom ≫ i.inv ≫ g) := infer_instance, simpa using this end lemma exact_epi_comp [exact g h] [epi f] : exact (f ≫ g) h := begin refine ⟨by simp, _⟩, rw image_to_kernel_comp_left, apply_instance, end @[simp] lemma exact_iso_comp [is_iso f] : exact (f ≫ g) h ↔ exact g h := ⟨λ w, by { rw ←is_iso.inv_hom_id_assoc f g, exactI exact_epi_comp, }, λ w, by exactI exact_epi_comp⟩ lemma exact_comp_mono [exact f g] [mono h] : exact f (g ≫ h) := begin refine ⟨by simp, _⟩, rw image_to_kernel_comp_right f g h exact.w, apply_instance, end @[simp] lemma exact_comp_iso [is_iso h] : exact f (g ≫ h) ↔ exact f g := ⟨λ w, begin rw [←category.comp_id g, ←is_iso.hom_inv_id h, ←category.assoc], exactI exact_comp_mono, end, λ w, by exactI exact_comp_mono⟩ lemma exact_kernel_subobject_arrow : exact (kernel_subobject f).arrow f := begin refine ⟨by simp, _⟩, apply @is_iso.epi_of_iso _ _ _ _ _ _, exact ⟨⟨factor_thru_image_subobject _, by { ext, simp, }, by { ext, simp, }⟩⟩, end lemma exact_kernel_ι : exact (kernel.ι f) f := by { rw [←kernel_subobject_arrow', exact_iso_comp], exact exact_kernel_subobject_arrow } instance [exact f g] : epi (factor_thru_kernel_subobject g f (by simp)) := begin rw ←factor_thru_image_subobject_comp_image_to_kernel, apply epi_comp, end variables (A) lemma kernel_subobject_arrow_eq_zero_of_exact_zero_left [exact (0 : A ⟶ B) g] : (kernel_subobject g).arrow = 0 := begin rw [←cancel_epi (image_to_kernel (0 : A ⟶ B) g exact.w), ←cancel_epi (factor_thru_image_subobject (0 : A ⟶ B))], simp end lemma kernel_ι_eq_zero_of_exact_zero_left [exact (0 : A ⟶ B) g] : kernel.ι g = 0 := by { rw ←kernel_subobject_arrow', simp [kernel_subobject_arrow_eq_zero_of_exact_zero_left A], } lemma exact_zero_left_of_mono [has_zero_object V] [mono g] : exact (0 : A ⟶ B) g := ⟨by simp, image_to_kernel_epi_of_zero_of_mono _⟩ end section has_cokernels variables [has_zero_morphisms V] [has_equalizers V] [has_cokernels V] (f g) @[simp, reassoc] lemma kernel_comp_cokernel [exact f g] : kernel.ι g ≫ cokernel.π f = 0 := begin rw [←kernel_subobject_arrow', category.assoc], convert comp_zero, apply zero_of_epi_comp (image_to_kernel f g exact.w) _, rw [image_to_kernel_arrow_assoc, ←image_subobject_arrow, category.assoc, ←iso.eq_inv_comp], ext, simp, end lemma comp_eq_zero_of_exact [exact f g] {X Y : V} {ι : X ⟶ B} (hι : ι ≫ g = 0) {π : B ⟶ Y} (hπ : f ≫ π = 0) : ι ≫ π = 0 := by rw [←kernel.lift_ι _ _ hι, ←cokernel.π_desc _ _ hπ, category.assoc, kernel_comp_cokernel_assoc, zero_comp, comp_zero] @[simp, reassoc] lemma fork_ι_comp_cofork_π [exact f g] (s : kernel_fork g) (t : cokernel_cofork f) : fork.ι s ≫ cofork.π t = 0 := comp_eq_zero_of_exact f g (kernel_fork.condition s) (cokernel_cofork.condition t) end has_cokernels section variables [has_zero_object V] open_locale zero_object section variables [has_zero_morphisms V] [has_kernels V] instance exact_of_zero {A C : V} (f : A ⟶ 0) (g : 0 ⟶ C) : exact f g := begin obtain rfl : f = 0 := by ext, obtain rfl : g = 0 := by ext, fsplit, { simp, }, { exact image_to_kernel_epi_of_zero_of_mono 0, }, end instance exact_zero_mono {B C : V} (f : B ⟶ C) [mono f] : exact (0 : (0 ⟶ B)) f := ⟨by simp, infer_instance⟩ instance exact_epi_zero {A B : V} (f : A ⟶ B) [epi f] : exact f (0 : (B ⟶ 0)) := ⟨by simp, infer_instance⟩ end section variables [preadditive V] lemma mono_iff_exact_zero_left [has_kernels V]{B C : V} (f : B ⟶ C) : mono f ↔ exact (0 : (0 ⟶ B)) f := ⟨λ h, by { resetI, apply_instance, }, λ h, preadditive.mono_of_kernel_iso_zero ((kernel_subobject_iso f).symm ≪≫ iso_zero_of_epi_zero (by simpa using h.epi))⟩ lemma epi_iff_exact_zero_right [has_equalizers V] {A B : V} (f : A ⟶ B) : epi f ↔ exact f (0 : (B ⟶ 0)) := ⟨λ h, by { resetI, apply_instance, }, λ h, begin have e₁ := h.epi, rw image_to_kernel_zero_right at e₁, have e₂ : epi (((image_subobject f).arrow ≫ inv (kernel_subobject 0).arrow) ≫ (kernel_subobject 0).arrow) := @epi_comp _ _ _ _ _ _ e₁ _ _, rw [category.assoc, is_iso.inv_hom_id, category.comp_id] at e₂, rw [←image_subobject_arrow] at e₂, resetI, haveI : epi (image.ι f) := epi_of_epi (image_subobject_iso f).hom (image.ι f), apply epi_of_epi_image, end⟩ end end end category_theory
f6e7b9488c8d459125e0c1d151718e62631011be
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/abelian/abelian.lean
f52b1e748b24791e81315c0c9d7a73c6bde287bc
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,588
lean
-- -- Copyright (c) 2017 Scott Morrison. All rights reserved. -- -- Released under Apache 2.0 license as described in the file LICENSE. -- -- Authors: Scott Morrison -- import category_theory.abelian.monic -- import category_theory.universal.monic -- import category_theory.universal.kernels -- open category_theory -- open category_theory.limits -- open category_theory.universal.monic -- namespace category_theory.abelian -- -- This is the def of abelian from Etingof's "Tensor categories" -- universes u v -- -- structure KernelImageCokernelDecomposition -- -- {C : Type u} [category.{u v} C] [has_zero_object.{u v} C] [has_kernels.{u v} C] [has_cokernels.{u v} C] -- -- {X Y : C} (f : X ⟶ Y) := -- -- (image_well_defined : cokernel (kernel.map f) ≅ kernel (cokernel.map f)) -- -- (composition_is_morphism : (cokernel (kernel.map f)).map ≫ image_well_defined.hom ≫ (kernel (cokernel.map f)).map = f) -- -- class Abelian {C : Type u} [category.{u v} C] [has_zero_object.{u v} C] [has_kernels.{u v} C] [has_cokernels.{u v} C] := -- -- (decomposition : ∀ {X Y : C} (f : X ⟶ Y), KernelImageCokernelDecomposition f) -- -- This is the usual definition -- class Abelian' {C : Type u} [category.{u v} C] [has_zero_object.{u v} C] := -- (monics_are_regular : ∀ {X Y : C} {f : X ⟶ Y} (m : mono f), regular_mono f) -- (epics_are_regular : ∀ {X Y : C} {f : X ⟶ Y} (m : epi f ), regular_epi f) -- -- PROJECT show these definitions are equivalent -- -- PROJECT define short and long exact sequences, cohomology? -- end category_theory.abelian
8b08b6f89262a2c80982b4f6ea0d4721127dcfb1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/finsupp_vector_space_auto.lean
4afb003c01ad2d41747e911e9d6e7c4734230e92
[]
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
4,838
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `ι →₀ β`. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.default import Mathlib.linear_algebra.dimension import Mathlib.linear_algebra.direct_sum.finsupp import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 u v w namespace Mathlib namespace finsupp theorem linear_independent_single {R : Type u_1} {M : Type u_2} {ι : Type u_3} [ring R] [add_comm_group M] [module R M] {φ : ι → Type u_4} {f : (ι : ι) → φ ι → M} (hf : ∀ (i : ι), linear_independent R (f i)) : linear_independent R fun (ix : sigma fun (i : ι) => φ i) => single (sigma.fst ix) (f (sigma.fst ix) (sigma.snd ix)) := sorry theorem is_basis_single {R : Type u_1} {M : Type u_2} {ι : Type u_3} [ring R] [add_comm_group M] [module R M] {φ : ι → Type u_4} (f : (ι : ι) → φ ι → M) (hf : ∀ (i : ι), is_basis R (f i)) : is_basis R fun (ix : sigma fun (i : ι) => φ i) => single (sigma.fst ix) (f (sigma.fst ix) (sigma.snd ix)) := sorry theorem is_basis_single_one {R : Type u_1} {ι : Type u_3} [ring R] : is_basis R fun (i : ι) => single i 1 := sorry /-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/ theorem is_basis.tensor_product {R : Type u_1} {M : Type u_2} {N : Type u_3} {ι : Type u_4} {κ : Type u_5} [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] {b : ι → M} (hb : is_basis R b) {c : κ → N} (hc : is_basis R c) : is_basis R fun (i : ι × κ) => tensor_product.tmul R (b (prod.fst i)) (c (prod.snd i)) := sorry theorem dim_eq {K : Type u} {V : Type v} {ι : Type v} [field K] [add_comm_group V] [vector_space K V] : vector_space.dim K (ι →₀ V) = cardinal.mk ι * vector_space.dim K V := sorry end finsupp /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ theorem equiv_of_dim_eq_lift_dim {K : Type u} {V : Type v} {V' : Type w} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (h : cardinal.lift (vector_space.dim K V) = cardinal.lift (vector_space.dim K V')) : Nonempty (linear_equiv K V V') := sorry /-- Two `K`-vector spaces are equivalent if their dimension is the same. -/ def equiv_of_dim_eq_dim {K : Type u} {V₁ : Type v} {V₂ : Type v} [field K] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] (h : vector_space.dim K V₁ = vector_space.dim K V₂) : linear_equiv K V₁ V₂ := Classical.choice sorry /-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/ def fin_dim_vectorspace_equiv {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (n : ℕ) (hn : vector_space.dim K V = ↑n) : linear_equiv K V (fin n → K) := Classical.choice sorry theorem eq_bot_iff_dim_eq_zero {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (p : submodule K V) (h : vector_space.dim K ↥p = 0) : p = ⊥ := let e : linear_equiv K ↥p ↥⊥ := equiv_of_dim_eq_dim (eq.mpr (id (Eq._oldrec (Eq.refl (vector_space.dim K ↥p = vector_space.dim K ↥⊥)) dim_bot)) h); linear_equiv.eq_bot_of_equiv p e theorem injective_of_surjective {K : Type u} {V₁ : Type v} {V₂ : Type v} [field K] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] (f : linear_map K V₁ V₂) (hV₁ : vector_space.dim K V₁ < cardinal.omega) (heq : vector_space.dim K V₂ = vector_space.dim K V₁) (hf : linear_map.range f = ⊤) : linear_map.ker f = ⊥ := sorry theorem cardinal_mk_eq_cardinal_mk_field_pow_dim {K : Type u} {V : Type u} [field K] [add_comm_group V] [vector_space K V] (h : vector_space.dim K V < cardinal.omega) : cardinal.mk V = cardinal.mk K ^ vector_space.dim K V := sorry theorem cardinal_lt_omega_of_dim_lt_omega {K : Type u} {V : Type u} [field K] [add_comm_group V] [vector_space K V] [fintype K] (h : vector_space.dim K V < cardinal.omega) : cardinal.mk V < cardinal.omega := eq.mpr (id (Eq._oldrec (Eq.refl (cardinal.mk V < cardinal.omega)) (cardinal_mk_eq_cardinal_mk_field_pow_dim h))) (cardinal.power_lt_omega (iff.mpr cardinal.lt_omega_iff_fintype (Nonempty.intro infer_instance)) h) end Mathlib
fad91c910a9fa38bb91c40959e2e2c75cf689a03
1446f520c1db37e157b631385707cc28a17a595e
/stage0/src/Init/Lean/Util/WHNF.lean
9a3ad4c88cd1563994f9c0323ccde6543919678c
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,545
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Declaration import Init.Lean.LocalContext namespace Lean namespace WHNF /- =========================== Smart unfolding support =========================== -/ def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (n : Name) : Name := mkNameStr n smartUnfoldingSuffix /- =========================== Helper functions =========================== -/ @[inline] def matchConstAux {α : Type} {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (e : Expr) (failK : Unit → m α) (k : ConstantInfo → List Level → m α) : m α := match e with | Expr.const name lvls _ => do (some cinfo) ← getConst name | failK (); k cinfo lvls | _ => failK () /- =========================== Helper functions for reducing recursors =========================== -/ private def getFirstCtor {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (d : Name) : m (Option Name) := do some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConst d | pure none; pure (some ctor) private def mkNullaryCtor {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (type : Expr) (nparams : Nat) : m (Option Expr) := match type.getAppFn with | Expr.const d lvls _ => do (some ctor) ← getFirstCtor getConst d | pure none; pure $ mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => pure none private def toCtorIfLit : Expr → Expr | Expr.lit (Literal.natVal v) _ => if v == 0 then mkConst `Nat.zero else mkApp (mkConst `Nat.succ) (mkNatLit (v-1)) | e => e private def getRecRuleFor (rec : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ _ => rec.rules.find? $ fun r => r.ctor == fn | _ => none @[specialize] private def toCtorWhenK {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (whnf : Expr → m Expr) (inferType : Expr → m Expr) (isDefEq : Expr → Expr → m Bool) (rec : RecursorVal) (major : Expr) : m (Option Expr) := do majorType ← inferType major; majorType ← whnf majorType; let majorTypeI := majorType.getAppFn; if !majorTypeI.isConstOf rec.getInduct then pure none else if majorType.hasExprMVar && majorType.getAppArgs.anyFrom rec.nparams Expr.hasExprMVar then pure none else do (some newCtorApp) ← mkNullaryCtor getConst majorType rec.nparams | pure none; newType ← inferType newCtorApp; defeq ← isDefEq majorType newType; pure $ if defeq then newCtorApp else none /-- Auxiliary function for reducing recursor applications. -/ @[specialize] def reduceRec {α} {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (whnf : Expr → m Expr) (inferType : Expr → m Expr) (isDefEq : Expr → Expr → m Bool) (rec : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → m α) (successK : Expr → m α) : m α := let majorIdx := rec.getMajorIdx; if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩; major ← whnf major; major ← if !rec.k then pure major else do { newMajor ← toCtorWhenK getConst whnf inferType isDefEq rec major; pure (newMajor.getD major) }; let major := toCtorIfLit major; match getRecRuleFor rec major with | some rule => let majorArgs := major.getAppArgs; if recLvls.length != rec.lparams.length then failK () else let rhs := rule.rhs.instantiateLevelParams rec.lparams recLvls; -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (rec.nparams+rec.nmotives+rec.nminors) recArgs; /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields; let rhs := mkAppRange rhs nparams majorArgs.size majorArgs; let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs; successK rhs | none => failK () else failK () @[specialize] def isRecStuck {m : Type → Type} [Monad m] (whnf : Expr → m Expr) (isStuck : Expr → m (Option Expr)) (rec : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : m (Option Expr) := if rec.k then -- TODO: improve this case pure none else do let majorIdx := rec.getMajorIdx; if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩; major ← whnf major; isStuck major else pure none /- =========================== Helper functions for reducing Quot.lift and Quot.ind =========================== -/ /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ @[specialize] def reduceQuotRec {α} {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (whnf : Expr → m Expr) (rec : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → m α) (successK : Expr → m α) : m α := let process (majorPos argPos : Nat) : m α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩; major ← whnf major; match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConst majorFn | failK (); let f := recArgs.get! argPos; let r := mkApp f majorArg; let recArity := majorPos + 1; successK $ mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK (); match rec.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () @[specialize] def isQuotRecStuck {m : Type → Type} [Monad m] (whnf : Expr → m Expr) (isStuck : Expr → m (Option Expr)) (rec : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : m (Option Expr) := let process (majorPos : Nat) : m (Option Expr) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩; major ← whnf major; isStuck major else pure none; match rec.kind with | QuotKind.lift => process 5 | QuotKind.ind => process 4 | _ => pure none /- =========================== Helper function for extracting "stuck term" =========================== -/ /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ @[specialize] partial def getStuckMVar {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (whnf : Expr → m Expr) : Expr → m (Option Expr) | Expr.mdata _ e _ => getStuckMVar e | Expr.proj _ _ e _ => do e ← whnf e; getStuckMVar e | e@(Expr.mvar _ _) => pure (some e) | e@(Expr.app f _ _) => let f := f.getAppFn; match f with | Expr.mvar _ _ => pure (some f) | Expr.const fName fLvls _ => do cinfo? ← getConst fName; match cinfo? with | some $ ConstantInfo.recInfo rec => isRecStuck whnf getStuckMVar rec fLvls e.getAppArgs | some $ ConstantInfo.quotInfo rec => isQuotRecStuck whnf getStuckMVar rec fLvls e.getAppArgs | _ => pure none | _ => pure none | _ => pure none /- =========================== Weak Head Normal Form auxiliary combinators =========================== -/ /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] partial def whnfEasyCases {m : Type → Type} [Monad m] (getLocalDecl : Name → m LocalDecl) (getMVarAssignment : Name → m (Option Expr)) : Expr → (Expr → m Expr) → m Expr | e@(Expr.forallE _ _ _ _), _ => pure e | e@(Expr.lam _ _ _ _), _ => pure e | e@(Expr.sort _ _), _ => pure e | e@(Expr.lit _ _), _ => pure e | e@(Expr.bvar _ _), _ => unreachable! | Expr.mdata _ e _, k => whnfEasyCases e k | e@(Expr.letE _ _ _ _ _), k => k e | e@(Expr.fvar fvarId _), k => do decl ← getLocalDecl fvarId; match decl.value? with | none => pure e | some v => whnfEasyCases v k | e@(Expr.mvar mvarId _), k => do v? ← getMVarAssignment mvarId; match v? with | some v => whnfEasyCases v k | none => pure e | e@(Expr.const _ _ _), k => k e | e@(Expr.app _ _ _), k => k e | e@(Expr.proj _ _ _ _), k => k e | Expr.localE _ _ _ _, _ => unreachable! /-- Return true iff term is of the form `idRhs ...` -/ private def isIdRhsApp (e : Expr) : Bool := e.isAppOf `idRhs /-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/ private def extractIdRhs (e : Expr) : Expr := if !isIdRhsApp e then e else let args := e.getAppArgs; if args.size < 2 then e else mkAppRange (args.get! 1) 2 args.size args @[specialize] private def deltaDefinition {α} (c : ConstantInfo) (lvls : List Level) (failK : Unit → α) (successK : Expr → α) : α := if c.lparams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls; successK (extractIdRhs val) @[specialize] private def deltaBetaDefinition {α} (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → α) (successK : Expr → α) : α := if c.lparams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls; let val := val.betaRev revArgs; successK (extractIdRhs val) /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. This method does *not* apply delta-reduction at the head symbol `f` unless `isAuxDef? f` returns true. Reason: we want to perform these reductions lazily at `isDefEq`. -/ @[specialize] partial def whnfCore {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (isAuxDef? : Name → m Bool) (whnf : Expr → m Expr) (inferType : Expr → m Expr) (isDefEq : Expr → Expr → m Bool) (getLocalDecl : FVarId → m LocalDecl) (getMVarAssignment : MVarId → m (Option Expr)) : Expr → m Expr | e => whnfEasyCases getLocalDecl getMVarAssignment e $ fun e => match e with | e@(Expr.const _ _ _) => pure e | e@(Expr.letE _ _ v b _) => whnfCore $ b.instantiate1 v | e@(Expr.app f _ _) => do let f := f.getAppFn; f' ← whnfCore f; if f'.isLambda then let revArgs := e.getAppRevArgs; whnfCore $ f'.betaRev revArgs else do let done : Unit → m Expr := fun _ => if f == f' then pure e else pure $ e.updateFn f'; matchConstAux getConst f' done $ fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec getConst whnf inferType isDefEq rec lvls e.getAppArgs done whnfCore | ConstantInfo.quotInfo rec => reduceQuotRec getConst whnf rec lvls e.getAppArgs done whnfCore | c@(ConstantInfo.defnInfo _) => do unfold? ← isAuxDef? c.name; if unfold? then deltaBetaDefinition c lvls e.getAppRevArgs done whnfCore else done () | _ => done () | e@(Expr.proj _ i c _) => do c ← whnf c; matchConstAux getConst c.getAppFn (fun _ => pure e) $ fun cinfo lvls => match cinfo with | ConstantInfo.ctorInfo ctorVal => pure $ c.getArgD (ctorVal.nparams + i) e | _ => pure e | _ => unreachable! /-- Similar to `whnfCore`, but uses `synthesizePending` to (try to) synthesize metavariables that are blocking reduction. -/ @[specialize] private partial def whnfCoreUnstuck {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (isAuxDef? : Name → m Bool) (whnf : Expr → m Expr) (inferType : Expr → m Expr) (isDefEq : Expr → Expr → m Bool) (synthesizePending : Expr → m Bool) (getLocalDecl : FVarId → m LocalDecl) (getMVarAssignment : MVarId → m (Option Expr)) : Expr → m Expr | e => do e ← whnfCore getConst isAuxDef? whnf inferType isDefEq getLocalDecl getMVarAssignment e; (some mvar) ← getStuckMVar getConst whnf e | pure e; succeeded ← synthesizePending mvar; if succeeded then whnfCoreUnstuck e else pure e /-- Unfold definition using "smart unfolding" if possible. -/ @[specialize] def unfoldDefinitionAux {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (isAuxDef? : Name → m Bool) (whnf : Expr → m Expr) (inferType : Expr → m Expr) (isDefEq : Expr → Expr → m Bool) (synthesizePending : Expr → m Bool) (getLocalDecl : FVarId → m LocalDecl) (getMVarAssignment : MVarId → m (Option Expr)) (e : Expr) : m (Option Expr) := match e with | Expr.app f _ _ => matchConstAux getConst f.getAppFn (fun _ => pure none) $ fun fInfo fLvls => if fInfo.lparams.length != fLvls.length then pure none else do fAuxInfo? ← getConst (mkSmartUnfoldingNameFor fInfo.name); match fAuxInfo? with | some $ fAuxInfo@(ConstantInfo.defnInfo _) => deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) $ fun e₁ => do e₂ ← whnfCoreUnstuck getConst isAuxDef? whnf inferType isDefEq synthesizePending getLocalDecl getMVarAssignment e₁; if isIdRhsApp e₂ then pure (some (extractIdRhs e₂)) else pure none | _ => if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else pure none | Expr.const name lvls _ => do (some (cinfo@(ConstantInfo.defnInfo _))) ← getConst name | pure none; deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => pure none /- Reference implementation for `whnf`. It does not cache any results. How to use: - `getConst constName` retrieves `constName` from environment. Caller may make definitions opaque by returning `none`. - `isAuxDef? constName` returns `true` is `constName` is an auxiliary declaration automatically generated by Lean and used by equation compiler, and must be eagerly reduced by `whnfCore`. This method is usually implemented using `isAuxRecursor`. - `synthesizePending` is used to (try to) synthesize synthetic metavariables that may be blocking reduction. The other parameters should be self explanatory. -/ @[specialize] partial def whnfMain {m : Type → Type} [Monad m] (getConst : Name → m (Option ConstantInfo)) (isAuxDef? : Name → m Bool) (inferType : Expr → m Expr) (isDefEq : Expr → Expr → m Bool) (synthesizePending : Expr → m Bool) (getLocalDecl : FVarId → m LocalDecl) (getMVarAssignment : MVarId → m (Option Expr)) : Expr → m Expr | e => do e ← whnfCore getConst isAuxDef? whnfMain inferType isDefEq getLocalDecl getMVarAssignment e; e? ← unfoldDefinitionAux getConst isAuxDef? whnfMain inferType isDefEq synthesizePending getLocalDecl getMVarAssignment e; match e? with | some e => whnfMain e | none => pure e end WHNF end Lean
166e0c02f2c193702b12a2975258b330d3d53bc8
94e33a31faa76775069b071adea97e86e218a8ee
/src/logic/equiv/fin.lean
afb5793e44a0cd386ad4ffc54e63aac597df2e2c
[ "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
15,435
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fin.vec_notation import logic.equiv.basic import tactic.norm_num /-! # Equivalences for `fin n` -/ universes u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv.equiv_punit _ /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, by norm_num, refine fin.cases _ _, by norm_num, exact λi, fin_zero_elim i end, begin rintro ⟨_|_⟩, { refl }, { rw ← fin.succ_zero_eq_one, refl } end⟩ /-- `Π i : fin 2, α i` is equivalent to `α 0 × α 1`. See also `fin_two_arrow_equiv` for a non-dependent version and `prod_equiv_pi_fin_two` for a version with inputs `α β : Type u`. -/ @[simps {fully_applied := ff}] def pi_fin_two_equiv (α : fin 2 → Type u) : (Π i, α i) ≃ α 0 × α 1 := { to_fun := λ f, (f 0, f 1), inv_fun := λ p, fin.cons p.1 $ fin.cons p.2 fin_zero_elim, left_inv := λ f, funext $ fin.forall_fin_two.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } lemma fin.preimage_apply_01_prod {α : fin 2 → Type u} (s : set (α 0)) (t : set (α 1)) : (λ f : Π i, α i, (f 0, f 1)) ⁻¹' s ×ˢ t = set.pi set.univ (fin.cons s $ fin.cons t fin.elim0) := begin ext f, have : (fin.cons s (fin.cons t fin.elim0) : Π i, set (α i)) 1 = t := rfl, simp [fin.forall_fin_two, this] end lemma fin.preimage_apply_01_prod' {α : Type u} (s t : set α) : (λ f : fin 2 → α, (f 0, f 1)) ⁻¹' s ×ˢ t = set.pi set.univ ![s, t] := fin.preimage_apply_01_prod s t /-- A product space `α × β` is equivalent to the space `Π i : fin 2, γ i`, where `γ = fin.cons α (fin.cons β fin_zero_elim)`. See also `pi_fin_two_equiv` and `fin_two_arrow_equiv`. -/ @[simps {fully_applied := ff }] def prod_equiv_pi_fin_two (α β : Type u) : α × β ≃ Π i : fin 2, ![α, β] i := (pi_fin_two_equiv (fin.cons α (fin.cons β fin_zero_elim))).symm /-- The space of functions `fin 2 → α` is equivalent to `α × α`. See also `pi_fin_two_equiv` and `prod_equiv_pi_fin_two`. -/ @[simps { fully_applied := ff }] def fin_two_arrow_equiv (α : Type*) : (fin 2 → α) ≃ α × α := { inv_fun := λ x, ![x.1, x.2], .. pi_fin_two_equiv (λ _, α) } /-- `Π i : fin 2, α i` is order equivalent to `α 0 × α 1`. See also `order_iso.fin_two_arrow_equiv` for a non-dependent version. -/ def order_iso.pi_fin_two_iso (α : fin 2 → Type u) [Π i, preorder (α i)] : (Π i, α i) ≃o α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, map_rel_iff' := λ f g, iff.symm fin.forall_fin_two } /-- The space of functions `fin 2 → α` is order equivalent to `α × α`. See also `order_iso.pi_fin_two_iso`. -/ def order_iso.fin_two_arrow_iso (α : Type*) [preorder α] : (fin 2 → α) ≃o α × α := { to_equiv := fin_two_arrow_equiv α, .. order_iso.pi_fin_two_iso (λ _, α) } /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := (fin.cast h).to_equiv @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) : fin (n + 1) ≃ option (fin n) := { to_fun := i.insert_nth none some, inv_fun := λ x, x.cases_on' i (fin.succ_above i), left_inv := λ x, fin.succ_above_cases i (by simp) (λ j, by simp) x, right_inv := λ x, by cases x; dsimp; simp } @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i = none := by simp [fin_succ_equiv'] @[simp] lemma fin_succ_equiv'_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : fin_succ_equiv' i (i.succ_above j) = some j := @fin.insert_nth_apply_succ_above n (λ _, option (fin n)) i _ _ _ lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i) m.cast_succ = some m := by rw [← fin.succ_above_below _ _ h, fin_succ_equiv'_succ_above] lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i) m.succ = some m := by rw [← fin.succ_above_above _ _ h, fin_succ_equiv'_succ_above] @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i := rfl @[simp] lemma fin_succ_equiv'_symm_some {n : ℕ} (i : fin (n + 1)) (j : fin n) : (fin_succ_equiv' i).symm (some j) = i.succ_above j := rfl lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := fin.succ_above_below i m h lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm (some m) = m.succ := fin.succ_above_above i m h lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm m = m.cast_succ := fin_succ_equiv'_symm_some_below h lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm m = m.succ := fin_succ_equiv'_symm_some_above h /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' 0 @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := rfl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := fin_succ_equiv'_above (fin.zero_le _) @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := fin_succ_equiv'_symm_none _ @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := congr_fun fin.succ_above_zero m @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl /-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/ def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' (fin.last n) @[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) : fin_succ_equiv_last i.cast_succ = some i := fin_succ_equiv'_below i.2 @[simp] lemma fin_succ_equiv_last_last {n : ℕ} : fin_succ_equiv_last (fin.last n) = none := by simp [fin_succ_equiv_last] @[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm (some i) = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm ↑i = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} : fin_succ_equiv_last.symm none = fin.last n := fin_succ_equiv'_symm_none _ /-- Equivalence between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ @[simps { fully_applied := ff}] def equiv.pi_fin_succ_above_equiv {n : ℕ} (α : fin (n + 1) → Type u) (i : fin (n + 1)) : (Π j, α j) ≃ α i × (Π j, α (i.succ_above j)) := { to_fun := λ f, (f i, λ j, f (i.succ_above j)), inv_fun := λ f, i.insert_nth f.1 f.2, left_inv := λ f, by simp [fin.insert_nth_eq_iff], right_inv := λ f, by simp } /-- Order isomorphism between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ def order_iso.pi_fin_succ_above_iso {n : ℕ} (α : fin (n + 1) → Type u) [Π i, has_le (α i)] (i : fin (n + 1)) : (Π j, α j) ≃o α i × (Π j, α (i.succ_above j)) := { to_equiv := equiv.pi_fin_succ_above_equiv α i, map_rel_iff' := λ f g, i.forall_iff_succ_above.symm } /-- Equivalence between `fin (n + 1) → β` and `β × (fin n → β)`. -/ @[simps { fully_applied := ff}] def equiv.pi_fin_succ (n : ℕ) (β : Type u) : (fin (n+1) → β) ≃ β × (fin n → β) := equiv.pi_fin_succ_above_equiv (λ _, β) 0 /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := sum.elim (fin.cast_add n) (fin.nat_add m), inv_fun := λ i, @fin.add_cases m n (λ _, fin m ⊕ fin n) sum.inl sum.inr i, left_inv := λ x, by { cases x with y y; dsimp; simp }, right_inv := λ x, by refine fin.add_cases (λ i, _) (λ i, _) x; simp } @[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) : (fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) : (fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.nat_add m i := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add (x : fin m) : fin_sum_fin_equiv.symm (fin.cast_add n x) = sum.inl x := fin_sum_fin_equiv.symm_apply_apply (sum.inl x) @[simp] lemma fin_sum_fin_equiv_symm_apply_nat_add (x : fin n) : fin_sum_fin_equiv.symm (fin.nat_add m x) = sum.inr x := fin_sum_fin_equiv.symm_apply_apply (sum.inr x) @[simp] lemma fin_sum_fin_equiv_symm_last : fin_sum_fin_equiv.symm (fin.last n) = sum.inr 0 := fin_sum_fin_equiv_symm_apply_nat_add 0 /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_cast_add (k : fin m) (n : ℕ) : fin_add_flip (fin.cast_add n k) = fin.nat_add n k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_nat_add (k : fin n) (m : ℕ) : fin_add_flip (fin.nat_add m k) = fin.cast_add m k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_mk_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := by convert fin_add_flip_apply_cast_add ⟨k, h⟩ n @[simp] lemma fin_add_flip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, tsub_le_self.trans_lt $ add_comm m n ▸ h₂⟩ := begin convert fin_add_flip_apply_nat_add ⟨k - m, (tsub_lt_iff_right h₁).2 _⟩ m, { simp [add_tsub_cancel_of_le h₁] }, { rwa add_comm } end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_mk_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ @[simps] def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2 + n * x.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, (x.div_nat, x.mod_nat), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying values are retained. This is the `order_iso` version of `fin.cast_le`. -/ @[simps apply symm_apply] def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} := { to_fun := λ i, ⟨fin.cast_le h i, by simpa using i.is_lt⟩, inv_fun := λ i, ⟨i, i.prop⟩, left_inv := λ _, by simp, right_inv := λ _, by simp, map_rel_iff' := λ _ _, by simp } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
2db3dcd0e98344c14400fb9cb358ffc6d4a337dd
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/nat/cast.lean
9f00f7c4941df45dda0733b2d17699617da74461
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
4,177
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group algebra.ring namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 def cast_coe : has_coe ℕ α := ⟨nat.cast⟩ local attribute [instance, priority 0] cast_coe @[simp] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl end local attribute [instance, priority 0] cast_coe @[simp] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] instance [add_monoid α] [has_one α] : is_add_monoid_hom (coe : ℕ → α) := { map_zero := cast_zero, map_add := cast_add } @[simp] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, n > 0 → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] instance [semiring α] : is_semiring_hom (coe : ℕ → α) := by refine_struct {..}; simp theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_lt_of_nonneg zero_lt_one (@cast_nonneg α _ m) | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] theorem eq_cast [add_monoid α] [has_one α] (f : ℕ → α) (H0 : f 0 = 0) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n | 0 := H0 | (n+1) := by rw [Hadd, H1, eq_cast]; refl theorem eq_cast' [add_group α] [has_one α] (f : ℕ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n := eq_cast _ (by rw [← add_left_inj (f 0), add_zero, ← Hadd]) H1 Hadd @[simp] theorem cast_id (n : ℕ) : ↑n = n := (eq_cast id rfl rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) end nat
6cf96e72fbfbc2f1b72e6deb7a43c208c9c240fa
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1804.lean
0e7db5d40d32c4d6d548ce733d9df3aaed030e90
[ "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
def inc : StateM Nat Nat := do let s ← get modify (· + 1) return s def f (x : Bool) : StateM Nat Nat := do let .true := x | return (← inc) get def g (x : Bool) : StateM Nat Nat := do let .true := x | do return (← inc) get #eval g true |>.run' 0 -- `0` as expected #eval f true |>.run' 0 -- should return `0`, not `1`
ca7988e62658bfd5147a6e5554c8a3256aed624f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/lie/ideal_operations.lean
b1ab8c6d38e2805cdaa8bbd1f0fb033883efe26b
[ "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
14,464
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.submodule /-! # Ideal operations for Lie algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a Lie module `M` over a Lie algebra `L`, there is a natural action of the Lie ideals of `L` on the Lie submodules of `M`. In the special case that `M = L` with the adjoint action, this provides a pairing of Lie ideals which is especially important. For example, it can be used to define solvability / nilpotency of a Lie algebra via the derived / lower-central series. ## Main definitions * `lie_submodule.has_bracket` * `lie_submodule.lie_ideal_oper_eq_linear_span` * `lie_ideal.map_bracket_le` * `lie_ideal.comap_bracket_le` ## Notation Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M` and a Lie ideal `I ⊆ L`, we introduce the notation `⁅I, N⁆` for the Lie submodule of `M` corresponding to the action defined in this file. ## Tags lie algebra, ideal operation -/ universes u v w w₁ w₂ namespace lie_submodule variables {R : Type u} {L : Type v} {M : Type w} {M₂ : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group M₂] [module R M₂] [lie_ring_module L M₂] [lie_module R L M₂] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) (N₂ : lie_submodule R L M₂) section lie_ideal_operations /-- Given a Lie module `M` over a Lie algebra `L`, the set of Lie ideals of `L` acts on the set of submodules of `M`. -/ instance has_bracket : has_bracket (lie_ideal R L) (lie_submodule R L M) := ⟨λ I N, lie_span R L { m | ∃ (x : I) (n : N), ⁅(x : L), (n : M)⁆ = m }⟩ lemma lie_ideal_oper_eq_span : ⁅I, N⁆ = lie_span R L { m | ∃ (x : I) (n : N), ⁅(x : L), (n : M)⁆ = m } := rfl /-- See also `lie_submodule.lie_ideal_oper_eq_linear_span'` and `lie_submodule.lie_ideal_oper_eq_tensor_map_range`. -/ lemma lie_ideal_oper_eq_linear_span : (↑⁅I, N⁆ : submodule R M) = submodule.span R { m | ∃ (x : I) (n : N), ⁅(x : L), (n : M)⁆ = m } := begin apply le_antisymm, { let s := {m : M | ∃ (x : ↥I) (n : ↥N), ⁅(x : L), (n : M)⁆ = m}, have aux : ∀ (y : L) (m' ∈ submodule.span R s), ⁅y, m'⁆ ∈ submodule.span R s, { intros y m' hm', apply submodule.span_induction hm', { rintros m'' ⟨x, n, hm''⟩, rw [← hm'', leibniz_lie], refine submodule.add_mem _ _ _; apply submodule.subset_span, { use [⟨⁅y, ↑x⁆, I.lie_mem x.property⟩, n], refl, }, { use [x, ⟨⁅y, ↑n⁆, N.lie_mem n.property⟩], refl, }, }, { simp only [lie_zero, submodule.zero_mem], }, { intros m₁ m₂ hm₁ hm₂, rw lie_add, exact submodule.add_mem _ hm₁ hm₂, }, { intros t m'' hm'', rw lie_smul, exact submodule.smul_mem _ t hm'', }, }, change _ ≤ ↑({ lie_mem := aux, ..submodule.span R s } : lie_submodule R L M), rw [coe_submodule_le_coe_submodule, lie_ideal_oper_eq_span, lie_span_le], exact submodule.subset_span, }, { rw lie_ideal_oper_eq_span, apply submodule_span_le_lie_span, }, end lemma lie_ideal_oper_eq_linear_span' : (↑⁅I, N⁆ : submodule R M) = submodule.span R { m | ∃ (x ∈ I) (n ∈ N), ⁅x, n⁆ = m } := begin rw lie_ideal_oper_eq_linear_span, congr, ext m, split, { rintros ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, exact ⟨x, hx, n, hn, rfl⟩, }, { rintros ⟨x, hx, n, hn, rfl⟩, exact ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, }, end lemma lie_le_iff : ⁅I, N⁆ ≤ N' ↔ ∀ (x ∈ I) (m ∈ N), ⁅x, m⁆ ∈ N' := begin rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], refine ⟨λ h x hx m hm, h ⟨⟨x, hx⟩, ⟨m, hm⟩, rfl⟩, _⟩, rintros h _ ⟨⟨x, hx⟩, ⟨m, hm⟩, rfl⟩, exact h x hx m hm, end lemma lie_coe_mem_lie (x : I) (m : N) : ⁅(x : L), (m : M)⁆ ∈ ⁅I, N⁆ := by { rw lie_ideal_oper_eq_span, apply subset_lie_span, use [x, m], } lemma lie_mem_lie {x : L} {m : M} (hx : x ∈ I) (hm : m ∈ N) : ⁅x, m⁆ ∈ ⁅I, N⁆ := N.lie_coe_mem_lie I ⟨x, hx⟩ ⟨m, hm⟩ lemma lie_comm : ⁅I, J⁆ = ⁅J, I⁆ := begin suffices : ∀ (I J : lie_ideal R L), ⁅I, J⁆ ≤ ⁅J, I⁆, { exact le_antisymm (this I J) (this J I), }, clear I J, intros I J, rw [lie_ideal_oper_eq_span, lie_span_le], rintros x ⟨y, z, h⟩, rw ← h, rw [← lie_skew, ← lie_neg, ← lie_submodule.coe_neg], apply lie_coe_mem_lie, end lemma lie_le_right : ⁅I, N⁆ ≤ N := begin rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨x, n, hn⟩, rw ← hn, exact N.lie_mem n.property, end lemma lie_le_left : ⁅I, J⁆ ≤ I := by { rw lie_comm, exact lie_le_right I J, } lemma lie_le_inf : ⁅I, J⁆ ≤ I ⊓ J := by { rw le_inf_iff, exact ⟨lie_le_left I J, lie_le_right J I⟩, } @[simp] lemma lie_bot : ⁅I, (⊥ : lie_submodule R L M)⁆ = ⊥ := by { rw eq_bot_iff, apply lie_le_right, } @[simp] lemma bot_lie : ⁅(⊥ : lie_ideal R L), N⁆ = ⊥ := begin suffices : ⁅(⊥ : lie_ideal R L), N⁆ ≤ ⊥, { exact le_bot_iff.mp this, }, rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨⟨x, hx⟩, n, hn⟩, rw ← hn, change x ∈ (⊥ : lie_ideal R L) at hx, rw mem_bot at hx, simp [hx], end lemma lie_eq_bot_iff : ⁅I, N⁆ = ⊥ ↔ ∀ (x ∈ I) (m ∈ N), ⁅(x : L), m⁆ = 0 := begin rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_eq_bot_iff], refine ⟨λ h x hx m hm, h ⁅x, m⁆ ⟨⟨x, hx⟩, ⟨m, hm⟩, rfl⟩, _⟩, rintros h - ⟨⟨x, hx⟩, ⟨⟨n, hn⟩, rfl⟩⟩, exact h x hx n hn, end lemma mono_lie (h₁ : I ≤ J) (h₂ : N ≤ N') : ⁅I, N⁆ ≤ ⁅J, N'⁆ := begin intros m h, rw [lie_ideal_oper_eq_span, mem_lie_span] at h, rw [lie_ideal_oper_eq_span, mem_lie_span], intros N hN, apply h, rintros m' ⟨⟨x, hx⟩, ⟨n, hn⟩, hm⟩, rw ← hm, apply hN, use [⟨x, h₁ hx⟩, ⟨n, h₂ hn⟩], refl, end lemma mono_lie_left (h : I ≤ J) : ⁅I, N⁆ ≤ ⁅J, N⁆ := mono_lie _ _ _ _ h (le_refl N) lemma mono_lie_right (h : N ≤ N') : ⁅I, N⁆ ≤ ⁅I, N'⁆ := mono_lie _ _ _ _ (le_refl I) h @[simp] lemma lie_sup : ⁅I, N ⊔ N'⁆ = ⁅I, N⁆ ⊔ ⁅I, N'⁆ := begin have h : ⁅I, N⁆ ⊔ ⁅I, N'⁆ ≤ ⁅I, N ⊔ N'⁆, { rw sup_le_iff, split; apply mono_lie_right; [exact le_sup_left, exact le_sup_right], }, suffices : ⁅I, N ⊔ N'⁆ ≤ ⁅I, N⁆ ⊔ ⁅I, N'⁆, { exact le_antisymm this h, }, clear h, rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨x, ⟨n, hn⟩, h⟩, erw lie_submodule.mem_sup, erw lie_submodule.mem_sup at hn, rcases hn with ⟨n₁, hn₁, n₂, hn₂, hn'⟩, use ⁅(x : L), (⟨n₁, hn₁⟩ : N)⁆, split, { apply lie_coe_mem_lie, }, use ⁅(x : L), (⟨n₂, hn₂⟩ : N')⁆, split, { apply lie_coe_mem_lie, }, simp [← h, ← hn'], end @[simp] lemma sup_lie : ⁅I ⊔ J, N⁆ = ⁅I, N⁆ ⊔ ⁅J, N⁆ := begin have h : ⁅I, N⁆ ⊔ ⁅J, N⁆ ≤ ⁅I ⊔ J, N⁆, { rw sup_le_iff, split; apply mono_lie_left; [exact le_sup_left, exact le_sup_right], }, suffices : ⁅I ⊔ J, N⁆ ≤ ⁅I, N⁆ ⊔ ⁅J, N⁆, { exact le_antisymm this h, }, clear h, rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨⟨x, hx⟩, n, h⟩, erw lie_submodule.mem_sup, erw lie_submodule.mem_sup at hx, rcases hx with ⟨x₁, hx₁, x₂, hx₂, hx'⟩, use ⁅((⟨x₁, hx₁⟩ : I) : L), (n : N)⁆, split, { apply lie_coe_mem_lie, }, use ⁅((⟨x₂, hx₂⟩ : J) : L), (n : N)⁆, split, { apply lie_coe_mem_lie, }, simp [← h, ← hx'], end @[simp] lemma lie_inf : ⁅I, N ⊓ N'⁆ ≤ ⁅I, N⁆ ⊓ ⁅I, N'⁆ := by { rw le_inf_iff, split; apply mono_lie_right; [exact inf_le_left, exact inf_le_right], } @[simp] lemma inf_lie : ⁅I ⊓ J, N⁆ ≤ ⁅I, N⁆ ⊓ ⁅J, N⁆ := by { rw le_inf_iff, split; apply mono_lie_left; [exact inf_le_left, exact inf_le_right], } variables (f : M →ₗ⁅R,L⁆ M₂) lemma map_bracket_eq : map f ⁅I, N⁆ = ⁅I, map f N⁆ := begin rw [← coe_to_submodule_eq_iff, coe_submodule_map, lie_ideal_oper_eq_linear_span, lie_ideal_oper_eq_linear_span, submodule.map_span], congr, ext m, split, { rintros ⟨-, ⟨⟨x, ⟨n, hn⟩, rfl⟩, hm⟩⟩, simp only [lie_module_hom.coe_to_linear_map, lie_module_hom.map_lie] at hm, exact ⟨x, ⟨f n, (mem_map (f n)).mpr ⟨n, hn, rfl⟩⟩, hm⟩, }, { rintros ⟨x, ⟨m₂, hm₂ : m₂ ∈ map f N⟩, rfl⟩, obtain ⟨n, hn, rfl⟩ := (mem_map m₂).mp hm₂, exact ⟨⁅x, n⁆, ⟨x, ⟨n, hn⟩, rfl⟩, by simp⟩, }, end lemma map_comap_le : map f (comap f N₂) ≤ N₂ := (N₂ : set M₂).image_preimage_subset f lemma map_comap_eq (hf : N₂ ≤ f.range) : map f (comap f N₂) = N₂ := begin rw set_like.ext'_iff, exact set.image_preimage_eq_of_subset hf, end lemma le_comap_map : N ≤ comap f (map f N) := (N : set M).subset_preimage_image f lemma comap_map_eq (hf : f.ker = ⊥) : comap f (map f N) = N := begin rw set_like.ext'_iff, exact (N : set M).preimage_image_eq (f.ker_eq_bot.mp hf), end lemma comap_bracket_eq (hf₁ : f.ker = ⊥) (hf₂ : N₂ ≤ f.range) : comap f ⁅I, N₂⁆ = ⁅I, comap f N₂⁆ := begin conv_lhs { rw ← map_comap_eq N₂ f hf₂, }, rw [← map_bracket_eq, comap_map_eq _ f hf₁], end @[simp] lemma map_comap_incl : map N.incl (comap N.incl N') = N ⊓ N' := begin rw ← coe_to_submodule_eq_iff, exact (N : submodule R M).map_comap_subtype N', end end lie_ideal_operations end lie_submodule namespace lie_ideal open lie_algebra variables {R : Type u} {L : Type v} {L' : Type w₂} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L') /-- Note that the inequality can be strict; e.g., the inclusion of an Abelian subalgebra of a simple algebra. -/ lemma map_bracket_le {I₁ I₂ : lie_ideal R L} : map f ⁅I₁, I₂⁆ ≤ ⁅map f I₁, map f I₂⁆ := begin rw map_le_iff_le_comap, erw lie_submodule.lie_span_le, intros x hx, obtain ⟨⟨y₁, hy₁⟩, ⟨y₂, hy₂⟩, hx⟩ := hx, rw ← hx, let fy₁ : ↥(map f I₁) := ⟨f y₁, mem_map hy₁⟩, let fy₂ : ↥(map f I₂) := ⟨f y₂, mem_map hy₂⟩, change _ ∈ comap f ⁅map f I₁, map f I₂⁆, simp only [submodule.coe_mk, mem_comap, lie_hom.map_lie], exact lie_submodule.lie_coe_mem_lie _ _ fy₁ fy₂, end lemma map_bracket_eq {I₁ I₂ : lie_ideal R L} (h : function.surjective f) : map f ⁅I₁, I₂⁆ = ⁅map f I₁, map f I₂⁆ := begin suffices : ⁅map f I₁, map f I₂⁆ ≤ map f ⁅I₁, I₂⁆, { exact le_antisymm (map_bracket_le f) this, }, rw [← lie_submodule.coe_submodule_le_coe_submodule, coe_map_of_surjective h, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.lie_ideal_oper_eq_linear_span, linear_map.map_span], apply submodule.span_mono, rintros x ⟨⟨z₁, h₁⟩, ⟨z₂, h₂⟩, rfl⟩, obtain ⟨y₁, rfl⟩ := mem_map_of_surjective h h₁, obtain ⟨y₂, rfl⟩ := mem_map_of_surjective h h₂, use [⁅(y₁ : L), (y₂ : L)⁆, y₁, y₂], apply f.map_lie, end lemma comap_bracket_le {J₁ J₂ : lie_ideal R L'} : ⁅comap f J₁, comap f J₂⁆ ≤ comap f ⁅J₁, J₂⁆ := begin rw ← map_le_iff_le_comap, exact le_trans (map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ map_comap_le map_comap_le), end variables {f} lemma map_comap_incl {I₁ I₂ : lie_ideal R L} : map I₁.incl (comap I₁.incl I₂) = I₁ ⊓ I₂ := by { conv_rhs { rw ← I₁.incl_ideal_range, }, rw ← map_comap_eq, exact I₁.incl_is_ideal_morphism, } lemma comap_bracket_eq {J₁ J₂ : lie_ideal R L'} (h : f.is_ideal_morphism) : comap f ⁅f.ideal_range ⊓ J₁, f.ideal_range ⊓ J₂⁆ = ⁅comap f J₁, comap f J₂⁆ ⊔ f.ker := begin rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, ← submodule.comap_map_eq, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.lie_ideal_oper_eq_linear_span, linear_map.map_span], congr, simp only [lie_hom.coe_to_linear_map, set.mem_set_of_eq], ext y, split, { rintros ⟨⟨x₁, hx₁⟩, ⟨x₂, hx₂⟩, hy⟩, rw ← hy, erw [lie_submodule.mem_inf, f.mem_ideal_range_iff h] at hx₁ hx₂, obtain ⟨⟨z₁, hz₁⟩, hz₁'⟩ := hx₁, rw ← hz₁ at hz₁', obtain ⟨⟨z₂, hz₂⟩, hz₂'⟩ := hx₂, rw ← hz₂ at hz₂', use [⁅z₁, z₂⁆, ⟨z₁, hz₁'⟩, ⟨z₂, hz₂'⟩, rfl], simp only [hz₁, hz₂, submodule.coe_mk, lie_hom.map_lie], }, { rintros ⟨x, ⟨⟨z₁, hz₁⟩, ⟨z₂, hz₂⟩, hx⟩, hy⟩, rw [← hy, ← hx], have hz₁' : f z₁ ∈ f.ideal_range ⊓ J₁, { rw lie_submodule.mem_inf, exact ⟨f.mem_ideal_range, hz₁⟩, }, have hz₂' : f z₂ ∈ f.ideal_range ⊓ J₂, { rw lie_submodule.mem_inf, exact ⟨f.mem_ideal_range, hz₂⟩, }, use [⟨f z₁, hz₁'⟩, ⟨f z₂, hz₂'⟩], simp only [submodule.coe_mk, lie_hom.map_lie], }, end lemma map_comap_bracket_eq {J₁ J₂ : lie_ideal R L'} (h : f.is_ideal_morphism) : map f ⁅comap f J₁, comap f J₂⁆ = ⁅f.ideal_range ⊓ J₁, f.ideal_range ⊓ J₂⁆ := by { rw [← map_sup_ker_eq_map, ← comap_bracket_eq h, map_comap_eq h, inf_eq_right], exact le_trans (lie_submodule.lie_le_left _ _) inf_le_left, } lemma comap_bracket_incl {I₁ I₂ : lie_ideal R L} : ⁅comap I.incl I₁, comap I.incl I₂⁆ = comap I.incl ⁅I ⊓ I₁, I ⊓ I₂⁆ := begin conv_rhs { congr, skip, rw ← I.incl_ideal_range, }, rw comap_bracket_eq, simp only [ker_incl, sup_bot_eq], exact I.incl_is_ideal_morphism, end /-- This is a very useful result; it allows us to use the fact that inclusion distributes over the Lie bracket operation on ideals, subject to the conditions shown. -/ lemma comap_bracket_incl_of_le {I₁ I₂ : lie_ideal R L} (h₁ : I₁ ≤ I) (h₂ : I₂ ≤ I) : ⁅comap I.incl I₁, comap I.incl I₂⁆ = comap I.incl ⁅I₁, I₂⁆ := by { rw comap_bracket_incl, rw ← inf_eq_right at h₁ h₂, rw [h₁, h₂], } end lie_ideal
abb0de4db0cf2be7503788729710837e0de06a6d
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/src/tableau2.lean
47670f9bce8d14f6fb13c178b69a09a5e205e630
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
32,996
lean
import data.matrix.pequiv data.rat.basic tactic.fin_cases data.list.min_max partition open matrix fintype finset function pequiv local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose section universes u v variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] {R : Type v} /- Belongs in mathlib -/ lemma mul_right_eq_of_mul_eq [semiring R] {M : matrix l m R} {N : matrix m n R} {O : matrix l n R} {P : matrix n o R} (h : M ⬝ N = O) : M ⬝ (N ⬝ P) = O ⬝ P := by rw [← matrix.mul_assoc, h] end variables {m n : ℕ} /-- The tableau consists of a matrix and a kant `const` column. `to_partition` stores the indices of the current row and column variables. `restricted` is the set of variables that are restricted to be nonnegative -/ structure tableau (m n : ℕ) extends partition m n := (to_matrix : matrix (fin m) (fin n) ℚ) (const : cvec m) (restricted : finset (fin (m + n))) (dead : finset (fin n)) namespace tableau open partition section predicates variable (T : tableau m n) /-- The affine subspace represented by the tableau ignoring nonnegativity restrictiions -/ def flat : set (cvec (m + n)) := { x | T.to_partition.rowp.to_matrixᵀ ⬝ x = T.to_matrix ⬝ T.to_partition.colp.to_matrixᵀ ⬝ x + T.const } /-- The res_set is the subset of ℚ^(m+n) that satisifies the nonnegativity constraints of the tableau, and the affine conditions -/ def res_set : set (cvec (m + n)) := flat T ∩ { x | ∀ i, i ∈ T.restricted → 0 ≤ x i 0 } /-- The dead_set is the subset of ℚ^(m+n) such that all dead variables are zero, and satisfies the affine conditions -/ def dead_set : set (cvec (m + n)) := flat T ∩ { x | ∀ j, j ∈ T.dead → x (T.to_partition.colg j) 0 = 0 } /-- The `sol_set` is the set of vector that satisfy the affine constraints the dead variable constraints, and the nonnegativity constraints. -/ def sol_set : set (cvec (m + n)) := res_set T ∩ { x | ∀ j, j ∈ T.dead → x (T.to_partition.colg j) 0 = 0 } lemma sol_set_eq_res_set_inter : T.sol_set = res_set T ∩ { x | ∀ j, j ∈ T.dead → x (T.to_partition.colg j) 0 = 0 } := rfl lemma sol_set_eq_dead_set_inter : T.sol_set = dead_set T ∩ { x | ∀ i, i ∈ T.restricted → 0 ≤ x i 0 } := set.inter_right_comm _ _ _ lemma sol_set_eq_res_set_inter_dead_set : T.sol_set = T.res_set ∩ T.dead_set := by simp [sol_set, res_set, dead_set, set.ext_iff]; tauto /-- Predicate for a variable being unbounded above in the `res_set` -/ def is_unbounded_above (i : fin (m + n)) : Prop := ∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ q ≤ x i 0 /-- Predicate for a variable being unbounded below in the `res_set` -/ def is_unbounded_below (i : fin (m + n)) : Prop := ∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ x i 0 ≤ q def is_optimal (x : cvec (m + n)) (i : fin (m + n)) : Prop := x ∈ T.sol_set ∧ ∀ y : cvec (m + n), y ∈ sol_set T → y i 0 ≤ x i 0 /-- Is this equivalent to `∀ (x : cvec (m + n)), x ∈ res_set T → x i 0 = x j 0`? No -/ def equal_in_flat (i j : fin (m + n)) : Prop := ∀ (x : cvec (m + n)), x ∈ flat T → x i 0 = x j 0 /-- Returns an element of the `flat` after assigning values to the column variables -/ def of_col (T : tableau m n) (x : cvec n) : cvec (m + n) := T.to_partition.colp.to_matrix ⬝ x + T.to_partition.rowp.to_matrix ⬝ (T.to_matrix ⬝ x + T.const) /-- A `tableau` is feasible if its `const` column is nonnegative in restricted rows -/ def feasible : Prop := ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.const i 0 instance : decidable_pred (@feasible m n) := λ _, by dunfold feasible; apply_instance /-- Given a row index `r` and a column index `s` it returns a tableau with `r` and `s` switched, but with the same `res_set` -/ def pivot (i : fin m) (j : fin n) : tableau m n := let p := (T.to_matrix i j)⁻¹ in { to_matrix := λ i' j', if i' = i then if j' = j then p else -T.to_matrix i' j' * p else if j' = j then T.to_matrix i' j * p else T.to_matrix i' j' - T.to_matrix i' j * T.to_matrix i j' * p, to_partition := T.to_partition.swap i j, const := λ i' k, if i' = i then -T.const i k * p else T.const i' k - T.to_matrix i' j * T.const i k * p, restricted := T.restricted, dead := T.dead } def restrict (T : tableau m n) (v : fin (m + n)) : tableau m n := { restricted := insert v T.restricted, ..T } -- def kill_col (T : tableau m n) (j : fin n) : tableau m n := -- { dead := insert c T.dead, -- ..T } end predicates section predicate_lemmas variable {T : tableau m n} @[simp] lemma eta : tableau.mk T.to_partition T.to_matrix T.const T.restricted T.dead = T := by cases T; refl lemma mem_flat_iff {x : cvec (m + n)} : x ∈ T.flat ↔ ∀ i, x (T.to_partition.rowg i) 0 = univ.sum (λ j : fin n, T.to_matrix i j * x (T.to_partition.colg j) 0) + T.const i 0 := have hx : x ∈ T.flat ↔ ∀ i, (T.to_partition.rowp.to_matrixᵀ ⬝ x) i 0 = (T.to_matrix ⬝ T.to_partition.colp.to_matrixᵀ ⬝ x + T.const) i 0, by rw [flat, set.mem_set_of_eq, matrix.ext_iff.symm, forall_swap, unique.forall_iff]; refl, begin rw hx, refine forall_congr (λ i, _), rw [← to_matrix_symm, mul_matrix_apply, add_val, rowp_symm_eq_some_rowg, matrix.mul_assoc, matrix.mul], conv in (T.to_matrix _ _ * (T.to_partition.colp.to_matrixᵀ ⬝ x) _ _) { rw [← to_matrix_symm, mul_matrix_apply, colp_symm_eq_some_colg] } end variable (T) @[simp] lemma colp_mul_of_col (x : cvec n) : T.to_partition.colp.to_matrixᵀ ⬝ of_col T x = x := by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat, mul_right_eq_of_mul_eq (rowp_transpose_mul_colp _), mul_right_eq_of_mul_eq (rowp_transpose_mul_rowp _), mul_right_eq_of_mul_eq (colp_transpose_mul_colp _), mul_right_eq_of_mul_eq (colp_transpose_mul_rowp _)] @[simp] lemma rowp_mul_of_col (x : cvec n) : T.to_partition.rowp.to_matrixᵀ ⬝ of_col T x = T.to_matrix ⬝ x + T.const := by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat, mul_right_eq_of_mul_eq (rowp_transpose_mul_colp _), mul_right_eq_of_mul_eq (rowp_transpose_mul_rowp _), mul_right_eq_of_mul_eq (colp_transpose_mul_colp _), mul_right_eq_of_mul_eq (colp_transpose_mul_rowp _)] lemma of_col_mem_flat (x : cvec n) : T.of_col x ∈ T.flat := by simp [matrix.mul_assoc, matrix.mul_add, flat] @[simp] lemma of_col_colg (x : cvec n) (j : fin n) : of_col T x (T.to_partition.colg j) = x j := funext $ λ v, calc of_col T x (T.to_partition.colg j) v = (T.to_partition.colp.to_matrixᵀ ⬝ of_col T x) j v : by rw [← to_matrix_symm, mul_matrix_apply, colp_symm_eq_some_colg] ... = x j v : by rw [colp_mul_of_col] lemma of_col_rowg (c : cvec n) (i : fin m) : of_col T c (T.to_partition.rowg i) = (T.to_matrix ⬝ c + T.const) i := funext $ λ v, calc of_col T c (T.to_partition.rowg i) v = (T.to_partition.rowp.to_matrixᵀ ⬝ of_col T c) i v : by rw [← to_matrix_symm, mul_matrix_apply, rowp_symm_eq_some_rowg] ... = (T.to_matrix ⬝ c + T.const) i v : by rw [rowp_mul_of_col] variable {T} lemma of_col_single_rowg {q : ℚ} {i j} {k} : T.of_col (q • (single j 0).to_matrix) (T.to_partition.rowg i) k = q * T.to_matrix i j + T.const i k:= begin fin_cases k, erw [of_col_rowg, matrix.mul_smul, matrix.add_val, matrix.smul_val, matrix_mul_apply, pequiv.symm_single_apply] end /-- Condition for the solution given by setting column index `j` to `q` and all other columns to zero being in the `res_set` -/ lemma of_col_single_mem_res_set {q : ℚ} {j : fin n} (hT : T.feasible) (hi : ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ q * T.to_matrix i j) (hj : T.to_partition.colg j ∉ T.restricted ∨ 0 ≤ q) : T.of_col (q • (single j 0).to_matrix) ∈ T.res_set := ⟨of_col_mem_flat _ _, λ v, (T.to_partition.eq_rowg_or_colg v).elim begin rintros ⟨i', hi'⟩ hres, subst hi', rw [of_col_single_rowg], exact add_nonneg (hi _ hres) (hT _ hres) end begin rintros ⟨j', hj'⟩ hres, subst hj', simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix], by_cases hjc : j' = j; simp [*, le_refl] at * end⟩ lemma of_col_single_mem_sol_set {q : ℚ} {j : fin n} (hT : T.feasible) (hi : ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ q * T.to_matrix i j) (hj : T.to_partition.colg j ∉ T.restricted ∨ 0 ≤ q) (hdead : j ∉ T.dead ∨ q = 0): T.of_col (q • (single j 0).to_matrix) ∈ T.sol_set := ⟨of_col_single_mem_res_set hT hi hj, λ j' hj', classical.by_cases (λ hjj' : j' = j, by subst hjj'; simp * at *) (λ hjj' : j' ≠ j, by simp [smul_val, pequiv.single, pequiv.to_matrix, hjj'])⟩ @[simp] lemma of_col_zero_mem_res_set_iff : T.of_col 0 ∈ T.res_set ↔ T.feasible := suffices (∀ v : fin (m + n), v ∈ T.restricted → (0 : ℚ) ≤ T.of_col 0 v 0) ↔ (∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.const i 0), by simpa [res_set, feasible, of_col_mem_flat], ⟨λ h i hi, by simpa [of_col_rowg] using h _ hi, λ h v hv, (T.to_partition.eq_rowg_or_colg v).elim (by rintros ⟨i, hi⟩; subst hi; simp [of_col_rowg]; tauto) (by rintros ⟨j, hj⟩; subst hj; simp)⟩ @[simp] lemma of_col_zero_mem_sol_set_iff : T.of_col 0 ∈ T.sol_set ↔ T.feasible := by simp [sol_set, of_col_zero_mem_res_set_iff] @[simp] lemma to_matrix_restrict (v : fin (m + n)) : (T.restrict v).to_matrix = T.to_matrix := rfl @[simp] lemma const_restrict (v : fin (m + n)) : (T.restrict v).const = T.const := rfl @[simp] lemma to_partition_restrict (v : fin (m + n)) : (T.restrict v).to_partition = T.to_partition := rfl @[simp] lemma dead_restrict (v : fin (m + n)) : (T.restrict v).dead = T.dead := rfl @[simp] lemma restricted_restrict (v : fin (m + n)) : (T.restrict v).restricted = insert v T.restricted := rfl @[simp] lemma flat_restrict (v : fin (m + n)) : (T.restrict v).flat = T.flat := by simp [flat] @[simp] lemma dead_set_restrict (v : fin (m + n)) : (T.restrict v).dead_set = T.dead_set := by simp [dead_set] lemma res_set_restrict (v : fin (m + n)) : (T.restrict v).res_set = T.res_set ∩ {x | 0 ≤ x v 0} := begin simp only [res_set, flat_restrict, set.inter_assoc], ext x, exact ⟨λ h, ⟨h.1, λ i hi, h.2 _ $ by simp [hi], h.2 _ $ by simp⟩, λ h, ⟨h.1, λ i hi, (mem_insert.1 hi).elim (λ hv, hv.symm ▸ h.2.2) $ h.2.1 _⟩⟩ end lemma sol_set_restrict (v : fin (m + n)) : (T.restrict v).sol_set = T.sol_set ∩ {x | 0 ≤ x v 0} := by simp [sol_set_eq_res_set_inter_dead_set, res_set_restrict, set.inter_comm, set.inter_assoc, set.inter_left_comm] lemma feasible_restrict {v : fin (m + n)} (hfT : T.feasible) (h : (∃ c, v = T.to_partition.colg c) ∨ ∃ i, v = T.to_partition.rowg i ∧ 0 ≤ T.const i 0) : (T.restrict v).feasible := h.elim (λ ⟨c, hc⟩, hc.symm ▸ λ i hi, hfT _ $ by simpa using hi) (λ ⟨i, hiv, hi⟩, hiv.symm ▸ λ i' hi', (mem_insert.1 hi').elim (λ h, by simp [T.to_partition.injective_rowg.eq_iff, *] at *) (λ hres, hfT _ $ by simpa using hres)) lemma is_unbounded_above_colg_aux {j : fin n} (hT : T.feasible) (hdead : j ∉ T.dead) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i j) (q : ℚ) : of_col T (max q 0 • (single j 0).to_matrix) ∈ sol_set T ∧ q ≤ of_col T (max q 0 • (single j 0).to_matrix) (T.to_partition.colg j) 0 := ⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (h _ hi)) (or.inr (le_max_right _ _)) (or.inl hdead), by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩ /-- A column variable is unbounded above if it is in a column where every negative entry is in a row owned by an unrestricted variable -/ lemma is_unbounded_above_colg {j : fin n} (hT : T.feasible) (hdead : j ∉ T.dead) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i j) : T.is_unbounded_above (T.to_partition.colg j) := λ q, ⟨_, is_unbounded_above_colg_aux hT hdead h q⟩ lemma is_unbounded_below_colg_aux {j : fin n} (hT : T.feasible) (hres : T.to_partition.colg j ∉ T.restricted) (hdead : j ∉ T.dead) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i j ≤ 0) (q : ℚ) : of_col T (min q 0 • (single j 0).to_matrix) ∈ sol_set T ∧ of_col T (min q 0 • (single j 0).to_matrix) (T.to_partition.colg j) 0 ≤ q := ⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi)) (or.inl hres) (or.inl hdead), by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩ /-- A column variable is unbounded below if it is unrestricted and it is in a column where every positive entry is in a row owned by an unrestricted variable -/ lemma is_unbounded_below_colg {j : fin n} (hT : T.feasible) (hres : T.to_partition.colg j ∉ T.restricted) (hdead : j ∉ T.dead) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i j ≤ 0) : T.is_unbounded_below (T.to_partition.colg j) := λ q, ⟨_, is_unbounded_below_colg_aux hT hres hdead h q⟩ /-- A row variable `r` is unbounded above if it is unrestricted and there is a column `s` where every restricted row variable has a nonpositive entry in that column, and `r` has a negative entry in that column. -/ lemma is_unbounded_above_rowg_of_nonpos {i : fin m} (hT : T.feasible) (j : fin n) (hres : T.to_partition.colg j ∉ T.restricted) (hdead : j ∉ T.dead) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i j ≤ 0) (his : T.to_matrix i j < 0) : is_unbounded_above T (T.to_partition.rowg i) := λ q, ⟨T.of_col (min ((q - T.const i 0) / T.to_matrix i j) 0 • (single j 0).to_matrix), of_col_single_mem_sol_set hT (λ i' hi', mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi')) (or.inl hres) (or.inl hdead), begin rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single_apply], cases le_total 0 ((q - T.const i 0) / T.to_matrix i j) with hq hq, { rw [min_eq_right hq], rw [le_div_iff_of_neg his, zero_mul, sub_nonpos] at hq, simpa }, { rw [min_eq_left hq, div_mul_cancel _ (ne_of_lt his)], simp } end⟩ /-- A row variable `i` is unbounded above if there is a column `s` where every restricted row variable has a nonpositive entry in that column, and `i` has a positive entry in that column. -/ lemma is_unbounded_above_rowg_of_nonneg {i : fin m} (hT : T.feasible) (j : fin n) (hs : ∀ i' : fin m, T.to_partition.rowg i' ∈ T.restricted → 0 ≤ T.to_matrix i' j) (hdead : j ∉ T.dead) (his : 0 < T.to_matrix i j) : is_unbounded_above T (T.to_partition.rowg i) := λ q, ⟨T.of_col (max ((q - T.const i 0) / T.to_matrix i j) 0 • (single j 0).to_matrix), of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (hs i hi)) (or.inr (le_max_right _ _)) (or.inl hdead), begin rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single_apply], cases le_total ((q - T.const i 0) / T.to_matrix i j) 0 with hq hq, { rw [max_eq_right hq], rw [div_le_iff his, zero_mul, sub_nonpos] at hq, simpa }, { rw [max_eq_left hq, div_mul_cancel _ (ne_of_gt his)], simp } end⟩ /-- The sample solution of a feasible tableau maximises the variable in row `r`, if every entry in that row is nonpositive and every entry in that row owned by a restricted variable is `0` -/ lemma is_optimal_of_col_zero {obj : fin m} (hf : T.feasible) (h : ∀ j, j ∉ T.dead → T.to_matrix obj j ≤ 0 ∧ (T.to_partition.colg j ∉ T.restricted → T.to_matrix obj j = 0)) : T.is_optimal (T.of_col 0) (T.to_partition.rowg obj) := ⟨of_col_zero_mem_sol_set_iff.2 hf, λ x hx, begin rw [of_col_rowg, matrix.mul_zero, zero_add, mem_flat_iff.1 hx.1.1], refine add_le_of_nonpos_of_le _ (le_refl _), refine sum_nonpos (λ j _, _), by_cases hj : (T.to_partition.colg j) ∈ T.restricted, { by_cases hdead : j ∈ T.dead, { simp [hx.2 _ hdead] }, { exact mul_nonpos_of_nonpos_of_nonneg (h _ hdead).1 (hx.1.2 _ hj) } }, { by_cases hdead : j ∈ T.dead, { simp [hx.2 _ hdead] }, { rw [(h _ hdead).2 hj, zero_mul] } } end⟩ lemma not_optimal_of_unbounded_above {v : fin (m + n)} {x : cvec (m + n)} (hu : is_unbounded_above T v) : ¬is_optimal T x v := λ hm, let ⟨y, hy⟩ := hu (x v 0 + 1) in not_le_of_gt (lt_add_one (x v 0)) (le_trans hy.2 (hm.2 y hy.1)) /-- Expression for the sum of all but one entries in the a row of a tableau. -/ lemma row_sum_erase_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {i : fin m} {j : fin n} : (univ.erase j).sum (λ j' : fin n, T.to_matrix i j' * x (T.to_partition.colg j') 0) = x (T.to_partition.rowg i) 0 - T.const i 0 - T.to_matrix i j * x (T.to_partition.colg j) 0 := begin rw [mem_flat_iff] at hx, conv_rhs { rw [hx i, ← insert_erase (mem_univ j), sum_insert (not_mem_erase _ _)] }, simp end /-- An expression for a column variable in terms of row variables. -/ lemma colg_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {i : fin m} {j : fin n} (his : T.to_matrix i j ≠ 0) : x (T.to_partition.colg j) 0 = (x (T.to_partition.rowg i) 0 -(univ.erase j).sum (λ j' : fin n, T.to_matrix i j' * x (T.to_partition.colg j') 0) - T.const i 0) * (T.to_matrix i j)⁻¹ := by simp [row_sum_erase_eq hx, mul_left_comm (T.to_matrix i j)⁻¹, mul_assoc, mul_left_comm (T.to_matrix i j), mul_inv_cancel his] /-- Another expression for a column variable in terms of row variables. -/ lemma colg_eq' {x : cvec (m + n)} (hx : x ∈ T.flat) {i : fin m} {j : fin n} (his : T.to_matrix i j ≠ 0) : x (T.to_partition.colg j) 0 = univ.sum (λ j' : fin n, (if j' = j then (T.to_matrix i j)⁻¹ else (-(T.to_matrix i j' * (T.to_matrix i j)⁻¹))) * x (colg (swap (T.to_partition) i j) j') 0) - (T.const i 0) * (T.to_matrix i j)⁻¹ := have (univ.erase j).sum (λ j' : fin n, ite (j' = j) (T.to_matrix i j)⁻¹ (-(T.to_matrix i j' * (T.to_matrix i j)⁻¹)) * x (colg (swap (T.to_partition) i j) j') 0) = (univ.erase j).sum (λ j' : fin n, -T.to_matrix i j' * x (T.to_partition.colg j') 0 * (T.to_matrix i j)⁻¹), from finset.sum_congr rfl $ λ j' hj', by simp [if_neg (mem_erase.1 hj').1, colg_swap_of_ne _ (mem_erase.1 hj').1, mul_comm, mul_assoc, mul_left_comm], by rw [← finset.insert_erase (mem_univ j), finset.sum_insert (not_mem_erase _ _), if_pos rfl, colg_swap, colg_eq hx his, this, ← finset.sum_mul]; simp [_root_.add_mul, mul_comm, _root_.mul_add] /-- Pivoting twice in the same place does nothing -/ @[simp] lemma pivot_pivot {i : fin m} {j : fin n} (his : T.to_matrix i j ≠ 0) : (T.pivot i j).pivot i j = T := begin cases T, simp [pivot, function.funext_iff], split; intros; split_ifs; simp [*, mul_assoc, mul_left_comm (T_to_matrix i j), mul_left_comm (T_to_matrix i j)⁻¹, mul_comm (T_to_matrix i j), inv_mul_cancel his] end /- These two sets are equal_in_flat, the stronger lemma is `flat_pivot` -/ private lemma subset_flat_pivot {i : fin m} {j : fin n} (h : T.to_matrix i j ≠ 0) : T.flat ⊆ (T.pivot i j).flat := λ x hx, have ∀ i' : fin m, (univ.erase j).sum (λ j' : fin n, ite (j' = j) (T.to_matrix i' j * (T.to_matrix i j)⁻¹) (T.to_matrix i' j' + -(T.to_matrix i' j * T.to_matrix i j' * (T.to_matrix i j)⁻¹)) * x ((T.to_partition.swap i j).colg j') 0) = (univ.erase j).sum (λ j' : fin n, T.to_matrix i' j' * x (T.to_partition.colg j') 0 - T.to_matrix i j' * x (T.to_partition.colg j') 0 * T.to_matrix i' j * (T.to_matrix i j)⁻¹), from λ i', finset.sum_congr rfl (λ j' hj', by rw [if_neg (mem_erase.1 hj').1, colg_swap_of_ne _ (mem_erase.1 hj').1]; simp [mul_add, add_mul, mul_comm, mul_assoc, mul_left_comm]), begin rw mem_flat_iff, assume i', by_cases hi'i : i' = i, { rw eq_comm at hi'i, subst hi'i, dsimp [pivot], simp [mul_inv_cancel h, neg_mul_eq_neg_mul_symm, if_true, add_comm, mul_inv_cancel, rowg_swap, eq_self_iff_true, colg_eq' hx h], congr, funext, congr }, { dsimp [pivot], simp only [if_neg hi'i], rw [← insert_erase (mem_univ j), sum_insert (not_mem_erase _ _), if_pos rfl, colg_swap, this, sum_sub_distrib, ← sum_mul, ← sum_mul, row_sum_erase_eq hx, rowg_swap_of_ne _ hi'i], simp [row_sum_erase_eq hx, mul_add, add_mul, mul_comm, mul_left_comm, mul_assoc], simp [mul_assoc, mul_left_comm (T.to_matrix i j), mul_left_comm (T.to_matrix i j)⁻¹, mul_comm (T.to_matrix i j), inv_mul_cancel h] } end variable (T) @[simp] lemma pivot_pivot_element (i : fin m) (j : fin n) : (T.pivot i j).to_matrix i j = (T.to_matrix i j)⁻¹ := by simp [pivot, if_pos rfl] @[simp] lemma pivot_pivot_row {i : fin m} {j j' : fin n} (h : j' ≠ j) : (T.pivot i j).to_matrix i j' = -T.to_matrix i j' / T.to_matrix i j := by dsimp [pivot]; rw [if_pos rfl, if_neg h, div_eq_mul_inv] @[simp] lemma pivot_pivot_column {i' i : fin m} {j : fin n} (h : i' ≠ i) : (T.pivot i j).to_matrix i' j = T.to_matrix i' j / T.to_matrix i j := by dsimp [pivot]; rw [if_neg h, if_pos rfl, div_eq_mul_inv] @[simp] lemma pivot_of_ne_of_ne {i i' : fin m} {j j' : fin n} (hi'i : i' ≠ i) (hjs : j' ≠ j) : (T.pivot i j).to_matrix i' j' = T.to_matrix i' j' - T.to_matrix i' j * T.to_matrix i j' / T.to_matrix i j := by dsimp [pivot]; rw [if_neg hi'i, if_neg hjs, div_eq_mul_inv] @[simp] lemma const_pivot_row {i : fin m} {j : fin n} : (T.pivot i j).const i 0 = -T.const i 0 / T.to_matrix i j := by simp [pivot, if_pos rfl, div_eq_mul_inv] @[simp] lemma const_pivot_of_ne {i i' : fin m} {j : fin n} (hi'i : i' ≠ i) : (T.pivot i j).const i' 0 = T.const i' 0 - T.to_matrix i' j * T.const i 0 / T.to_matrix i j := by dsimp [pivot]; rw [if_neg hi'i, div_eq_mul_inv] @[simp] lemma restricted_pivot (i s) : (T.pivot i s).restricted = T.restricted := rfl @[simp] lemma to_partition_pivot (i s) : (T.pivot i s).to_partition = T.to_partition.swap i s := rfl @[simp] lemma dead_pivot (i c) : (T.pivot i c).dead = T.dead := rfl variable {T} @[simp] lemma flat_pivot {i : fin m} {j : fin n} (hij : T.to_matrix i j ≠ 0) : (T.pivot i j).flat = T.flat := set.subset.antisymm (by conv_rhs { rw ← pivot_pivot hij }; exact subset_flat_pivot (by simp [hij])) (subset_flat_pivot hij) @[simp] lemma res_set_pivot {i : fin m} {j : fin n} (hij : T.to_matrix i j ≠ 0) : (T.pivot i j).res_set = T.res_set := by rw [res_set, flat_pivot hij]; refl @[simp] lemma dead_set_pivot {i : fin m} {j : fin n} (hij : T.to_matrix i j ≠ 0) (hdead : j ∉ T.dead) : (T.pivot i j).dead_set = T.dead_set := begin rw [dead_set, dead_set, flat_pivot hij], congr, funext x, refine forall_congr_eq (λ j', forall_congr_eq (λ hj', _)), have hjj' : j' ≠ j, from λ hjj', by simp * at *, simp [colg_swap_of_ne _ hjj'] end @[simp] lemma sol_set_pivot {i : fin m} {j : fin n} (hij : T.to_matrix i j ≠ 0) (hdead : j ∉ T.dead) : (T.pivot i j).sol_set = T.sol_set := by simp [sol_set_eq_dead_set_inter, dead_set_pivot hij hdead, flat_pivot hij] /-- Two row variables are `equal_in_flat` iff the corresponding rows of the tableau are equal -/ lemma equal_in_flat_row_row {i i' : fin m} : T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.rowg i') ↔ (T.const i 0 = T.const i' 0 ∧ ∀ j : fin n, T.to_matrix i j = T.to_matrix i' j) := ⟨λ h, have Hconst : T.const i 0 = T.const i' 0, by simpa [of_col_rowg] using h (T.of_col 0) (of_col_mem_flat _ _), ⟨Hconst, λ j, begin have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_rowg, add_val, add_val, matrix_mul_apply, matrix_mul_apply, symm_single_apply, Hconst, add_right_cancel_iff] at this, end⟩, λ h x hx, by simp [mem_flat_iff.1 hx, h.1, h.2]⟩ /-- A row variable is equal_in_flat to a column variable iff its row has zeros, and a single one in that column. -/ lemma equal_in_flat_row_col {i : fin m} {j : fin n} : T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.colg j) ↔ (∀ j', j' ≠ j → T.to_matrix i j' = 0) ∧ T.const i 0 = 0 ∧ T.to_matrix i j = 1 := ⟨λ h, have Hconst : T.const i 0 = 0, by simpa [of_col_rowg] using h (T.of_col 0) (of_col_mem_flat _ _), ⟨assume j' hj', begin have := h (T.of_col (single j' (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_colg, add_val, Hconst, add_zero, matrix_mul_apply, symm_single_apply, pequiv.to_matrix, single_apply_of_ne hj', if_neg (option.not_mem_none _)] at this end, Hconst, begin have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_colg, add_val, Hconst, add_zero, matrix_mul_apply, symm_single_apply, pequiv.to_matrix, single_apply] at this end⟩, by rintros ⟨h₁, h₂, h₃⟩ x hx; rw [mem_flat_iff.1 hx, h₂, sum_eq_single j]; simp *; tauto⟩ lemma mul_single_ext {R : Type*} {m n : ℕ} [semiring R] {A B : matrix (fin m) (fin n) R} (h : ∀ j : fin n, A ⬝ (single j (0 : fin 1)).to_matrix = B ⬝ (single j (0 : fin 1)).to_matrix) : A = B := by ext i j; simpa [matrix_mul_apply] using congr_fun (congr_fun (h j) i) 0 lemma single_mul_ext {R : Type*} {m n : ℕ} [semiring R] {A B : matrix (fin m) (fin n) R} (h : ∀ i, (single (0 : fin 1) i).to_matrix ⬝ A = (single (0 : fin 1) i).to_matrix ⬝ B) : A = B := by ext i j; simpa [mul_matrix_apply] using congr_fun (congr_fun (h i) 0) j lemma ext {T₁ T₂ : tableau m n} (hflat : T₁.flat = T₂.flat) (hpartition : T₁.to_partition = T₂.to_partition) (hdead : T₁.dead = T₂.dead) (hres : T₁.restricted = T₂.restricted) : T₁ = T₂ := have hconst : T₁.const = T₂.const, by rw [set.ext_iff] at hflat; simpa [of_col, flat, hpartition, matrix.mul_assoc, mul_right_eq_of_mul_eq (rowp_transpose_mul_rowp _), mul_right_eq_of_mul_eq (colp_transpose_mul_rowp _)] using (hflat (T₁.of_col 0)).1 (of_col_mem_flat _ _), have hmatrix : T₁.to_matrix = T₂.to_matrix, from mul_single_ext $ λ j, begin rw [set.ext_iff] at hflat, have := (hflat (T₁.of_col (single j 0).to_matrix)).1 (of_col_mem_flat _ _), simpa [of_col, hconst, hpartition, flat, matrix.mul_add, matrix.mul_assoc, mul_right_eq_of_mul_eq (rowp_transpose_mul_colp _), mul_right_eq_of_mul_eq (rowp_transpose_mul_rowp _), mul_right_eq_of_mul_eq (colp_transpose_mul_colp _), mul_right_eq_of_mul_eq (colp_transpose_mul_rowp _)] using (hflat (T₁.of_col (single j 0).to_matrix)).1 (of_col_mem_flat _ _) end, by cases T₁; cases T₂; simp * at * end predicate_lemmas /-- Conditions for unboundedness based on reading the tableau. The conditions are equivalent to the simplex pivot rule failing to find a pivot row. -/ lemma unbounded_of_tableau {T : tableau m n} {obj : fin m} {j : fin n} (hT : T.feasible) (hdead : j ∉ T.dead) (hrow : ∀ i, obj ≠ i → T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix obj j / T.to_matrix i j) (hc : (T.to_matrix obj j ≠ 0 ∧ T.to_partition.colg j ∉ T.restricted) ∨ (0 < T.to_matrix obj j ∧ T.to_partition.colg j ∈ T.restricted)) : T.is_unbounded_above (T.to_partition.rowg obj) := have hToj : T.to_matrix obj j ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc, (lt_or_gt_of_ne hToj).elim (λ hToj : T.to_matrix obj j < 0, is_unbounded_above_rowg_of_nonpos hT j (hc.elim and.right (λ h, (not_lt_of_gt hToj h.1).elim)) hdead (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToj)) (λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToj)) hToj) (λ hToj : 0 < T.to_matrix obj j, is_unbounded_above_rowg_of_nonneg hT j (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToj)) (λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToj)) hdead hToj) /-- Conditions for the tableau being feasible, that must be satisified by a simplex pivot rule -/ lemma feasible_pivot {T : tableau m n} (hT : T.feasible) {i j} (hres : T.to_partition.rowg i ∈ T.restricted) (hpos : T.to_partition.colg j ∈ T.restricted → T.to_matrix i j < 0) (himin : ∀ (i' : fin m), T.to_partition.rowg i' ∈ T.restricted → 0 < T.to_matrix i' j / T.to_matrix i j → abs (T.const i 0 / T.to_matrix i j) ≤ abs (T.const i' 0 / T.to_matrix i' j)) : (T.pivot i j).feasible := begin assume i' hi', dsimp only [pivot], by_cases hii : i' = i, { subst i', rw [if_pos rfl, neg_mul_eq_neg_mul_symm, neg_nonneg], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hres) (inv_nonpos.2 $ le_of_lt (by simp * at *)) }, { rw if_neg hii, rw [to_partition_pivot, rowg_swap_of_ne _ hii, restricted_pivot] at hi', by_cases hTii : 0 < T.to_matrix i' j / T.to_matrix i j, { have hTi'c0 : T.to_matrix i' j ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTii, have hTic0 : T.to_matrix i j ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTii, have := himin _ hi' hTii, rwa [abs_div, abs_div, abs_of_nonneg (hT _ hres), abs_of_nonneg (hT _ hi'), le_div_iff (abs_pos_iff.2 hTi'c0), div_eq_mul_inv, mul_right_comm, ← abs_inv, mul_assoc, ← abs_mul, ← div_eq_mul_inv, abs_of_nonneg (le_of_lt hTii), ← sub_nonneg, ← mul_div_assoc, div_eq_mul_inv, mul_comm (T.const i 0)] at this }, { refine add_nonneg (hT _ hi') (neg_nonneg.2 _), rw [mul_assoc, mul_left_comm], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hres) (le_of_not_gt hTii) } } end lemma feasible_simplex_pivot {T : tableau m n} {obj : fin m} (hT : T.feasible) {i j} (hres : T.to_partition.rowg i ∈ T.restricted) (hineg : T.to_matrix i j < 0) (himin : ∀ (i' : fin m), obj ≠ i' → T.to_partition.rowg i' ∈ T.restricted → T.to_matrix i' j < 0 → abs (T.const i 0 / T.to_matrix i j) ≤ abs (T.const i' 0 / T.to_matrix i' j)) (hc : T.to_partition.colg j ∈ T.restricted → 0 < T.to_matrix obj j) : (T.pivot i j).feasible := feasible_pivot hT hres (λ hcres, inv_neg'.1 (neg_of_mul_neg_left _ (le_of_lt (hc hcres)))) (λ i' hi'res hii, have hobji : obj ≠ i', from λ hobji, not_lt_of_gt hii (hobji ▸ hineg), (himin _ hobji hi'res $ have hTrc0 : T.to_matrix i j ≠ 0, from λ _, by simp [*, lt_irrefl] at *, suffices (T.to_matrix obj j / T.to_matrix i j) / (T.to_matrix i' j / T.to_matrix i j) < 0, by rwa [div_div_div_cancel_right _ _ hTrc0] at this, div_neg_of_neg_of_pos hineg hii)) /-- Used in sign_of_max -/ lemma feasible_pivot_obj_of_nonpos {T : tableau m n} {obj : fin m} (hT : T.feasible) {j} (hc : T.to_partition.colg j ∈ T.restricted → 0 < T.to_matrix obj j) (hr : ∀ i, obj ≠ i → T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix obj j / T.to_matrix i j) (hobj : T.const obj 0 ≤ 0) : feasible (T.pivot obj j) := λ i hi, if hiobj : i = obj then by rw [hiobj, const_pivot_row, neg_div, neg_nonneg]; exact mul_nonpos_of_nonpos_of_nonneg hobj (le_of_lt $ by simp [*, inv_pos'] at *) else begin rw [const_pivot_of_ne _ hiobj], rw [to_partition_pivot, rowg_swap_of_ne _ hiobj, restricted_pivot] at hi, refine add_nonneg (hT _ hi) (neg_nonneg.2 _), rw [div_eq_mul_inv, mul_right_comm], exact mul_nonpos_of_nonneg_of_nonpos (inv_nonneg.1 (by simpa [mul_inv'] using hr _ (ne.symm hiobj) hi)) hobj end lemma simplex_const_obj_le {T : tableau m n} {obj : fin m} (hT : T.feasible) {i j} (hres : T.to_partition.rowg i ∈ T.restricted) (hineg : T.to_matrix obj j / T.to_matrix i j < 0) : T.const obj 0 ≤ (T.pivot i j).const obj 0 := have obj ≠ i, from λ hor, begin subst hor, by_cases h0 : T.to_matrix obj j = 0, { simp [lt_irrefl, *] at * }, { simp [div_self h0, not_lt_of_le zero_le_one, *] at * } end, by simp only [le_add_iff_nonneg_right, sub_eq_add_neg, neg_nonneg, mul_assoc, div_eq_mul_inv, mul_left_comm (T.to_matrix obj j), const_pivot_of_ne _ this]; exact mul_nonpos_of_nonneg_of_nonpos (hT _ hres) (le_of_lt hineg) lemma const_eq_zero_of_const_obj_eq {T : tableau m n} {obj : fin m} (hT : T.feasible) {i j} (hc : T.to_matrix obj j ≠ 0) (hrc : T.to_matrix i j ≠ 0) (hobjr : obj ≠ i) (hobj : (T.pivot i j).const obj 0 = T.const obj 0) : T.const i 0 = 0 := by rw [const_pivot_of_ne _ hobjr, sub_eq_iff_eq_add, ← sub_eq_iff_eq_add', sub_self, eq_comm, div_eq_mul_inv, mul_eq_zero, mul_eq_zero, inv_eq_zero] at hobj; tauto end tableau
95071833ba9cef520d3b451d387032120759d527
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_safe_log_issue.lean
f0df3dcd4f05655bb6f4b2d0facd3e350f0d18f3
[ "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
676
lean
import data.real open real namespace safe definition pos (x : ℝ) := x > 0 constants (exp : ℝ → ℝ) constants (safe_log : Π (x : ℝ), pos x → ℝ) lemma pos_add {x y : ℝ} : pos x → pos y → pos (x + y) := sorry lemma pos_mul {x y : ℝ} : pos x → pos y → pos (x * y) := sorry lemma log_mul [simp] : ∀ (x y : ℝ) (x_pos : pos x) (y_pos : pos y), safe_log (x * y) (pos_mul x_pos y_pos) = safe_log x x_pos + safe_log y y_pos := sorry example (x y z w : ℝ) (x_pos : pos x) (y_pos : pos y) (z_pos : pos z) (w_pos : pos w) : x * y = z + w → safe_log (z + w) (pos_add z_pos w_pos) = safe_log x x_pos + safe_log y y_pos := by inst_simp end safe
8b638d2b15d4ba04ed7a542db0fb6f41c9a60efc
0003047346476c031128723dfd16fe273c6bc605
/src/data/set/intervals.lean
1749bef71fc2f48c679ccc4935ad07812d841d49
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,877
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Intervals Naming conventions: `i`: infinite `o`: open `c`: closed Each interval has the name `I` + letter for left side + letter for right side TODO: This is just the beginning; a lot of rules are missing -/ import data.set.lattice algebra.order algebra.order_functions import tactic.linarith namespace set open set section intervals variables {α : Type*} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ lemma Iio_ne_empty [no_bot_order α] (a : α) : Iio a ≠ ∅ := ne_empty_iff_exists_mem.2 (no_bot a) lemma Ioi_ne_empty [no_top_order α] (a : α) : Ioi a ≠ ∅ := ne_empty_iff_exists_mem.2 (no_top a) lemma Iic_ne_empty (b : α) : Iic b ≠ ∅ := ne_empty_iff_exists_mem.2 ⟨b, le_refl b⟩ lemma Ici_ne_empty (a : α) : Ici a ≠ ∅ := ne_empty_iff_exists_mem.2 ⟨a, le_refl a⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ end intervals section partial_order variables {α : Type*} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] lemma Ico_diff_Ioo_eq_singleton (h : a < b) : Ico a b \ Ioo a b = {a} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact eq.symm (classical.by_contradiction (λ ne, h (lt_of_le_of_ne ax ne) xb)) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, (lt_irrefl x).elim⟩ } end lemma Icc_diff_Ico_eq_singleton (h : a ≤ b) : Icc a b \ Ico a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ ne, h ax (lt_of_le_of_ne xb ne)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end end partial_order section linear_order variables {α : Type*} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ end linear_order section decidable_linear_order variables {α : Type*} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b := set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) := set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} lemma Ioo_inter_Ioo {a b c d : α} : Ioo a b ∩ Ioo c d = Ioo (max a c) (min b d) := set.ext $ by simp [iff_def, Ioo, lt_min_iff, max_lt_iff] {contextual := tt} end decidable_linear_order end set
1de7337eef2312142daae1067e86fa1faf0aa77c
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/stage0/src/Leanpkg.lean
baca20288c36230b1ce33642b34d5a82bf49bebc
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,886
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich -/ import Leanpkg.Resolve import Leanpkg.Git import Leanpkg.Build import Lean.Util.Paths open System namespace Leanpkg def readManifest : IO Manifest := do let m ← Manifest.fromFile leanpkgTomlFn if m.leanVersion ≠ leanVersionString then IO.eprintln $ "\nWARNING: Lean version mismatch: installed version is " ++ leanVersionString ++ ", but package requires " ++ m.leanVersion ++ "\n" return m def writeManifest (manifest : Lean.Syntax) (fn : FilePath) : IO Unit := do IO.FS.writeFile fn manifest.reprint.get! def lockFileName : System.FilePath := ⟨".leanpkg-lock"⟩ partial def withLockFile (x : IO α) : IO α := do acquire try x finally IO.FS.removeFile lockFileName where acquire (firstTime := true) := try -- TODO: lock file should ideally contain PID if !System.Platform.isWindows then discard <| IO.FS.Handle.mkPrim lockFileName "wx" else -- `x` mode doesn't seem to work on Windows even though it's listed at -- https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=msvc-160 -- ...? Let's use the slightly racy approach then. if ← lockFileName.pathExists then throw <| IO.Error.alreadyExists none 0 "" discard <| IO.FS.Handle.mk lockFileName IO.FS.Mode.write catch | IO.Error.alreadyExists .. => do if firstTime then IO.eprintln s!"Waiting for prior leanpkg invocation to finish... (remove '{lockFileName}' if stuck)" IO.sleep (ms := 300) acquire (firstTime := false) | e => throw e def getRootPart (pkg : FilePath := ".") : IO Lean.Name := do let entries ← pkg.readDir match entries.filter (FilePath.extension ·.fileName == "lean") with | #[rootFile] => FilePath.withExtension rootFile.fileName "" |>.toString | #[] => throw <| IO.userError s!"no '.lean' file found in {← IO.FS.realPath "."}" | _ => throw <| IO.userError s!"{← IO.FS.realPath "."} must contain a unique '.lean' file as the package root" structure Configuration extends Lean.LeanPaths := moreDeps : List FilePath def configure : IO Configuration := do let d ← readManifest IO.eprintln $ "configuring " ++ d.name ++ " " ++ d.version let assg ← solveDeps d let paths ← constructPath assg let mut moreDeps := [leanpkgTomlFn] for path in paths do unless path == FilePath.mk "." / "." do -- build recursively -- TODO: share build of common dependencies execCmd { cmd := (← IO.appPath).toString cwd := path args := #["build"] } moreDeps := (path / Build.buildPath / (← getRootPart path).toString |>.withExtension "olean") :: moreDeps return { oleanPath := paths.map (· / Build.buildPath) srcPath := paths moreDeps } def execMake (makeArgs : List String) (cfg : Build.Config) : IO Unit := withLockFile do let manifest ← readManifest let leanArgs := (match manifest.timeout with | some t => ["-T", toString t] | none => []) ++ cfg.leanArgs let mut spawnArgs := { cmd := "sh" cwd := manifest.effectivePath args := #["-c", s!"\"{← IO.appDir}/leanmake\" PKG={cfg.pkg} LEAN_OPTS=\"{" ".intercalate leanArgs}\" LEAN_PATH=\"{cfg.leanPath}\" {" ".intercalate makeArgs} MORE_DEPS+=\"{" ".intercalate (cfg.moreDeps.map toString)}\" >&2"] } execCmd spawnArgs def buildImports (imports : List String) (leanArgs : List String) : IO Unit := do unless ← leanpkgTomlFn.pathExists do return let manifest ← readManifest let cfg ← configure let imports := imports.map (·.toName) let root ← getRootPart let localImports := imports.filter (·.getRoot == root) if localImports != [] then let buildCfg : Build.Config := { pkg := root, leanArgs, leanPath := cfg.oleanPath.toString, moreDeps := cfg.moreDeps } if ← FilePath.pathExists "Makefile" then let oleans := localImports.map fun i => Lean.modToFilePath "build" i "olean" |>.toString execMake oleans buildCfg else Build.buildModules buildCfg localImports IO.println <| Lean.toJson cfg.toLeanPaths def build (makeArgs leanArgs : List String) : IO Unit := do let cfg ← configure let root ← getRootPart let buildCfg : Build.Config := { pkg := root, leanArgs, leanPath := cfg.oleanPath.toString, moreDeps := cfg.moreDeps } if makeArgs != [] || (← FilePath.pathExists "Makefile") then execMake makeArgs buildCfg else Build.buildModules buildCfg [root] def initGitignoreContents := "/build " def initPkg (n : String) (fromNew : Bool) : IO Unit := do IO.FS.writeFile leanpkgTomlFn s!"[package] name = \"{n}\" version = \"0.1\" lean_version = \"{leanVersionString}\" " IO.FS.writeFile ⟨s!"{n.capitalize}.lean"⟩ "def main : IO Unit := IO.println \"Hello, world!\" " let h ← IO.FS.Handle.mk ⟨".gitignore"⟩ IO.FS.Mode.append (bin := false) h.putStr initGitignoreContents unless ← System.FilePath.isDir ⟨".git"⟩ do (do execCmd {cmd := "git", args := #["init", "-q"]} unless upstreamGitBranch = "master" do execCmd {cmd := "git", args := #["checkout", "-B", upstreamGitBranch]} ) <|> IO.eprintln "WARNING: failed to initialize git repository" def init (n : String) := initPkg n false def usage := "Lean package manager, version " ++ uiLeanVersionString ++ " Usage: leanpkg <command> init <name> create a Lean package in the current directory configure download and build dependencies build [<args>] configure and build *.olean files See `leanpkg help <command>` for more information on a specific command." def main : (cmd : String) → (leanpkgArgs leanArgs : List String) → IO Unit | "init", [Name], [] => init Name | "configure", [], [] => discard <| configure | "print-paths", leanpkgArgs, leanArgs => buildImports leanpkgArgs leanArgs | "build", makeArgs, leanArgs => build makeArgs leanArgs | "help", ["configure"], [] => IO.println "Download dependencies Usage: leanpkg configure This command sets up the `build/deps` directory. For each (transitive) git dependency, the specified commit is checked out into a sub-directory of `build/deps`. If there are dependencies on multiple versions of the same package, the version materialized is undefined. No copy is made of local dependencies." | "help", ["build"], [] => IO.println "download dependencies and build *.olean files Usage: leanpkg build [<leanmake-args>] [-- <lean-args>] This command invokes `leanpkg configure` followed by `leanmake <leanmake-args> LEAN_OPTS=<lean-args>`. If defined, the `package.timeout` configuration value is passed to Lean via its `-T` parameter. If no <lean-args> are given, only .olean files will be produced in `build/`. If `lib` or `bin` is passed instead, the extracted C code is compiled with `c++` and a static library in `build/lib` or an executable in `build/bin`, respectively, is created. `leanpkg build bin` requires a declaration of name `main` in the root namespace, which must return `IO Unit` or `IO UInt32` (the exit code) and may accept the program's command line arguments as a `List String` parameter. NOTE: building and linking dependent libraries currently has to be done manually, e.g. ``` $ (cd a; leanpkg build lib) $ (cd b; leanpkg build bin LINK_OPTS=../a/build/lib/libA.a) ```" | "help", ["init"], [] => IO.println "Create a new Lean package in the current directory Usage: leanpkg init <name> This command creates a new Lean package with the given name in the current directory." | "help", _, [] => IO.println usage | _, _, _ => throw <| IO.userError usage private def splitCmdlineArgsCore : List String → List String × List String | [] => ([], []) | (arg::args) => if arg == "--" then ([], args) else let (outerArgs, innerArgs) := splitCmdlineArgsCore args (arg::outerArgs, innerArgs) def splitCmdlineArgs : List String → IO (String × List String × List String) | [] => throw <| IO.userError usage | [cmd] => return (cmd, [], []) | (cmd::rest) => let (outerArgs, innerArgs) := splitCmdlineArgsCore rest return (cmd, outerArgs, innerArgs) end Leanpkg def main (args : List String) : IO UInt32 := do try Lean.enableInitializersExecution Lean.initSearchPath none -- HACK let (cmd, outerArgs, innerArgs) ← Leanpkg.splitCmdlineArgs args Leanpkg.main cmd outerArgs innerArgs pure 0 catch e => IO.eprintln e -- avoid "uncaught exception: ..." pure 1
aecee6647bc37548d30ef50b213ada83e68fae60
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/complex/upper_half_plane/metric.lean
39d5417caffa58ee443683ae9bdde0c241071506
[ "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
17,514
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 analysis.complex.upper_half_plane.topology import analysis.special_functions.arsinh import geometry.euclidean.inversion /-! # Metric on the upper half-plane In this file we define a `metric_space` structure on the `upper_half_plane`. We use hyperbolic (Poincaré) distance given by `dist z w = 2 * arsinh (dist (z : ℂ) w / (2 * real.sqrt (z.im * w.im)))` instead of the induced Euclidean distance because the hyperbolic distance is invariant under holomorphic automorphisms of the upper half-plane. However, we ensure that the projection to `topological_space` is definitionally equal to the induced topological space structure. We also prove that a metric ball/closed ball/sphere in Poincaré metric is a Euclidean ball/closed ball/sphere with another center and radius. -/ noncomputable theory open_locale upper_half_plane complex_conjugate nnreal topology matrix_groups open set metric filter real variables {z w : ℍ} {r R : ℝ} namespace upper_half_plane instance : has_dist ℍ := ⟨λ z w, 2 * arsinh (dist (z : ℂ) w / (2 * sqrt (z.im * w.im)))⟩ lemma dist_eq (z w : ℍ) : dist z w = 2 * arsinh (dist (z : ℂ) w / (2 * sqrt (z.im * w.im))) := rfl lemma sinh_half_dist (z w : ℍ) : sinh (dist z w / 2) = dist (z : ℂ) w / (2 * sqrt (z.im * w.im)) := by rw [dist_eq, mul_div_cancel_left (arsinh _) two_ne_zero, sinh_arsinh] lemma cosh_half_dist (z w : ℍ) : cosh (dist z w / 2) = dist (z : ℂ) (conj (w : ℂ)) / (2 * sqrt (z.im * w.im)) := begin have H₁ : (2 ^ 2 : ℝ) = 4, by norm_num1, have H₂ : 0 < z.im * w.im, from mul_pos z.im_pos w.im_pos, have H₃ : 0 < 2 * sqrt (z.im * w.im), from mul_pos two_pos (sqrt_pos.2 H₂), rw [← sq_eq_sq (cosh_pos _).le (div_nonneg dist_nonneg H₃.le), cosh_sq', sinh_half_dist, div_pow, div_pow, one_add_div (pow_ne_zero 2 H₃.ne'), mul_pow, sq_sqrt H₂.le, H₁], congr' 1, simp only [complex.dist_eq, complex.sq_abs, complex.norm_sq_sub, complex.norm_sq_conj, complex.conj_conj, complex.mul_re, complex.conj_re, complex.conj_im, coe_im], ring end lemma tanh_half_dist (z w : ℍ) : tanh (dist z w / 2) = dist (z : ℂ) w / dist (z : ℂ) (conj ↑w) := begin rw [tanh_eq_sinh_div_cosh, sinh_half_dist, cosh_half_dist, div_div_div_comm, div_self, div_one], exact (mul_pos (zero_lt_two' ℝ) (sqrt_pos.2 $ mul_pos z.im_pos w.im_pos)).ne' end lemma exp_half_dist (z w : ℍ) : exp (dist z w / 2) = (dist (z : ℂ) w + dist (z : ℂ) (conj ↑w)) / (2 * sqrt (z.im * w.im)) := by rw [← sinh_add_cosh, sinh_half_dist, cosh_half_dist, add_div] lemma cosh_dist (z w : ℍ) : cosh (dist z w) = 1 + dist (z : ℂ) w ^ 2 / (2 * z.im * w.im) := by rw [dist_eq, cosh_two_mul, cosh_sq', add_assoc, ← two_mul, sinh_arsinh, div_pow, mul_pow, sq_sqrt (mul_pos z.im_pos w.im_pos).le, sq (2 : ℝ), mul_assoc, ← mul_div_assoc, mul_assoc, mul_div_mul_left _ _ (two_ne_zero' ℝ)] lemma sinh_half_dist_add_dist (a b c : ℍ) : sinh ((dist a b + dist b c) / 2) = (dist (a : ℂ) b * dist (c : ℂ) (conj ↑b) + dist (b : ℂ) c * dist (a : ℂ) (conj ↑b)) / (2 * sqrt (a.im * c.im) * dist (b : ℂ) (conj ↑b)) := begin simp only [add_div _ _ (2 : ℝ), sinh_add, sinh_half_dist, cosh_half_dist, div_mul_div_comm], rw [← add_div, complex.dist_self_conj, coe_im, abs_of_pos b.im_pos, mul_comm (dist ↑b _), dist_comm (b : ℂ), complex.dist_conj_comm, mul_mul_mul_comm, mul_mul_mul_comm _ _ _ b.im], congr' 2, rw [sqrt_mul, sqrt_mul, sqrt_mul, mul_comm (sqrt a.im), mul_mul_mul_comm, mul_self_sqrt, mul_comm]; exact (im_pos _).le end protected lemma dist_comm (z w : ℍ) : dist z w = dist w z := by simp only [dist_eq, dist_comm (z : ℂ), mul_comm] lemma dist_le_iff_le_sinh : dist z w ≤ r ↔ dist (z : ℂ) w / (2 * sqrt (z.im * w.im)) ≤ sinh (r / 2) := by rw [← div_le_div_right (zero_lt_two' ℝ), ← sinh_le_sinh, sinh_half_dist] lemma dist_eq_iff_eq_sinh : dist z w = r ↔ dist (z : ℂ) w / (2 * sqrt (z.im * w.im)) = sinh (r / 2) := by rw [← div_left_inj' (two_ne_zero' ℝ), ← sinh_inj, sinh_half_dist] lemma dist_eq_iff_eq_sq_sinh (hr : 0 ≤ r) : dist z w = r ↔ dist (z : ℂ) w ^ 2 / (4 * z.im * w.im) = sinh (r / 2) ^ 2 := begin rw [dist_eq_iff_eq_sinh, ← sq_eq_sq, div_pow, mul_pow, sq_sqrt, mul_assoc], { norm_num }, { exact (mul_pos z.im_pos w.im_pos).le }, { exact div_nonneg dist_nonneg (mul_nonneg zero_le_two $ sqrt_nonneg _) }, { exact sinh_nonneg_iff.2 (div_nonneg hr zero_le_two) } end protected lemma dist_triangle (a b c : ℍ) : dist a c ≤ dist a b + dist b c := begin rw [dist_le_iff_le_sinh, sinh_half_dist_add_dist, div_mul_eq_div_div _ _ (dist _ _), le_div_iff, div_mul_eq_mul_div], { exact div_le_div_of_le (mul_nonneg zero_le_two (sqrt_nonneg _)) (euclidean_geometry.mul_dist_le_mul_dist_add_mul_dist (a : ℂ) b c (conj ↑b)) }, { rw [dist_comm, dist_pos, ne.def, complex.conj_eq_iff_im], exact b.im_ne_zero } end lemma dist_le_dist_coe_div_sqrt (z w : ℍ) : dist z w ≤ dist (z : ℂ) w / sqrt (z.im * w.im) := begin rw [dist_le_iff_le_sinh, ← div_mul_eq_div_div_swap, self_le_sinh_iff], exact div_nonneg dist_nonneg (mul_nonneg zero_le_two (sqrt_nonneg _)) end /-- An auxiliary `metric_space` instance on the upper half-plane. This instance has bad projection to `topological_space`. We replace it later. -/ def metric_space_aux : metric_space ℍ := { dist := dist, dist_self := λ z, by rw [dist_eq, dist_self, zero_div, arsinh_zero, mul_zero], dist_comm := upper_half_plane.dist_comm, dist_triangle := upper_half_plane.dist_triangle, eq_of_dist_eq_zero := λ z w h, by simpa [dist_eq, real.sqrt_eq_zero', (mul_pos z.im_pos w.im_pos).not_le, subtype.coe_inj] using h } open complex lemma cosh_dist' (z w : ℍ) : real.cosh (dist z w) = ((z.re - w.re) ^ 2 + z.im ^ 2 + w.im ^ 2) / (2 * z.im * w.im) := have H : 0 < 2 * z.im * w.im, from mul_pos (mul_pos two_pos z.im_pos) w.im_pos, by { field_simp [cosh_dist, complex.dist_eq, complex.sq_abs, norm_sq_apply, H, H.ne'], ring } /-- Euclidean center of the circle with center `z` and radius `r` in the hyperbolic metric. -/ def center (z : ℍ) (r : ℝ) : ℍ := ⟨⟨z.re, z.im * cosh r⟩, mul_pos z.im_pos (cosh_pos _)⟩ @[simp] lemma center_re (z r) : (center z r).re = z.re := rfl @[simp] lemma center_im (z r) : (center z r).im = z.im * cosh r := rfl @[simp] lemma center_zero (z : ℍ) : center z 0 = z := subtype.ext $ ext rfl $ by rw [coe_im, coe_im, center_im, real.cosh_zero, mul_one] lemma dist_coe_center_sq (z w : ℍ) (r : ℝ) : dist (z : ℂ) (w.center r) ^ 2 = 2 * z.im * w.im * (cosh (dist z w) - cosh r) + (w.im * sinh r) ^ 2 := begin have H : 2 * z.im * w.im ≠ 0, by apply_rules [mul_ne_zero, two_ne_zero, im_ne_zero], simp only [complex.dist_eq, complex.sq_abs, norm_sq_apply, coe_re, coe_im, center_re, center_im, cosh_dist', mul_div_cancel' _ H, sub_sq z.im, mul_pow, real.cosh_sq, sub_re, sub_im, mul_sub, ← sq], ring end lemma dist_coe_center (z w : ℍ) (r : ℝ) : dist (z : ℂ) (w.center r) = sqrt (2 * z.im * w.im * (cosh (dist z w) - cosh r) + (w.im * sinh r) ^ 2) := by rw [← sqrt_sq dist_nonneg, dist_coe_center_sq] lemma cmp_dist_eq_cmp_dist_coe_center (z w : ℍ) (r : ℝ) : cmp (dist z w) r = cmp (dist (z : ℂ) (w.center r)) (w.im * sinh r) := begin letI := metric_space_aux, cases lt_or_le r 0 with hr₀ hr₀, { transitivity ordering.gt, exacts [(hr₀.trans_le dist_nonneg).cmp_eq_gt, ((mul_neg_of_pos_of_neg w.im_pos (sinh_neg_iff.2 hr₀)).trans_le dist_nonneg).cmp_eq_gt.symm] }, have hr₀' : 0 ≤ w.im * sinh r, from mul_nonneg w.im_pos.le (sinh_nonneg_iff.2 hr₀), have hzw₀ : 0 < 2 * z.im * w.im, from mul_pos (mul_pos two_pos z.im_pos) w.im_pos, simp only [← cosh_strict_mono_on.cmp_map_eq dist_nonneg hr₀, ← (@strict_mono_on_pow ℝ _ _ two_pos).cmp_map_eq dist_nonneg hr₀', dist_coe_center_sq], rw [← cmp_mul_pos_left hzw₀, ← cmp_sub_zero, ← mul_sub, ← cmp_add_right, zero_add], end lemma dist_eq_iff_dist_coe_center_eq : dist z w = r ↔ dist (z : ℂ) (w.center r) = w.im * sinh r := eq_iff_eq_of_cmp_eq_cmp (cmp_dist_eq_cmp_dist_coe_center z w r) @[simp] lemma dist_self_center (z : ℍ) (r : ℝ) : dist (z : ℂ) (z.center r) = z.im * (cosh r - 1) := begin rw [dist_of_re_eq (z.center_re r).symm, dist_comm, real.dist_eq, mul_sub, mul_one], exact abs_of_nonneg (sub_nonneg.2 $ le_mul_of_one_le_right z.im_pos.le (one_le_cosh _)) end @[simp] lemma dist_center_dist (z w : ℍ) : dist (z : ℂ) (w.center (dist z w)) = w.im * sinh (dist z w) := dist_eq_iff_dist_coe_center_eq.1 rfl lemma dist_lt_iff_dist_coe_center_lt : dist z w < r ↔ dist (z : ℂ) (w.center r) < w.im * sinh r := lt_iff_lt_of_cmp_eq_cmp (cmp_dist_eq_cmp_dist_coe_center z w r) lemma lt_dist_iff_lt_dist_coe_center : r < dist z w ↔ w.im * sinh r < dist (z : ℂ) (w.center r) := lt_iff_lt_of_cmp_eq_cmp (cmp_eq_cmp_symm.1 $ cmp_dist_eq_cmp_dist_coe_center z w r) lemma dist_le_iff_dist_coe_center_le : dist z w ≤ r ↔ dist (z : ℂ) (w.center r) ≤ w.im * sinh r := le_iff_le_of_cmp_eq_cmp (cmp_dist_eq_cmp_dist_coe_center z w r) lemma le_dist_iff_le_dist_coe_center : r < dist z w ↔ w.im * sinh r < dist (z : ℂ) (w.center r) := lt_iff_lt_of_cmp_eq_cmp (cmp_eq_cmp_symm.1 $ cmp_dist_eq_cmp_dist_coe_center z w r) /-- For two points on the same vertical line, the distance is equal to the distance between the logarithms of their imaginary parts. -/ lemma dist_of_re_eq (h : z.re = w.re) : dist z w = dist (log z.im) (log w.im) := begin have h₀ : 0 < z.im / w.im, from div_pos z.im_pos w.im_pos, rw [dist_eq_iff_dist_coe_center_eq, real.dist_eq, ← abs_sinh, ← log_div z.im_ne_zero w.im_ne_zero, sinh_log h₀, dist_of_re_eq, coe_im, coe_im, center_im, cosh_abs, cosh_log h₀, inv_div]; [skip, exact h], nth_rewrite 3 [← abs_of_pos w.im_pos], simp only [← _root_.abs_mul, coe_im, real.dist_eq], congr' 1, field_simp [z.im_pos, w.im_pos, z.im_ne_zero, w.im_ne_zero], ring end /-- Hyperbolic distance between two points is greater than or equal to the distance between the logarithms of their imaginary parts. -/ lemma dist_log_im_le (z w : ℍ) : dist (log z.im) (log w.im) ≤ dist z w := calc dist (log z.im) (log w.im) = @dist ℍ _ ⟨⟨0, z.im⟩, z.im_pos⟩ ⟨⟨0, w.im⟩, w.im_pos⟩ : eq.symm $ @dist_of_re_eq ⟨⟨0, z.im⟩, z.im_pos⟩ ⟨⟨0, w.im⟩, w.im_pos⟩ rfl ... ≤ dist z w : mul_le_mul_of_nonneg_left (arsinh_le_arsinh.2 $ div_le_div_of_le (mul_nonneg zero_le_two (sqrt_nonneg _)) $ by simpa [sqrt_sq_eq_abs] using complex.abs_im_le_abs (z - w)) zero_le_two lemma im_le_im_mul_exp_dist (z w : ℍ) : z.im ≤ w.im * exp (dist z w) := begin rw [← div_le_iff' w.im_pos, ← exp_log z.im_pos, ← exp_log w.im_pos, ← real.exp_sub, exp_le_exp], exact (le_abs_self _).trans (dist_log_im_le z w) end lemma im_div_exp_dist_le (z w : ℍ) : z.im / exp (dist z w) ≤ w.im := (div_le_iff (exp_pos _)).2 (im_le_im_mul_exp_dist z w) /-- An upper estimate on the complex distance between two points in terms of the hyperbolic distance and the imaginary part of one of the points. -/ lemma dist_coe_le (z w : ℍ) : dist (z : ℂ) w ≤ w.im * (exp (dist z w) - 1) := calc dist (z : ℂ) w ≤ dist (z : ℂ) (w.center (dist z w)) + dist (w : ℂ) (w.center (dist z w)) : dist_triangle_right _ _ _ ... = w.im * (exp (dist z w) - 1) : by rw [dist_center_dist, dist_self_center, ← mul_add, ← add_sub_assoc, real.sinh_add_cosh] /-- An upper estimate on the complex distance between two points in terms of the hyperbolic distance and the imaginary part of one of the points. -/ lemma le_dist_coe (z w : ℍ) : w.im * (1 - exp (-dist z w)) ≤ dist (z : ℂ) w := calc w.im * (1 - exp (-dist z w)) = dist (z : ℂ) (w.center (dist z w)) - dist (w : ℂ) (w.center (dist z w)) : by { rw [dist_center_dist, dist_self_center, ← real.cosh_sub_sinh], ring } ... ≤ dist (z : ℂ) w : sub_le_iff_le_add.2 $ dist_triangle _ _ _ /-- The hyperbolic metric on the upper half plane. We ensure that the projection to `topological_space` is definitionally equal to the subtype topology. -/ instance : metric_space ℍ := metric_space_aux.replace_topology $ begin refine le_antisymm (continuous_id_iff_le.1 _) _, { refine (@continuous_iff_continuous_dist _ _ metric_space_aux.to_pseudo_metric_space _ _).2 _, have : ∀ (x : ℍ × ℍ), 2 * real.sqrt (x.1.im * x.2.im) ≠ 0, from λ x, mul_ne_zero two_ne_zero (real.sqrt_pos.2 $ mul_pos x.1.im_pos x.2.im_pos).ne', -- `continuity` fails to apply `continuous.div` apply_rules [continuous.div, continuous.mul, continuous_const, continuous.arsinh, continuous.dist, continuous_coe.comp, continuous_fst, continuous_snd, real.continuous_sqrt.comp, continuous_im.comp] }, { letI : metric_space ℍ := metric_space_aux, refine le_of_nhds_le_nhds (λ z, _), rw [nhds_induced], refine (nhds_basis_ball.le_basis_iff (nhds_basis_ball.comap _)).2 (λ R hR, _), have h₁ : 1 < R / im z + 1, from lt_add_of_pos_left _ (div_pos hR z.im_pos), have h₀ : 0 < R / im z + 1, from one_pos.trans h₁, refine ⟨log (R / im z + 1), real.log_pos h₁, _⟩, refine λ w hw, (dist_coe_le w z).trans_lt _, rwa [← lt_div_iff' z.im_pos, sub_lt_iff_lt_add, ← real.lt_log_iff_exp_lt h₀] } end lemma im_pos_of_dist_center_le {z : ℍ} {r : ℝ} {w : ℂ} (h : dist w (center z r) ≤ z.im * sinh r) : 0 < w.im := calc 0 < z.im * (cosh r - sinh r) : mul_pos z.im_pos (sub_pos.2 $ sinh_lt_cosh _) ... = (z.center r).im - z.im * sinh r : mul_sub _ _ _ ... ≤ (z.center r).im - dist (z.center r : ℂ) w : sub_le_sub_left (by rwa [dist_comm]) _ ... ≤ w.im : sub_le_comm.1 $ (le_abs_self _).trans (abs_im_le_abs $ z.center r - w) lemma image_coe_closed_ball (z : ℍ) (r : ℝ) : (coe : ℍ → ℂ) '' closed_ball z r = closed_ball (z.center r) (z.im * sinh r) := begin ext w, split, { rintro ⟨w, hw, rfl⟩, exact dist_le_iff_dist_coe_center_le.1 hw }, { intro hw, lift w to ℍ using im_pos_of_dist_center_le hw, exact mem_image_of_mem _ (dist_le_iff_dist_coe_center_le.2 hw) }, end lemma image_coe_ball (z : ℍ) (r : ℝ) : (coe : ℍ → ℂ) '' ball z r = ball (z.center r) (z.im * sinh r) := begin ext w, split, { rintro ⟨w, hw, rfl⟩, exact dist_lt_iff_dist_coe_center_lt.1 hw }, { intro hw, lift w to ℍ using im_pos_of_dist_center_le (ball_subset_closed_ball hw), exact mem_image_of_mem _ (dist_lt_iff_dist_coe_center_lt.2 hw) }, end lemma image_coe_sphere (z : ℍ) (r : ℝ) : (coe : ℍ → ℂ) '' sphere z r = sphere (z.center r) (z.im * sinh r) := begin ext w, split, { rintro ⟨w, hw, rfl⟩, exact dist_eq_iff_dist_coe_center_eq.1 hw }, { intro hw, lift w to ℍ using im_pos_of_dist_center_le (sphere_subset_closed_ball hw), exact mem_image_of_mem _ (dist_eq_iff_dist_coe_center_eq.2 hw) }, end instance : proper_space ℍ := begin refine ⟨λ z r, _⟩, rw [← inducing_coe.is_compact_iff, image_coe_closed_ball], apply is_compact_closed_ball end lemma isometry_vertical_line (a : ℝ) : isometry (λ y, mk ⟨a, exp y⟩ (exp_pos y)) := begin refine isometry.of_dist_eq (λ y₁ y₂, _), rw [dist_of_re_eq], exacts [congr_arg2 _ (log_exp _) (log_exp _), rfl] end lemma isometry_real_vadd (a : ℝ) : isometry ((+ᵥ) a : ℍ → ℍ) := isometry.of_dist_eq $ λ y₁ y₂, by simp only [dist_eq, coe_vadd, vadd_im, dist_add_left] lemma isometry_pos_mul (a : {x : ℝ // 0 < x}) : isometry ((•) a : ℍ → ℍ) := begin refine isometry.of_dist_eq (λ y₁ y₂, _), simp only [dist_eq, coe_pos_real_smul, pos_real_im], congr' 2, rw [dist_smul₀, mul_mul_mul_comm, real.sqrt_mul (mul_self_nonneg _), real.sqrt_mul_self_eq_abs, real.norm_eq_abs, mul_left_comm], exact mul_div_mul_left _ _ (mt _root_.abs_eq_zero.1 a.2.ne') end /-- `SL(2, ℝ)` acts on the upper half plane as an isometry.-/ instance : has_isometric_smul SL(2, ℝ) ℍ := ⟨λ g, begin have h₀ : isometry (λ z, modular_group.S • z : ℍ → ℍ) := isometry.of_dist_eq (λ y₁ y₂, by { have h₁ : 0 ≤ im y₁ * im y₂ := mul_nonneg y₁.property.le y₂.property.le, have h₂ : complex.abs (y₁ * y₂) ≠ 0, { simp [y₁.ne_zero, y₂.ne_zero], }, simp only [dist_eq, modular_S_smul, inv_neg, neg_div, div_mul_div_comm, coe_mk, mk_im, div_one, complex.inv_im, complex.neg_im, coe_im, neg_neg, complex.norm_sq_neg, mul_eq_mul_left_iff, real.arsinh_inj, bit0_eq_zero, one_ne_zero, or_false, dist_neg_neg, mul_neg, neg_mul, dist_inv_inv₀ y₁.ne_zero y₂.ne_zero, ← absolute_value.map_mul, ← complex.norm_sq_mul, real.sqrt_div h₁, ← complex.abs_apply, mul_div (2 : ℝ), div_div_div_comm, div_self h₂, complex.norm_eq_abs], }), by_cases hc : g 1 0 = 0, { obtain ⟨u, v, h⟩ := exists_SL2_smul_eq_of_apply_zero_one_eq_zero g hc, rw h, exact (isometry_real_vadd v).comp (isometry_pos_mul u), }, { obtain ⟨u, v, w, h⟩ := exists_SL2_smul_eq_of_apply_zero_one_ne_zero g hc, rw h, exact (isometry_real_vadd w).comp (h₀.comp $ (isometry_real_vadd v).comp $ isometry_pos_mul u) } end⟩ end upper_half_plane
049785d239e2a58ea0e9cffb5bb280f934f08f84
4727251e0cd73359b15b664c3170e5d754078599
/src/order/succ_pred/basic.lean
a657e33acc0b5cddf8635a7e29ad4b19901e1cf2
[ "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
36,983
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.complete_lattice import order.cover import order.iterate import tactic.monotonicity /-! # Successor and predecessor This file defines successor and predecessor orders. `succ a`, the successor of an element `a : α` is the least element greater than `a`. `pred a` is the greatest element less than `a`. Typical examples include `ℕ`, `ℤ`, `ℕ+`, `fin n`, but also `enat`, the lexicographic order of a successor/predecessor order... ## Typeclasses * `succ_order`: Order equipped with a sensible successor function. * `pred_order`: Order equipped with a sensible predecessor function. * `is_succ_archimedean`: `succ_order` where `succ` iterated to an element gives all the greater ones. * `is_pred_archimedean`: `pred_order` where `pred` iterated to an element gives all the smaller ones. ## Implementation notes Maximal elements don't have a sensible successor. Thus the naïve typeclass ```lean class naive_succ_order (α : Type*) [preorder α] := (succ : α → α) (succ_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) (lt_succ_iff : ∀ {a b}, a < succ b ↔ a ≤ b) ``` can't apply to an `order_top` because plugging in `a = b = ⊤` into either of `succ_le_iff` and `lt_succ_iff` yields `⊤ < ⊤` (or more generally `m < m` for a maximal element `m`). The solution taken here is to remove the implications `≤ → <` and instead require that `a < succ a` for all non maximal elements (enforced by the combination of `le_succ` and the contrapositive of `max_of_succ_le`). The stricter condition of every element having a sensible successor can be obtained through the combination of `succ_order α` and `no_max_order α`. ## TODO Is `galois_connection pred succ` always true? If not, we should introduce ```lean class succ_pred_order (α : Type*) [preorder α] extends succ_order α, pred_order α := (pred_succ_gc : galois_connection (pred : α → α) succ) ``` `covby` should help here. -/ open function order_dual set variables {α : Type*} /-- Order equipped with a sensible successor function. -/ @[ext] class succ_order (α : Type*) [preorder α] := (succ : α → α) (le_succ : ∀ a, a ≤ succ a) (max_of_succ_le {a} : succ a ≤ a → is_max a) (succ_le_of_lt {a b} : a < b → succ a ≤ b) (le_of_lt_succ {a b} : a < succ b → a ≤ b) /-- Order equipped with a sensible predecessor function. -/ @[ext] class pred_order (α : Type*) [preorder α] := (pred : α → α) (pred_le : ∀ a, pred a ≤ a) (min_of_le_pred {a} : a ≤ pred a → is_min a) (le_pred_of_lt {a b} : a < b → a ≤ pred b) (le_of_pred_lt {a b} : pred a < b → a ≤ b) instance [preorder α] [succ_order α] : pred_order αᵒᵈ := { pred := to_dual ∘ succ_order.succ ∘ of_dual, pred_le := succ_order.le_succ, min_of_le_pred := λ _, succ_order.max_of_succ_le, le_pred_of_lt := λ a b h, succ_order.succ_le_of_lt h, le_of_pred_lt := λ a b, succ_order.le_of_lt_succ } instance [preorder α] [pred_order α] : succ_order αᵒᵈ := { succ := to_dual ∘ pred_order.pred ∘ of_dual, le_succ := pred_order.pred_le, max_of_succ_le := λ _, pred_order.min_of_le_pred, succ_le_of_lt := λ a b h, pred_order.le_pred_of_lt h, le_of_lt_succ := λ a b, pred_order.le_of_pred_lt } section preorder variables [preorder α] /-- A constructor for `succ_order α` usable when `α` has no maximal element. -/ def succ_order.of_succ_le_iff_of_le_lt_succ (succ : α → α) (hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) (hle_of_lt_succ : ∀ {a b}, a < succ b → a ≤ b) : succ_order α := { succ := succ, le_succ := λ a, (hsucc_le_iff.1 le_rfl).le, max_of_succ_le := λ a ha, (lt_irrefl a $ hsucc_le_iff.1 ha).elim, succ_le_of_lt := λ a b, hsucc_le_iff.2, le_of_lt_succ := λ a b, hle_of_lt_succ } /-- A constructor for `pred_order α` usable when `α` has no minimal element. -/ def pred_order.of_le_pred_iff_of_pred_le_pred (pred : α → α) (hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b) (hle_of_pred_lt : ∀ {a b}, pred a < b → a ≤ b) : pred_order α := { pred := pred, pred_le := λ a, (hle_pred_iff.1 le_rfl).le, min_of_le_pred := λ a ha, (lt_irrefl a $ hle_pred_iff.1 ha).elim, le_pred_of_lt := λ a b, hle_pred_iff.2, le_of_pred_lt := λ a b, hle_of_pred_lt } end preorder section linear_order variables [linear_order α] /-- A constructor for `succ_order α` for `α` a linear order. -/ @[simps] def succ_order.of_core (succ : α → α) (hn : ∀ {a}, ¬ is_max a → ∀ b, a < b ↔ succ a ≤ b) (hm : ∀ a, is_max a → succ a = a) : succ_order α := { succ := succ, succ_le_of_lt := λ a b, classical.by_cases (λ h hab, (hm a h).symm ▸ hab.le) (λ h, (hn h b).mp), le_succ := λ a, classical.by_cases (λ h, (hm a h).symm.le) (λ h, le_of_lt $ by simpa using (hn h a).not), le_of_lt_succ := λ a b hab, classical.by_cases (λ h, hm b h ▸ hab.le) (λ h, by simpa [hab] using (hn h a).not), max_of_succ_le := λ a, not_imp_not.mp $ λ h, by simpa using (hn h a).not } /-- A constructor for `pred_order α` for `α` a linear order. -/ @[simps] def pred_order.of_core {α} [linear_order α] (pred : α → α) (hn : ∀ {a}, ¬ is_min a → ∀ b, b ≤ pred a ↔ b < a) (hm : ∀ a, is_min a → pred a = a) : pred_order α := { pred := pred, le_pred_of_lt := λ a b, classical.by_cases (λ h hab, (hm b h).symm ▸ hab.le) (λ h, (hn h a).mpr), pred_le := λ a, classical.by_cases (λ h, (hm a h).le) (λ h, le_of_lt $ by simpa using (hn h a).not), le_of_pred_lt := λ a b hab, classical.by_cases (λ h, hm a h ▸ hab.le) (λ h, by simpa [hab] using (hn h b).not), min_of_le_pred := λ a, not_imp_not.mp $ λ h, by simpa using (hn h a).not } /-- A constructor for `succ_order α` usable when `α` is a linear order with no maximal element. -/ def succ_order.of_succ_le_iff (succ : α → α) (hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) : succ_order α := { succ := succ, le_succ := λ a, (hsucc_le_iff.1 le_rfl).le, max_of_succ_le := λ a ha, (lt_irrefl a $ hsucc_le_iff.1 ha).elim, succ_le_of_lt := λ a b, hsucc_le_iff.2, le_of_lt_succ := λ a b h, le_of_not_lt ((not_congr hsucc_le_iff).1 h.not_le) } /-- A constructor for `pred_order α` usable when `α` is a linear order with no minimal element. -/ def pred_order.of_le_pred_iff (pred : α → α) (hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b) : pred_order α := { pred := pred, pred_le := λ a, (hle_pred_iff.1 le_rfl).le, min_of_le_pred := λ a ha, (lt_irrefl a $ hle_pred_iff.1 ha).elim, le_pred_of_lt := λ a b, hle_pred_iff.2, le_of_pred_lt := λ a b h, le_of_not_lt ((not_congr hle_pred_iff).1 h.not_le) } end linear_order /-! ### Successor order -/ namespace order section preorder variables [preorder α] [succ_order α] {a b : α} /-- The successor of an element. If `a` is not maximal, then `succ a` is the least element greater than `a`. If `a` is maximal, then `succ a = a`. -/ def succ : α → α := succ_order.succ lemma le_succ : ∀ a : α, a ≤ succ a := succ_order.le_succ lemma max_of_succ_le {a : α} : succ a ≤ a → is_max a := succ_order.max_of_succ_le lemma succ_le_of_lt {a b : α} : a < b → succ a ≤ b := succ_order.succ_le_of_lt lemma le_of_lt_succ {a b : α} : a < succ b → a ≤ b := succ_order.le_of_lt_succ @[simp] lemma succ_le_iff_is_max : succ a ≤ a ↔ is_max a := ⟨max_of_succ_le, λ h, h $ le_succ _⟩ @[simp] lemma lt_succ_iff_not_is_max : a < succ a ↔ ¬ is_max a := ⟨not_is_max_of_lt, λ ha, (le_succ a).lt_of_not_le $ λ h, ha $ max_of_succ_le h⟩ alias lt_succ_iff_not_is_max ↔ _ order.lt_succ_of_not_is_max lemma wcovby_succ (a : α) : a ⩿ succ a := ⟨le_succ a, λ b hb, (succ_le_of_lt hb).not_lt⟩ lemma covby_succ_of_not_is_max (h : ¬ is_max a) : a ⋖ succ a := (wcovby_succ a).covby_of_lt $ lt_succ_of_not_is_max h lemma lt_succ_iff_of_not_is_max (ha : ¬ is_max a) : b < succ a ↔ b ≤ a := ⟨le_of_lt_succ, λ h, h.trans_lt $ lt_succ_of_not_is_max ha⟩ lemma succ_le_iff_of_not_is_max (ha : ¬ is_max a) : succ a ≤ b ↔ a < b := ⟨(lt_succ_of_not_is_max ha).trans_le, succ_le_of_lt⟩ @[simp, mono] lemma succ_le_succ (h : a ≤ b) : succ a ≤ succ b := begin by_cases hb : is_max b, { by_cases hba : b ≤ a, { exact (hb $ hba.trans $ le_succ _).trans (le_succ _) }, { exact succ_le_of_lt ((h.lt_of_not_le hba).trans_le $ le_succ b) } }, { rwa [succ_le_iff_of_not_is_max (λ ha, hb $ ha.mono h), lt_succ_iff_of_not_is_max hb] } end lemma succ_mono : monotone (succ : α → α) := λ a b, succ_le_succ lemma Iio_succ_of_not_is_max (ha : ¬ is_max a) : Iio (succ a) = Iic a := set.ext $ λ x, lt_succ_iff_of_not_is_max ha lemma Ici_succ_of_not_is_max (ha : ¬ is_max a) : Ici (succ a) = Ioi a := set.ext $ λ x, succ_le_iff_of_not_is_max ha lemma Ico_succ_right_of_not_is_max (hb : ¬ is_max b) : Ico a (succ b) = Icc a b := by rw [←Ici_inter_Iio, Iio_succ_of_not_is_max hb, Ici_inter_Iic] lemma Ioo_succ_right_of_not_is_max (hb : ¬ is_max b) : Ioo a (succ b) = Ioc a b := by rw [←Ioi_inter_Iio, Iio_succ_of_not_is_max hb, Ioi_inter_Iic] lemma Icc_succ_left_of_not_is_max (ha : ¬ is_max a) : Icc (succ a) b = Ioc a b := by rw [←Ici_inter_Iic, Ici_succ_of_not_is_max ha, Ioi_inter_Iic] lemma Ico_succ_left_of_not_is_max (ha : ¬ is_max a) : Ico (succ a) b = Ioo a b := by rw [←Ici_inter_Iio, Ici_succ_of_not_is_max ha, Ioi_inter_Iio] section no_max_order variables [no_max_order α] lemma lt_succ (a : α) : a < succ a := lt_succ_of_not_is_max $ not_is_max a lemma lt_succ_iff : a < succ b ↔ a ≤ b := lt_succ_iff_of_not_is_max $ not_is_max b lemma succ_le_iff : succ a ≤ b ↔ a < b := succ_le_iff_of_not_is_max $ not_is_max a @[simp] lemma succ_le_succ_iff : succ a ≤ succ b ↔ a ≤ b := ⟨λ h, le_of_lt_succ $ (lt_succ a).trans_le h, λ h, succ_le_of_lt $ h.trans_lt $ lt_succ b⟩ lemma succ_lt_succ_iff : succ a < succ b ↔ a < b := lt_iff_lt_of_le_iff_le' succ_le_succ_iff succ_le_succ_iff alias succ_le_succ_iff ↔ order.le_of_succ_le_succ _ alias succ_lt_succ_iff ↔ order.lt_of_succ_lt_succ order.succ_lt_succ lemma succ_strict_mono : strict_mono (succ : α → α) := λ a b, succ_lt_succ lemma covby_succ (a : α) : a ⋖ succ a := covby_succ_of_not_is_max $ not_is_max a @[simp] lemma Iio_succ (a : α) : Iio (succ a) = Iic a := Iio_succ_of_not_is_max $ not_is_max _ @[simp] lemma Ici_succ (a : α) : Ici (succ a) = Ioi a := Ici_succ_of_not_is_max $ not_is_max _ lemma Ico_succ_right (a b : α) : Ico a (succ b) = Icc a b := Ico_succ_right_of_not_is_max $ not_is_max _ lemma Ioo_succ_right (a b : α) : Ioo a (succ b) = Ioc a b := Ioo_succ_right_of_not_is_max $ not_is_max _ lemma Icc_succ_left (a b : α) : Icc (succ a) b = Ioc a b := Icc_succ_left_of_not_is_max $ not_is_max _ lemma Ico_succ_left (a b : α) : Ico (succ a) b = Ioo a b := Ico_succ_left_of_not_is_max $ not_is_max _ end no_max_order end preorder section partial_order variables [partial_order α] [succ_order α] {a b : α} @[simp] lemma succ_eq_iff_is_max : succ a = a ↔ is_max a := ⟨λ h, max_of_succ_le h.le, λ h, h.eq_of_ge $ le_succ _⟩ alias succ_eq_iff_is_max ↔ _ is_max.succ_eq lemma le_le_succ_iff : a ≤ b ∧ b ≤ succ a ↔ b = a ∨ b = succ a := begin refine ⟨λ h, or_iff_not_imp_left.2 $ λ hba : b ≠ a, h.2.antisymm (succ_le_of_lt $ h.1.lt_of_ne $ hba.symm), _⟩, rintro (rfl | rfl), { exact ⟨le_rfl, le_succ b⟩ }, { exact ⟨le_succ a, le_rfl⟩ } end lemma _root_.covby.succ_eq (h : a ⋖ b) : succ a = b := (succ_le_of_lt h.lt).eq_of_not_lt $ λ h', h.2 (lt_succ_of_not_is_max h.lt.not_is_max) h' lemma le_succ_iff_eq_or_le : a ≤ succ b ↔ a = succ b ∨ a ≤ b := begin by_cases hb : is_max b, { rw [hb.succ_eq, or_iff_right_of_imp le_of_eq] }, { rw [←lt_succ_iff_of_not_is_max hb, le_iff_eq_or_lt] } end lemma lt_succ_iff_eq_or_lt_of_not_is_max (hb : ¬ is_max b) : a < succ b ↔ a = b ∨ a < b := (lt_succ_iff_of_not_is_max hb).trans le_iff_eq_or_lt lemma Iic_succ (a : α) : Iic (succ a) = insert (succ a) (Iic a) := ext $ λ _, le_succ_iff_eq_or_le lemma Icc_succ_right (h : a ≤ succ b) : Icc a (succ b) = insert (succ b) (Icc a b) := by simp_rw [←Ici_inter_Iic, Iic_succ, inter_insert_of_mem (mem_Ici.2 h)] lemma Ioc_succ_right (h : a < succ b) : Ioc a (succ b) = insert (succ b) (Ioc a b) := by simp_rw [←Ioi_inter_Iic, Iic_succ, inter_insert_of_mem (mem_Ioi.2 h)] section no_max_order variables [no_max_order α] @[simp] lemma succ_eq_succ_iff : succ a = succ b ↔ a = b := by simp_rw [eq_iff_le_not_lt, succ_le_succ_iff, succ_lt_succ_iff] lemma succ_injective : injective (succ : α → α) := λ a b, succ_eq_succ_iff.1 lemma succ_ne_succ_iff : succ a ≠ succ b ↔ a ≠ b := succ_injective.ne_iff alias succ_ne_succ_iff ↔ _ order.succ_ne_succ lemma lt_succ_iff_eq_or_lt : a < succ b ↔ a = b ∨ a < b := lt_succ_iff.trans le_iff_eq_or_lt lemma succ_eq_iff_covby : succ a = b ↔ a ⋖ b := ⟨by { rintro rfl, exact covby_succ _ }, covby.succ_eq⟩ lemma Iio_succ_eq_insert (a : α) : Iio (succ a) = insert a (Iio a) := ext $ λ _, lt_succ_iff_eq_or_lt lemma Ico_succ_right_eq_insert (h : a ≤ b) : Ico a (succ b) = insert b (Ico a b) := by simp_rw [←Iio_inter_Ici, Iio_succ_eq_insert, insert_inter_of_mem (mem_Ici.2 h)] lemma Ioo_succ_right_eq_insert (h : a < b) : Ioo a (succ b) = insert b (Ioo a b) := by simp_rw [←Iio_inter_Ioi, Iio_succ_eq_insert, insert_inter_of_mem (mem_Ioi.2 h)] end no_max_order section order_top variables [order_top α] @[simp] lemma succ_top : succ (⊤ : α) = ⊤ := is_max_top.succ_eq @[simp] lemma succ_le_iff_eq_top : succ a ≤ a ↔ a = ⊤ := succ_le_iff_is_max.trans is_max_iff_eq_top @[simp] lemma lt_succ_iff_ne_top : a < succ a ↔ a ≠ ⊤ := lt_succ_iff_not_is_max.trans not_is_max_iff_ne_top end order_top section order_bot variables [order_bot α] [nontrivial α] lemma bot_lt_succ (a : α) : ⊥ < succ a := (lt_succ_of_not_is_max not_is_max_bot).trans_le $ succ_mono bot_le lemma succ_ne_bot (a : α) : succ a ≠ ⊥ := (bot_lt_succ a).ne' end order_bot end partial_order /-- There is at most one way to define the successors in a `partial_order`. -/ instance [partial_order α] : subsingleton (succ_order α) := ⟨begin introsI h₀ h₁, ext a, by_cases ha : is_max a, { exact (@is_max.succ_eq _ _ h₀ _ ha).trans ha.succ_eq.symm }, { exact @covby.succ_eq _ _ h₀ _ _ (covby_succ_of_not_is_max ha) } end⟩ section complete_lattice variables [complete_lattice α] [succ_order α] lemma succ_eq_infi (a : α) : succ a = ⨅ b (h : a < b), b := begin refine le_antisymm (le_infi (λ b, le_infi succ_le_of_lt)) _, obtain rfl | ha := eq_or_ne a ⊤, { rw succ_top, exact le_top }, exact infi₂_le _ (lt_succ_iff_ne_top.2 ha), end end complete_lattice /-! ### Predecessor order -/ section preorder variables [preorder α] [pred_order α] {a b : α} /-- The predecessor of an element. If `a` is not minimal, then `pred a` is the greatest element less than `a`. If `a` is minimal, then `pred a = a`. -/ def pred : α → α := pred_order.pred lemma pred_le : ∀ a : α, pred a ≤ a := pred_order.pred_le lemma min_of_le_pred {a : α} : a ≤ pred a → is_min a := pred_order.min_of_le_pred lemma le_pred_of_lt {a b : α} : a < b → a ≤ pred b := pred_order.le_pred_of_lt lemma le_of_pred_lt {a b : α} : pred a < b → a ≤ b := pred_order.le_of_pred_lt @[simp] lemma le_pred_iff_is_min : a ≤ pred a ↔ is_min a := ⟨min_of_le_pred, λ h, h $ pred_le _⟩ @[simp] lemma pred_lt_iff_not_is_min : pred a < a ↔ ¬ is_min a := ⟨not_is_min_of_lt, λ ha, (pred_le a).lt_of_not_le $ λ h, ha $ min_of_le_pred h⟩ alias pred_lt_iff_not_is_min ↔ _ order.pred_lt_of_not_is_min lemma pred_wcovby (a : α) : pred a ⩿ a := ⟨pred_le a, λ b hb, (le_of_pred_lt hb).not_lt⟩ lemma pred_covby_of_not_is_min (h : ¬ is_min a) : pred a ⋖ a := (pred_wcovby a).covby_of_lt $ pred_lt_of_not_is_min h lemma pred_lt_iff_of_not_is_min (ha : ¬ is_min a) : pred a < b ↔ a ≤ b := ⟨le_of_pred_lt, (pred_lt_of_not_is_min ha).trans_le⟩ lemma le_pred_iff_of_not_is_min (ha : ¬ is_min a) : b ≤ pred a ↔ b < a := ⟨λ h, h.trans_lt $ pred_lt_of_not_is_min ha, le_pred_of_lt⟩ @[simp, mono] lemma pred_le_pred {a b : α} (h : a ≤ b) : pred a ≤ pred b := succ_le_succ h.dual lemma pred_mono : monotone (pred : α → α) := λ a b, pred_le_pred lemma Ioi_pred_of_not_is_min (ha : ¬ is_min a) : Ioi (pred a) = Ici a := set.ext $ λ x, pred_lt_iff_of_not_is_min ha lemma Iic_pred_of_not_is_min (ha : ¬ is_min a) : Iic (pred a) = Iio a := set.ext $ λ x, le_pred_iff_of_not_is_min ha lemma Ioc_pred_left_of_not_is_min (ha : ¬ is_min a) : Ioc (pred a) b = Icc a b := by rw [←Ioi_inter_Iic, Ioi_pred_of_not_is_min ha, Ici_inter_Iic] lemma Ioo_pred_left_of_not_is_min (ha : ¬ is_min a) : Ioo (pred a) b = Ico a b := by rw [←Ioi_inter_Iio, Ioi_pred_of_not_is_min ha, Ici_inter_Iio] lemma Icc_pred_right_of_not_is_min (ha : ¬ is_min b) : Icc a (pred b) = Ico a b := by rw [←Ici_inter_Iic, Iic_pred_of_not_is_min ha, Ici_inter_Iio] lemma Ioc_pred_right_of_not_is_min (ha : ¬ is_min b) : Ioc a (pred b) = Ioo a b := by rw [←Ioi_inter_Iic, Iic_pred_of_not_is_min ha, Ioi_inter_Iio] section no_min_order variables [no_min_order α] lemma pred_lt (a : α) : pred a < a := pred_lt_of_not_is_min $ not_is_min a lemma pred_lt_iff : pred a < b ↔ a ≤ b := pred_lt_iff_of_not_is_min $ not_is_min a lemma le_pred_iff : a ≤ pred b ↔ a < b := le_pred_iff_of_not_is_min $ not_is_min b @[simp] lemma pred_le_pred_iff : pred a ≤ pred b ↔ a ≤ b := ⟨λ h, le_of_pred_lt $ h.trans_lt (pred_lt b), λ h, le_pred_of_lt $ (pred_lt a).trans_le h⟩ @[simp] lemma pred_lt_pred_iff : pred a < pred b ↔ a < b := by simp_rw [lt_iff_le_not_le, pred_le_pred_iff] alias pred_le_pred_iff ↔ order.le_of_pred_le_pred _ alias pred_lt_pred_iff ↔ order.lt_of_pred_lt_pred pred_lt_pred lemma pred_strict_mono : strict_mono (pred : α → α) := λ a b, pred_lt_pred lemma pred_covby (a : α) : pred a ⋖ a := pred_covby_of_not_is_min $ not_is_min a @[simp] lemma Ioi_pred (a : α) : Ioi (pred a) = Ici a := Ioi_pred_of_not_is_min $ not_is_min a @[simp] lemma Iic_pred (a : α) : Iic (pred a) = Iio a := Iic_pred_of_not_is_min $ not_is_min a lemma Ioc_pred_left (a b : α) : Ioc (pred a) b = Icc a b := Ioc_pred_left_of_not_is_min $ not_is_min _ lemma Ioo_pred_left (a b : α) : Ioo (pred a) b = Ico a b := Ioo_pred_left_of_not_is_min $ not_is_min _ lemma Icc_pred_right (a b : α) : Icc a (pred b) = Ico a b := Icc_pred_right_of_not_is_min $ not_is_min _ lemma Ioc_pred_right (a b : α) : Ioc a (pred b) = Ioo a b := Ioc_pred_right_of_not_is_min $ not_is_min _ end no_min_order end preorder section partial_order variables [partial_order α] [pred_order α] {a b : α} @[simp] lemma pred_eq_iff_is_min : pred a = a ↔ is_min a := ⟨λ h, min_of_le_pred h.ge, λ h, h.eq_of_le $ pred_le _⟩ alias pred_eq_iff_is_min ↔ _ is_min.pred_eq lemma pred_le_le_iff {a b : α} : pred a ≤ b ∧ b ≤ a ↔ b = a ∨ b = pred a := begin refine ⟨λ h, or_iff_not_imp_left.2 $ λ hba : b ≠ a, (le_pred_of_lt $ h.2.lt_of_ne hba).antisymm h.1, _⟩, rintro (rfl | rfl), { exact ⟨pred_le b, le_rfl⟩ }, { exact ⟨le_rfl, pred_le a⟩ } end lemma _root_.covby.pred_eq {a b : α} (h : a ⋖ b) : pred b = a := (le_pred_of_lt h.lt).eq_of_not_gt $ λ h', h.2 h' $ pred_lt_of_not_is_min h.lt.not_is_min lemma pred_le_iff_eq_or_le : pred a ≤ b ↔ b = pred a ∨ a ≤ b := begin by_cases ha : is_min a, { rw [ha.pred_eq, or_iff_right_of_imp ge_of_eq] }, { rw [←pred_lt_iff_of_not_is_min ha, le_iff_eq_or_lt, eq_comm] } end lemma pred_lt_iff_eq_or_lt_of_not_is_min (ha : ¬ is_min a) : pred a < b ↔ a = b ∨ a < b := (pred_lt_iff_of_not_is_min ha).trans le_iff_eq_or_lt lemma Ici_pred (a : α) : Ici (pred a) = insert (pred a) (Ici a) := ext $ λ _, pred_le_iff_eq_or_le lemma Icc_pred_left (h : pred a ≤ b) : Icc (pred a) b = insert (pred a) (Icc a b) := by simp_rw [←Ici_inter_Iic, Ici_pred, insert_inter_of_mem (mem_Iic.2 h)] lemma Ico_pred_left (h : pred a < b) : Ico (pred a) b = insert (pred a) (Ico a b) := by simp_rw [←Ici_inter_Iio, Ici_pred, insert_inter_of_mem (mem_Iio.2 h)] section no_min_order variables [no_min_order α] @[simp] lemma pred_eq_pred_iff : pred a = pred b ↔ a = b := by simp_rw [eq_iff_le_not_lt, pred_le_pred_iff, pred_lt_pred_iff] lemma pred_injective : injective (pred : α → α) := λ a b, pred_eq_pred_iff.1 lemma pred_ne_pred_iff : pred a ≠ pred b ↔ a ≠ b := pred_injective.ne_iff alias pred_ne_pred_iff ↔ _ order.pred_ne_pred lemma pred_lt_iff_eq_or_lt : pred a < b ↔ a = b ∨ a < b := pred_lt_iff.trans le_iff_eq_or_lt lemma pred_eq_iff_covby : pred b = a ↔ a ⋖ b := ⟨by { rintro rfl, exact pred_covby _ }, covby.pred_eq⟩ lemma Ioi_pred_eq_insert (a : α) : Ioi (pred a) = insert a (Ioi a) := ext $ λ _, pred_lt_iff_eq_or_lt.trans $ or_congr_left' eq_comm lemma Ico_pred_right_eq_insert (h : a ≤ b) : Ioc (pred a) b = insert a (Ioc a b) := by simp_rw [←Ioi_inter_Iic, Ioi_pred_eq_insert, insert_inter_of_mem (mem_Iic.2 h)] lemma Ioo_pred_right_eq_insert (h : a < b) : Ioo (pred a) b = insert a (Ioo a b) := by simp_rw [←Ioi_inter_Iio, Ioi_pred_eq_insert, insert_inter_of_mem (mem_Iio.2 h)] end no_min_order section order_bot variables [order_bot α] @[simp] lemma pred_bot : pred (⊥ : α) = ⊥ := is_min_bot.pred_eq @[simp] lemma le_pred_iff_eq_bot : a ≤ pred a ↔ a = ⊥ := @succ_le_iff_eq_top αᵒᵈ _ _ _ _ @[simp] lemma pred_lt_iff_ne_bot : pred a < a ↔ a ≠ ⊥ := @lt_succ_iff_ne_top αᵒᵈ _ _ _ _ end order_bot section order_top variables [order_top α] [nontrivial α] lemma pred_lt_top (a : α) : pred a < ⊤ := (pred_mono le_top).trans_lt $ pred_lt_of_not_is_min not_is_min_top lemma pred_ne_top (a : α) : pred a ≠ ⊤ := (pred_lt_top a).ne end order_top end partial_order /-- There is at most one way to define the predecessors in a `partial_order`. -/ instance [partial_order α] : subsingleton (pred_order α) := ⟨begin introsI h₀ h₁, ext a, by_cases ha : is_min a, { exact (@is_min.pred_eq _ _ h₀ _ ha).trans ha.pred_eq.symm }, { exact @covby.pred_eq _ _ h₀ _ _ (pred_covby_of_not_is_min ha) } end⟩ section complete_lattice variables [complete_lattice α] [pred_order α] lemma pred_eq_supr (a : α) : pred a = ⨆ b (h : b < a), b := begin refine le_antisymm _ (supr_le (λ b, supr_le le_pred_of_lt)), obtain rfl | ha := eq_or_ne a ⊥, { rw pred_bot, exact bot_le }, { exact @le_supr₂ _ _ (λ b, b < a) _ (λ a _, a) (pred a) (pred_lt_iff_ne_bot.2 ha) } end end complete_lattice /-! ### Successor-predecessor orders -/ section succ_pred_order variables [partial_order α] [succ_order α] [pred_order α] {a b : α} @[simp] lemma succ_pred_of_not_is_min (h : ¬ is_min a) : succ (pred a) = a := (pred_covby_of_not_is_min h).succ_eq @[simp] lemma pred_succ_of_not_is_max (h : ¬ is_max a) : pred (succ a) = a := (covby_succ_of_not_is_max h).pred_eq @[simp] lemma succ_pred [no_min_order α] (a : α) : succ (pred a) = a := (pred_covby _).succ_eq @[simp] lemma pred_succ [no_max_order α] (a : α) : pred (succ a) = a := (covby_succ _).pred_eq end succ_pred_order /-! ### `with_bot`, `with_top` Adding a greatest/least element to a `succ_order` or to a `pred_order`. As far as successors and predecessors are concerned, there are four ways to add a bottom or top element to an order: * Adding a `⊤` to an `order_top`: Preserves `succ` and `pred`. * Adding a `⊤` to a `no_max_order`: Preserves `succ`. Never preserves `pred`. * Adding a `⊥` to an `order_bot`: Preserves `succ` and `pred`. * Adding a `⊥` to a `no_min_order`: Preserves `pred`. Never preserves `succ`. where "preserves `(succ/pred)`" means `(succ/pred)_order α → (succ/pred)_order ((with_top/with_bot) α)`. -/ section with_top open with_top /-! #### Adding a `⊤` to an `order_top` -/ instance [decidable_eq α] [partial_order α] [order_top α] [succ_order α] : succ_order (with_top α) := { succ := λ a, match a with | ⊤ := ⊤ | (some a) := ite (a = ⊤) ⊤ (some (succ a)) end, le_succ := λ a, begin cases a, { exact le_top }, change ((≤) : with_top α → with_top α → Prop) _ (ite _ _ _), split_ifs, { exact le_top }, { exact some_le_some.2 (le_succ a) } end, max_of_succ_le := λ a ha, begin cases a, { exact is_max_top }, change ((≤) : with_top α → with_top α → Prop) (ite _ _ _) _ at ha, split_ifs at ha with ha', { exact (not_top_le_coe _ ha).elim }, { rw [some_le_some, succ_le_iff_eq_top] at ha, exact (ha' ha).elim } end, succ_le_of_lt := λ a b h, begin cases b, { exact le_top }, cases a, { exact (not_top_lt h).elim }, rw some_lt_some at h, change ((≤) : with_top α → with_top α → Prop) (ite _ _ _) _, split_ifs with ha, { rw ha at h, exact (not_top_lt h).elim }, { exact some_le_some.2 (succ_le_of_lt h) } end, le_of_lt_succ := λ a b h, begin cases a, { exact (not_top_lt h).elim }, cases b, { exact le_top }, change ((<) : with_top α → with_top α → Prop) _ (ite _ _ _) at h, rw some_le_some, split_ifs at h with hb, { rw hb, exact le_top }, { exact le_of_lt_succ (some_lt_some.1 h) } end } instance [preorder α] [order_top α] [pred_order α] : pred_order (with_top α) := { pred := λ a, match a with | ⊤ := some ⊤ | (some a) := some (pred a) end, pred_le := λ a, match a with | ⊤ := le_top | (some a) := some_le_some.2 (pred_le a) end, min_of_le_pred := λ a ha, begin cases a, { exact ((coe_lt_top (⊤ : α)).not_le ha).elim }, { exact (min_of_le_pred $ some_le_some.1 ha).with_top } end, le_pred_of_lt := λ a b h, begin cases a, { exact ((le_top).not_lt h).elim }, cases b, { exact some_le_some.2 le_top }, exact some_le_some.2 (le_pred_of_lt $ some_lt_some.1 h), end, le_of_pred_lt := λ a b h, begin cases b, { exact le_top }, cases a, { exact (not_top_lt $ some_lt_some.1 h).elim }, { exact some_le_some.2 (le_of_pred_lt $ some_lt_some.1 h) } end } /-! #### Adding a `⊤` to a `no_max_order` -/ instance with_top.succ_order_of_no_max_order [preorder α] [no_max_order α] [succ_order α] : succ_order (with_top α) := { succ := λ a, match a with | ⊤ := ⊤ | (some a) := some (succ a) end, le_succ := λ a, begin cases a, { exact le_top }, { exact some_le_some.2 (le_succ a) } end, max_of_succ_le := λ a ha, begin cases a, { exact is_max_top }, { exact (not_is_max _ $ max_of_succ_le $ some_le_some.1 ha).elim } end, succ_le_of_lt := λ a b h, begin cases a, { exact (not_top_lt h).elim }, cases b, { exact le_top}, { exact some_le_some.2 (succ_le_of_lt $ some_lt_some.1 h) } end, le_of_lt_succ := λ a b h, begin cases a, { exact (not_top_lt h).elim }, cases b, { exact le_top }, { exact some_le_some.2 (le_of_lt_succ $ some_lt_some.1 h) } end } instance [preorder α] [no_max_order α] [hα : nonempty α] : is_empty (pred_order (with_top α)) := ⟨begin introI, set b := pred (⊤ : with_top α) with h, cases pred (⊤ : with_top α) with a ha; change b with pred ⊤ at h, { exact hα.elim (λ a, (min_of_le_pred h.ge).not_lt $ coe_lt_top a) }, { obtain ⟨c, hc⟩ := exists_gt a, rw [←some_lt_some, ←h] at hc, exact (le_of_pred_lt hc).not_lt (some_lt_none _) } end⟩ end with_top section with_bot open with_bot /-! #### Adding a `⊥` to an `order_bot` -/ instance [preorder α] [order_bot α] [succ_order α] : succ_order (with_bot α) := { succ := λ a, match a with | ⊥ := some ⊥ | (some a) := some (succ a) end, le_succ := λ a, match a with | ⊥ := bot_le | (some a) := some_le_some.2 (le_succ a) end, max_of_succ_le := λ a ha, begin cases a, { exact ((none_lt_some (⊥ : α)).not_le ha).elim }, { exact is_max.with_bot (max_of_succ_le $ some_le_some.1 ha) } end, succ_le_of_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact some_le_some.2 bot_le }, { exact some_le_some.2 (succ_le_of_lt $ some_lt_some.1 h) } end, le_of_lt_succ := λ a b h, begin cases a, { exact bot_le }, cases b, { exact (not_lt_bot $ some_lt_some.1 h).elim }, { exact some_le_some.2 (le_of_lt_succ $ some_lt_some.1 h) } end } instance [decidable_eq α] [partial_order α] [order_bot α] [pred_order α] : pred_order (with_bot α) := { pred := λ a, match a with | ⊥ := ⊥ | (some a) := ite (a = ⊥) ⊥ (some (pred a)) end, pred_le := λ a, begin cases a, { exact bot_le }, change (ite _ _ _ : with_bot α) ≤ some a, split_ifs, { exact bot_le }, { exact some_le_some.2 (pred_le a) } end, min_of_le_pred := λ a ha, begin cases a, { exact is_min_bot }, change ((≤) : with_bot α → with_bot α → Prop) _ (ite _ _ _) at ha, split_ifs at ha with ha', { exact (not_coe_le_bot _ ha).elim }, { rw [some_le_some, le_pred_iff_eq_bot] at ha, exact (ha' ha).elim } end, le_pred_of_lt := λ a b h, begin cases a, { exact bot_le }, cases b, { exact (not_lt_bot h).elim }, rw some_lt_some at h, change ((≤) : with_bot α → with_bot α → Prop) _ (ite _ _ _), split_ifs with hb, { rw hb at h, exact (not_lt_bot h).elim }, { exact some_le_some.2 (le_pred_of_lt h) } end, le_of_pred_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact bot_le }, change ((<) : with_bot α → with_bot α → Prop) (ite _ _ _) _ at h, rw some_le_some, split_ifs at h with ha, { rw ha, exact bot_le }, { exact le_of_pred_lt (some_lt_some.1 h) } end } /-! #### Adding a `⊥` to a `no_min_order` -/ instance [preorder α] [no_min_order α] [hα : nonempty α] : is_empty (succ_order (with_bot α)) := ⟨begin introI, set b : with_bot α := succ ⊥ with h, cases succ (⊥ : with_bot α) with a ha; change b with succ ⊥ at h, { exact hα.elim (λ a, (max_of_succ_le h.le).not_lt $ bot_lt_coe a) }, { obtain ⟨c, hc⟩ := exists_lt a, rw [←some_lt_some, ←h] at hc, exact (le_of_lt_succ hc).not_lt (none_lt_some _) } end⟩ instance with_bot.pred_order_of_no_min_order [preorder α] [no_min_order α] [pred_order α] : pred_order (with_bot α) := { pred := λ a, match a with | ⊥ := ⊥ | (some a) := some (pred a) end, pred_le := λ a, begin cases a, { exact bot_le }, { exact some_le_some.2 (pred_le a) } end, min_of_le_pred := λ a ha, begin cases a, { exact is_min_bot }, { exact (not_is_min _ $ min_of_le_pred $ some_le_some.1 ha).elim } end, le_pred_of_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact bot_le }, { exact some_le_some.2 (le_pred_of_lt $ some_lt_some.1 h) } end, le_of_pred_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact bot_le }, { exact some_le_some.2 (le_of_pred_lt $ some_lt_some.1 h) } end } end with_bot end order open order /-! ### Archimedeanness -/ /-- A `succ_order` is succ-archimedean if one can go from any two comparable elements by iterating `succ` -/ class is_succ_archimedean (α : Type*) [preorder α] [succ_order α] : Prop := (exists_succ_iterate_of_le {a b : α} (h : a ≤ b) : ∃ n, succ^[n] a = b) /-- A `pred_order` is pred-archimedean if one can go from any two comparable elements by iterating `pred` -/ class is_pred_archimedean (α : Type*) [preorder α] [pred_order α] : Prop := (exists_pred_iterate_of_le {a b : α} (h : a ≤ b) : ∃ n, pred^[n] b = a) export is_succ_archimedean (exists_succ_iterate_of_le) export is_pred_archimedean (exists_pred_iterate_of_le) section preorder variables [preorder α] section succ_order variables [succ_order α] [is_succ_archimedean α] {a b : α} instance : is_pred_archimedean αᵒᵈ := ⟨λ a b h, by convert exists_succ_iterate_of_le h.of_dual⟩ lemma has_le.le.exists_succ_iterate (h : a ≤ b) : ∃ n, succ^[n] a = b := exists_succ_iterate_of_le h lemma exists_succ_iterate_iff_le : (∃ n, succ^[n] a = b) ↔ a ≤ b := begin refine ⟨_, exists_succ_iterate_of_le⟩, rintro ⟨n, rfl⟩, exact id_le_iterate_of_id_le le_succ n a, end /-- Induction principle on a type with a `succ_order` for all elements above a given element `m`. -/ @[elab_as_eliminator] lemma succ.rec {P : α → Prop} {m : α} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (succ n)) ⦃n : α⦄ (hmn : m ≤ n) : P n := begin obtain ⟨n, rfl⟩ := hmn.exists_succ_iterate, clear hmn, induction n with n ih, { exact h0 }, { rw [function.iterate_succ_apply'], exact h1 _ (id_le_iterate_of_id_le le_succ n m) ih } end lemma succ.rec_iff {p : α → Prop} (hsucc : ∀ a, p a ↔ p (succ a)) {a b : α} (h : a ≤ b) : p a ↔ p b := begin obtain ⟨n, rfl⟩ := h.exists_succ_iterate, exact iterate.rec (λ b, p a ↔ p b) (λ c hc, hc.trans (hsucc _)) iff.rfl n, end end succ_order section pred_order variables [pred_order α] [is_pred_archimedean α] {a b : α} instance : is_succ_archimedean αᵒᵈ := ⟨λ a b h, by convert exists_pred_iterate_of_le h.of_dual⟩ lemma has_le.le.exists_pred_iterate (h : a ≤ b) : ∃ n, pred^[n] b = a := exists_pred_iterate_of_le h lemma exists_pred_iterate_iff_le : (∃ n, pred^[n] b = a) ↔ a ≤ b := @exists_succ_iterate_iff_le αᵒᵈ _ _ _ _ _ /-- Induction principle on a type with a `pred_order` for all elements below a given element `m`. -/ @[elab_as_eliminator] lemma pred.rec {P : α → Prop} {m : α} (h0 : P m) (h1 : ∀ n, n ≤ m → P n → P (pred n)) ⦃n : α⦄ (hmn : n ≤ m) : P n := @succ.rec αᵒᵈ _ _ _ _ _ h0 h1 _ hmn lemma pred.rec_iff {p : α → Prop} (hsucc : ∀ a, p a ↔ p (pred a)) {a b : α} (h : a ≤ b) : p a ↔ p b := (@succ.rec_iff αᵒᵈ _ _ _ _ hsucc _ _ h).symm end pred_order end preorder section linear_order variables [linear_order α] section succ_order variables [succ_order α] [is_succ_archimedean α] {a b : α} lemma exists_succ_iterate_or : (∃ n, succ^[n] a = b) ∨ ∃ n, succ^[n] b = a := (le_total a b).imp exists_succ_iterate_of_le exists_succ_iterate_of_le lemma succ.rec_linear {p : α → Prop} (hsucc : ∀ a, p a ↔ p (succ a)) (a b : α) : p a ↔ p b := (le_total a b).elim (succ.rec_iff hsucc) (λ h, (succ.rec_iff hsucc h).symm) end succ_order section pred_order variables [pred_order α] [is_pred_archimedean α] {a b : α} lemma exists_pred_iterate_or : (∃ n, pred^[n] b = a) ∨ ∃ n, pred^[n] a = b := (le_total a b).imp exists_pred_iterate_of_le exists_pred_iterate_of_le lemma pred.rec_linear {p : α → Prop} (hsucc : ∀ a, p a ↔ p (pred a)) (a b : α) : p a ↔ p b := (le_total a b).elim (pred.rec_iff hsucc) (λ h, (pred.rec_iff hsucc h).symm) end pred_order end linear_order section is_well_order variables [linear_order α] @[priority 100] instance is_well_order.to_is_pred_archimedean [h : is_well_order α (<)] [pred_order α] : is_pred_archimedean α := ⟨λ a, begin refine well_founded.fix h.wf (λ b ih hab, _), replace hab := hab.eq_or_lt, rcases hab with rfl | hab, { exact ⟨0, rfl⟩ }, cases le_or_lt b (pred b) with hb hb, { cases (min_of_le_pred hb).not_lt hab }, obtain ⟨k, hk⟩ := ih (pred b) hb (le_pred_of_lt hab), refine ⟨k + 1, _⟩, rw [iterate_add_apply, iterate_one, hk], end⟩ @[priority 100] instance is_well_order.to_is_succ_archimedean [h : is_well_order α (>)] [succ_order α] : is_succ_archimedean α := by convert @order_dual.is_succ_archimedean αᵒᵈ _ _ _ end is_well_order section order_bot variables [preorder α] [order_bot α] [succ_order α] [is_succ_archimedean α] lemma succ.rec_bot (p : α → Prop) (hbot : p ⊥) (hsucc : ∀ a, p a → p (succ a)) (a : α) : p a := succ.rec hbot (λ x _ h, hsucc x h) (bot_le : ⊥ ≤ a) end order_bot section order_top variables [preorder α] [order_top α] [pred_order α] [is_pred_archimedean α] lemma pred.rec_top (p : α → Prop) (htop : p ⊤) (hpred : ∀ a, p a → p (pred a)) (a : α) : p a := pred.rec htop (λ x _ h, hpred x h) (le_top : a ≤ ⊤) end order_top
1fa0f694c84b3cf93a84de0d035c8acf0a714329
675b8263050a5d74b89ceab381ac81ce70535688
/src/analysis/normed_space/banach.lean
dfec0c4c1e9e8b3a1e87caa6a6b7db8a5f232e4f
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,985
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.baire import analysis.normed_space.operator_norm /-! # Banach open mapping theorem This file contains the Banach open mapping theorem, i.e., the fact that a bijective bounded linear map between Banach spaces has a bounded inverse. -/ open function metric set filter finset open_locale classical topological_space big_operators variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E →L[𝕜] F) include 𝕜 variable [complete_space F] /-- First step of the proof of the Banach open mapping theorem (using completeness of `F`): by Baire's theorem, there exists a ball in `E` whose image closure has nonempty interior. Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by images of elements of norm at most `C * ∥y∥`. For further use, we will only need such an element whose image is within distance `∥y∥/2` of `y`, to apply an iterative process. -/ lemma exists_approx_preimage_norm_le (surj : surjective f) : ∃C ≥ 0, ∀y, ∃x, dist (f x) y ≤ 1/2 * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥ := begin have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ, { refine subset.antisymm (subset_univ _) (λy hy, _), rcases surj y with ⟨x, hx⟩, rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩, refine mem_Union.2 ⟨n, subset_closure _⟩, refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩, rwa [mem_ball, dist_eq_norm, sub_zero] }, have : ∃ (n : ℕ) x, x ∈ interior (closure (f '' (ball 0 n))) := nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A, simp only [mem_interior_iff_mem_nhds, mem_nhds_iff] at this, rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩, { refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _, exacts [inv_nonneg.2 (div_nonneg (le_of_lt εpos) (by norm_num)), n.cast_nonneg] }, { by_cases hy : y = 0, { use 0, simp [hy] }, { rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydlt, leyd, dinv⟩, let δ := ∥d∥ * ∥y∥/4, have δpos : 0 < δ := div_pos (mul_pos (norm_pos_iff.2 hd) (norm_pos_iff.2 hy)) (by norm_num), have : a + d • y ∈ ball a ε, by simp [dist_eq_norm, lt_of_le_of_lt ydlt.le (half_lt_self εpos)], rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩, rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩, rw ← xz₁ at h₁, rw [mem_ball, dist_eq_norm, sub_zero] at hx₁, have : a ∈ ball a ε, by { simp, exact εpos }, rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩, rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩, rw ← xz₂ at h₂, rw [mem_ball, dist_eq_norm, sub_zero] at hx₂, let x := x₁ - x₂, have I : ∥f x - d • y∥ ≤ 2 * δ := calc ∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ : by { congr' 1, simp only [x, f.map_sub], abel } ... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ : norm_sub_le _ _ ... ≤ δ + δ : begin apply add_le_add, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ }, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ } end ... = 2 * δ : (two_mul _).symm, have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc ∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ : by rwa [f.map_smul _, inv_mul_cancel, one_smul] ... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub] ... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * (2 * δ) : begin apply mul_le_mul_of_nonneg_left I, rw inv_nonneg, exact norm_nonneg _ end ... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring } ... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] } ... = (1/2) * ∥y∥ : by ring, rw ← dist_eq_norm at J, have K : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc ∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, normed_field.norm_inv] ... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin refine mul_le_mul dinv _ (norm_nonneg _) _, { exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) }, { apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _), exact inv_nonneg.2 (le_of_lt (half_pos εpos)) } end ... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring, exact ⟨d⁻¹ • x, J, K⟩ } }, end variable [complete_space E] /-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then any point has a preimage with controlled norm. -/ theorem exists_preimage_norm_le (surj : surjective f) : ∃C > 0, ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ := begin obtain ⟨C, C0, hC⟩ := exists_approx_preimage_norm_le f surj, /- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`, leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a preimage of `y`. This uses completeness of `E`. -/ choose g hg using hC, let h := λy, y - f (g y), have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥, { assume y, rw [← dist_eq_norm, dist_comm], exact (hg y).1 }, refine ⟨2 * C + 1, by linarith, λy, _⟩, have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥, { assume n, induction n with n IH, { simp only [one_div, nat.nat_zero_eq_zero, one_mul, iterate_zero_apply, pow_zero] }, { rw [iterate_succ'], apply le_trans (hle _) _, rw [pow_succ, mul_assoc], apply mul_le_mul_of_nonneg_left IH, norm_num } }, let u := λn, g((h^[n]) y), have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥), { assume n, apply le_trans (hg _).2 _, calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0 ... = (1 / 2) ^ n * (C * ∥y∥) : by ring }, have sNu : summable (λn, ∥u n∥), { refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _, exact summable.mul_right _ (summable_geometric_of_lt_1 (by norm_num) (by norm_num)) }, have su : summable u := summable_of_summable_norm sNu, let x := tsum u, have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc ∥x∥ ≤ (∑'n, ∥u n∥) : norm_tsum_le_tsum_norm sNu ... ≤ (∑'n, (1/2)^n * (C * ∥y∥)) : tsum_le_tsum ule sNu (summable.mul_right _ summable_geometric_two) ... = (∑'n, (1/2)^n) * (C * ∥y∥) : by { rw tsum_mul_right, exact summable_geometric_two } ... = 2 * (C * ∥y∥) : by rw tsum_geometric_two ... = 2 * C * ∥y∥ + 0 : by rw [add_zero, mul_assoc] ... ≤ 2 * C * ∥y∥ + ∥y∥ : add_le_add (le_refl _) (norm_nonneg _) ... = (2 * C + 1) * ∥y∥ : by ring, have fsumeq : ∀n:ℕ, f (∑ i in finset.range n, u i) = y - (h^[n]) y, { assume n, induction n with n IH, { simp [f.map_zero] }, { rw [sum_range_succ, f.map_add, IH, iterate_succ'], simp [u, h, sub_eq_add_neg, add_comm, add_left_comm] } }, have : tendsto (λn, ∑ i in range n, u i) at_top (𝓝 x) := su.has_sum.tendsto_sum_nat, have L₁ : tendsto (λn, f(∑ i in range n, u i)) at_top (𝓝 (f x)) := (f.continuous.tendsto _).comp this, simp only [fsumeq] at L₁, have L₂ : tendsto (λn, y - (h^[n]) y) at_top (𝓝 (y - 0)), { refine tendsto_const_nhds.sub _, rw tendsto_iff_norm_tendsto_zero, simp only [sub_zero], refine squeeze_zero (λ_, norm_nonneg _) hnle _, have : 0 = 0 * ∥y∥, by rw zero_mul, rw this, refine tendsto.mul _ tendsto_const_nhds, exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) }, have feq : f x = y - 0 := tendsto_nhds_unique L₁ L₂, rw sub_zero at feq, exact ⟨x, feq, x_ineq⟩ end /-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/ theorem open_mapping (surj : surjective f) : is_open_map f := begin assume s hs, rcases exists_preimage_norm_le f surj with ⟨C, Cpos, hC⟩, refine is_open_iff.2 (λy yfs, _), rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩, rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩, refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩, rcases hC (z-y) with ⟨w, wim, wnorm⟩, have : f (x + w) = z, by { rw [f.map_add, wim, fxy, add_sub_cancel'_right] }, rw ← this, have : x + w ∈ ball x ε := calc dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp } ... ≤ C * ∥z - y∥ : wnorm ... < C * (ε/C) : begin apply mul_lt_mul_of_pos_left _ Cpos, rwa [mem_ball, dist_eq_norm] at hz, end ... = ε : mul_div_cancel' _ (ne_of_gt Cpos), exact set.mem_image_of_mem _ (hε this) end namespace linear_equiv /-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/ @[continuity] theorem continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) : continuous e.symm := begin rw continuous_def, intros s hs, rw [← e.image_eq_preimage], rw [← e.coe_coe] at h ⊢, exact open_mapping ⟨↑e, h⟩ e.surjective s hs end /-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the inverse map is also continuous. -/ def to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) : E ≃L[𝕜] F := { continuous_to_fun := h, continuous_inv_fun := e.continuous_symm h, ..e } @[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) : ⇑(e.to_continuous_linear_equiv_of_continuous h) = e := rfl @[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) : ⇑(e.to_continuous_linear_equiv_of_continuous h).symm = e.symm := rfl end linear_equiv namespace continuous_linear_equiv /-- Convert a bijective continuous linear map `f : E →L[𝕜] F` between two Banach spaces to a continuous linear equivalence. -/ noncomputable def of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) : E ≃L[𝕜] F := (linear_equiv.of_bijective ↑f hinj hsurj).to_continuous_linear_equiv_of_continuous f.continuous @[simp] lemma coe_fn_of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) : ⇑(of_bijective f hinj hsurj) = f := rfl @[simp] lemma of_bijective_symm_apply_apply (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) (x : E) : (of_bijective f hinj hsurj).symm (f x) = x := (of_bijective f hinj hsurj).symm_apply_apply x @[simp] lemma of_bijective_apply_symm_apply (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) (y : F) : f ((of_bijective f hinj hsurj).symm y) = y := (of_bijective f hinj hsurj).apply_symm_apply y end continuous_linear_equiv
f0f490125fd4f2a14062efd19b0d37c407e0d66f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/real/cardinality.lean
af4dbc2f353bdf3795caeb9f4df70fd149f8889b
[ "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
9,564
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import set_theory.continuum import analysis.specific_limits import data.rat.denumerable import data.set.intervals.image_preimage /-! # The cardinality of the reals This file shows that the real numbers have cardinality continuum, i.e. `#ℝ = 𝔠`. We show that `#ℝ ≤ 𝔠` by noting that every real number is determined by a Cauchy-sequence of the form `ℕ → ℚ`, which has cardinality `𝔠`. To show that `#ℝ ≥ 𝔠` we define an injection from `{0, 1} ^ ℕ` to `ℝ` with `f ↦ Σ n, f n * (1 / 3) ^ n`. We conclude that all intervals with distinct endpoints have cardinality continuum. ## Main definitions * `cardinal.cantor_function` is the function that sends `f` in `{0, 1} ^ ℕ` to `ℝ` by `f ↦ Σ' n, f n * (1 / 3) ^ n` ## Main statements * `cardinal.mk_real : #ℝ = 𝔠`: the reals have cardinality continuum. * `cardinal.not_countable_real`: the universal set of real numbers is not countable. We can use this same proof to show that all the other sets in this file are not countable. * 8 lemmas of the form `mk_Ixy_real` for `x,y ∈ {i,o,c}` state that intervals on the reals have cardinality continuum. ## Notation * `𝔠` : notation for `cardinal.continuum` in locale `cardinal`, defined in `set_theory.continuum`. ## Tags continuum, cardinality, reals, cardinality of the reals -/ open nat set open_locale cardinal noncomputable theory namespace cardinal variables {c : ℝ} {f g : ℕ → bool} {n : ℕ} /-- The body of the sum in `cantor_function`. `cantor_function_aux c f n = c ^ n` if `f n = tt`; `cantor_function_aux c f n = 0` if `f n = ff`. -/ def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n := by simp [cantor_function_aux, h] @[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 := by simp [cantor_function_aux, h] lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := by { cases h' : f n; simp [h'], apply pow_nonneg h } lemma cantor_function_aux_eq (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := by simp [cantor_function_aux, h] lemma cantor_function_aux_succ (f : ℕ → bool) : (λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n := by { ext n, cases h : f (n + 1); simp [h, pow_succ] } lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := begin apply (summable_geometric_of_lt_1 h1 h2).summable_of_eq_zero_or_self, intro n, cases h : f n; simp [h] end /-- `cantor_function c (f : ℕ → bool)` is `Σ n, f n * c ^ n`, where `tt` is interpreted as `1` and `ff` is interpreted as `0`. It is implemented using `cantor_function_aux`. -/ def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑' n, cantor_function_aux c f n lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantor_function c f ≤ cantor_function c g := begin apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2), intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1], replace h3 : g n = tt := h3 n h, simp [h, h3] end lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) := begin rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)], rw [cantor_function_aux_succ, tsum_mul_left, cantor_function_aux, pow_zero], refl end /-- `cantor_function c` is strictly increasing with if `0 < c < 1/2`, if we endow `ℕ → bool` with a lexicographic order. The lexicographic order doesn't exist for these infinitary products, so we explicitly write out what it means. -/ lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool} (hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) : cantor_function c f < cantor_function c g := begin have h3 : c < 1, { apply h2.trans, norm_num }, induction n with n ih generalizing f g, { let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n, have hf_max : ∀n, f n → f_max n, { intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl }, let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n, have hg_min : ∀n, g_min n → g n, { intros n hn, cases n, rw [gn], apply rfl, contradiction }, apply (cantor_function_le (le_of_lt h1) h3 hf_max).trans_lt, refine lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min), have : c / (1 - c) < 1, { rw [div_lt_one, lt_sub_iff_add_lt], { convert add_lt_add h2 h2, norm_num }, rwa sub_pos }, convert this, { rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv, ←tsum_geometric_of_lt_1 (le_of_lt h1) h3], apply zero_add }, { convert tsum_eq_single 0 _, { apply_instance }, { intros n hn, cases n, contradiction, refl } } }, rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3], rw [hn 0 $ zero_lt_succ n], apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn end /-- `cantor_function c` is injective if `0 < c < 1/2`. -/ lemma cantor_function_injective (h1 : 0 < c) (h2 : c < 1 / 2) : function.injective (cantor_function c) := begin intros f g hfg, classical, by_contra h, revert hfg, have : ∃n, f n ≠ g n, { rw [←not_forall], intro h', apply h, ext, apply h' }, let n := nat.find this, have hn : ∀ (k : ℕ), k < n → f k = g k, { intros k hk, apply of_not_not, exact nat.find_min this hk }, cases fn : f n, { apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _, apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this }, { apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn, apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this } end /-- The cardinality of the reals, as a type. -/ lemma mk_real : #ℝ = 𝔠 := begin apply le_antisymm, { rw real.equiv_Cauchy.cardinal_eq, apply mk_quotient_le.trans, apply (mk_subtype_le _).trans_eq, rw [← power_def, mk_nat, mk_rat, omega_power_omega] }, { convert mk_le_of_injective (cantor_function_injective _ _), rw [←power_def, mk_bool, mk_nat, two_power_omega], exact 1 / 3, norm_num, norm_num } end /-- The cardinality of the reals, as a set. -/ lemma mk_univ_real : #(set.univ : set ℝ) = 𝔠 := by rw [mk_univ, mk_real] /-- **Non-Denumerability of the Continuum**: The reals are not countable. -/ lemma not_countable_real : ¬ countable (set.univ : set ℝ) := by { rw [← mk_set_le_omega, not_le, mk_univ_real], apply cantor } /-- The cardinality of the interval (a, ∞). -/ lemma mk_Ioi_real (a : ℝ) : #(Ioi a) = 𝔠 := begin refine le_antisymm (mk_real ▸ mk_set_le _) _, rw [← not_lt], intro h, refine ne_of_lt _ mk_univ_real, have hu : Iio a ∪ {a} ∪ Ioi a = set.univ, { convert Iic_union_Ioi, exact Iio_union_right }, rw ← hu, refine lt_of_le_of_lt (mk_union_le _ _) _, refine lt_of_le_of_lt (add_le_add_right (mk_union_le _ _) _) _, have h2 : (λ x, a + a - x) '' Ioi a = Iio a, { convert image_const_sub_Ioi _ _, simp }, rw ← h2, refine add_lt_of_lt (cantor _).le _ h, refine add_lt_of_lt (cantor _).le (mk_image_le.trans_lt h) _, rw mk_singleton, exact one_lt_omega.trans (cantor _) end /-- The cardinality of the interval [a, ∞). -/ lemma mk_Ici_real (a : ℝ) : #(Ici a) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioi_real a ▸ mk_le_mk_of_subset Ioi_subset_Ici_self) /-- The cardinality of the interval (-∞, a). -/ lemma mk_Iio_real (a : ℝ) : #(Iio a) = 𝔠 := begin refine le_antisymm (mk_real ▸ mk_set_le _) _, have h2 : (λ x, a + a - x) '' Iio a = Ioi a, { convert image_const_sub_Iio _ _, simp }, exact mk_Ioi_real a ▸ h2 ▸ mk_image_le end /-- The cardinality of the interval (-∞, a]. -/ lemma mk_Iic_real (a : ℝ) : #(Iic a) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Iio_real a ▸ mk_le_mk_of_subset Iio_subset_Iic_self) /-- The cardinality of the interval (a, b). -/ lemma mk_Ioo_real {a b : ℝ} (h : a < b) : #(Ioo a b) = 𝔠 := begin refine le_antisymm (mk_real ▸ mk_set_le _) _, have h1 : #((λ x, x - a) '' Ioo a b) ≤ #(Ioo a b) := mk_image_le, refine le_trans _ h1, rw [image_sub_const_Ioo, sub_self], replace h := sub_pos_of_lt h, have h2 : #(has_inv.inv '' Ioo 0 (b - a)) ≤ #(Ioo 0 (b - a)) := mk_image_le, refine le_trans _ h2, rw [image_inv_Ioo_0_left h, mk_Ioi_real] end /-- The cardinality of the interval [a, b). -/ lemma mk_Ico_real {a b : ℝ} (h : a < b) : #(Ico a b) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ico_self) /-- The cardinality of the interval [a, b]. -/ lemma mk_Icc_real {a b : ℝ} (h : a < b) : #(Icc a b) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Icc_self) /-- The cardinality of the interval (a, b]. -/ lemma mk_Ioc_real {a b : ℝ} (h : a < b) : #(Ioc a b) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ioc_self) end cardinal
08d45ff3178f5e18ffe3d55dbba0cb3aa9f5c932
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/category_theory/limits/shapes/constructions/limits_of_products_and_equalizers.lean
0c3044fe45d1cd4397a1355183154978e20e98e5
[ "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
4,773
lean
/- -- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.finite_products /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. TODO: provide the dual result. -/ open category_theory open opposite namespace category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers -- We assume here only that we have exactly the products we need, so that we can prove -- variations of the construction (all products gives all limits, finite products gives finite limits...) variables (F : J ⥤ C) [H₁ : has_limit.{v} (functor.of_function F.obj)] [H₂ : has_limit.{v} (functor.of_function (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] include H₁ H₂ /-- Corresponding to any functor `F : J ⥤ C`, we construct a new functor from the walking parallel pair of morphisms to `C`, given by the diagram ``` s ∏_j F j ===> Π_{f : j ⟶ j'} F j' t ``` where the two morphisms `s` and `t` are defined componentwise: * The `s_f` component is the projection `∏_j F j ⟶ F j` followed by `f`. * The `t_f` component is the projection `∏_j F j ⟶ F j'`. In a moment we prove that cones over `F` are isomorphic to cones over this new diagram. -/ @[simp] def diagram : walking_parallel_pair ⥤ C := let pi_obj := limits.pi_obj F.obj in let pi_hom := limits.pi_obj (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2) in let s : pi_obj ⟶ pi_hom := pi.lift (λ f : (Σ p : J × J, p.1 ⟶ p.2), pi.π F.obj f.1.1 ≫ F.map f.2) in let t : pi_obj ⟶ pi_hom := pi.lift (λ f : (Σ p : J × J, p.1 ⟶ p.2), pi.π F.obj f.1.2) in parallel_pair s t /-- The morphism from cones over the walking pair diagram `diagram F` to cones over the original diagram `F`. -/ @[simp] def cones_hom : (diagram F).cones ⟶ F.cones := { app := λ X c, { app := λ j, c.app walking_parallel_pair.zero ≫ pi.π _ j, naturality' := λ j j' f, begin have L := c.naturality walking_parallel_pair_hom.left, have R := c.naturality walking_parallel_pair_hom.right, have t := congr_arg (λ g, g ≫ pi.π _ (⟨(j, j'), f⟩ : Σ (p : J × J), p.fst ⟶ p.snd)) (R.symm.trans L), dsimp at t, dsimp, simpa only [limit.lift_π, fan.mk_π_app, category.assoc, category.id_comp] using t, end }, }. local attribute [semireducible] op unop opposite /-- The morphism from cones over the original diagram `F` to cones over the walking pair diagram `diagram F`. -/ @[simp] def cones_inv : F.cones ⟶ (diagram F).cones := { app := λ X c, begin refine (fork.of_ι _ _).π, { exact pi.lift c.app }, { ext ⟨⟨A,B⟩,f⟩, dsimp, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw ←(c.naturality f), dsimp, simp only [category.id_comp], } end, naturality' := λ X Y f, by { ext c j, cases j; tidy, } }. /-- The natural isomorphism between cones over the walking pair diagram `diagram F` and cones over the original diagram `F`. -/ def cones_iso : (diagram F).cones ≅ F.cones := { hom := cones_hom F, inv := cones_inv F, hom_inv_id' := begin ext X c j, cases j, { ext, simp }, { ext, have t := c.naturality walking_parallel_pair_hom.left, conv at t { dsimp, to_lhs, simp only [category.id_comp] }, simp [t], } end } end has_limit_of_has_products_of_has_equalizers open has_limit_of_has_products_of_has_equalizers /-- Any category with products and equalizers has all limits. -/ -- This is not an instance, as it is not always how one wants to construct limits! def limits_from_equalizers_and_products [has_products.{v} C] [has_equalizers.{v} C] : has_limits.{v} C := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.of_cones_iso (diagram F) F (cones_iso F) } } /-- Any category with finite products and equalizers has all finite limits. -/ -- This is not an instance, as it is not always how one wants to construct finite limits! def finite_limits_from_equalizers_and_finite_products [has_finite_products.{v} C] [has_equalizers.{v} C] : has_finite_limits.{v} C := { has_limits_of_shape := λ J _ _, by exactI { has_limit := λ F, has_limit.of_cones_iso (diagram F) F (cones_iso F) } } end category_theory.limits
9e586b17893919c5c7267e77b097d9aa08b73e8c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/option/basic.lean
6100a0849479e289dd77ef9b2fc0ecae436699e8
[]
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
2,767
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic import Mathlib.Lean3Lib.init.control.monad import Mathlib.Lean3Lib.init.control.alternative universes u v u_1 u_2 namespace Mathlib namespace option def to_monad {m : Type → Type} [Monad m] [alternative m] {A : Type} : Option A → m A := sorry def get_or_else {α : Type u} : Option α → α → α := sorry def is_some {α : Type u} : Option α → Bool := sorry def is_none {α : Type u} : Option α → Bool := sorry def get {α : Type u} {o : Option α} : ↥(is_some o) → α := sorry def rhoare {α : Type u} : Bool → α → Option α := sorry def lhoare {α : Type u} : α → Option α → α := sorry infixr:1 "|>" => Mathlib.option.rhoare infixr:1 "<|" => Mathlib.option.lhoare protected def bind {α : Type u} {β : Type v} : Option α → (α → Option β) → Option β := sorry protected def map {α : Type u_1} {β : Type u_2} (f : α → β) (o : Option α) : Option β := option.bind o (some ∘ f) theorem map_id {α : Type u_1} : option.map id = id := sorry protected instance monad : Monad Option := { toApplicative := { toFunctor := { map := option.map, mapConst := fun (α β : Type u_1) => option.map ∘ function.const β }, toPure := { pure := some }, toSeq := { seq := fun (α β : Type u_1) (f : Option (α → β)) (x : Option α) => option.bind f fun (_x : α → β) => option.map _x x }, toSeqLeft := { seqLeft := fun (α β : Type u_1) (a : Option α) (b : Option β) => (fun (α β : Type u_1) (f : Option (α → β)) (x : Option α) => option.bind f fun (_x : α → β) => option.map _x x) β α (option.map (function.const β) a) b }, toSeqRight := { seqRight := fun (α β : Type u_1) (a : Option α) (b : Option β) => (fun (α β : Type u_1) (f : Option (α → β)) (x : Option α) => option.bind f fun (_x : α → β) => option.map _x x) β β (option.map (function.const α id) a) b } }, toBind := { bind := option.bind } } protected def orelse {α : Type u} : Option α → Option α → Option α := sorry protected instance alternative : alternative Option := alternative.mk none end option protected instance option.inhabited (α : Type u) : Inhabited (Option α) := { default := none } protected instance option.decidable_eq {α : Type u} [d : DecidableEq α] : DecidableEq (Option α) := sorry
6e048ecad9915ac78e811c447f91bfee75eb3119
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/locally_convex/basic.lean
098c89bb39681e582706738ede62338907dbc55d
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
14,533
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Bhavik Mehta, Yaël Dillies -/ import analysis.convex.basic import analysis.normed_space.lattice_ordered_group import analysis.normed_space.ordered /-! # Local convexity This file defines absorbent and balanced sets. An absorbent set is one that "surrounds" the origin. The idea is made precise by requiring that any point belongs to all large enough scalings of the set. This is the vector world analog of a topological neighborhood of the origin. A balanced set is one that is everywhere around the origin. This means that `a • s ⊆ s` for all `a` of norm less than `1`. ## Main declarations For a module over a normed ring: * `absorbs`: A set `s` absorbs a set `t` if all large scalings of `s` contain `t`. * `absorbent`: A set `s` is absorbent if every point eventually belongs to all large scalings of `s`. * `balanced`: A set `s` is balanced if `a • s ⊆ s` for all `a` of norm less than `1`. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags absorbent, balanced, locally convex, LCTVS -/ open set open_locale pointwise topological_space variables {𝕜 𝕝 E : Type*} {ι : Sort*} {κ : ι → Sort*} section semi_normed_ring variables [semi_normed_ring 𝕜] section has_smul variables (𝕜) [has_smul 𝕜 E] /-- A set `A` absorbs another set `B` if `B` is contained in all scalings of `A` by elements of sufficiently large norm. -/ def absorbs (A B : set E) := ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → B ⊆ a • A variables {𝕜} {s t u v A B : set E} @[simp] lemma absorbs_empty {s : set E}: absorbs 𝕜 s (∅ : set E) := ⟨1, one_pos, λ a ha, set.empty_subset _⟩ lemma absorbs.mono (hs : absorbs 𝕜 s u) (hst : s ⊆ t) (hvu : v ⊆ u) : absorbs 𝕜 t v := let ⟨r, hr, h⟩ := hs in ⟨r, hr, λ a ha, hvu.trans $ (h _ ha).trans $ smul_set_mono hst⟩ lemma absorbs.mono_left (hs : absorbs 𝕜 s u) (h : s ⊆ t) : absorbs 𝕜 t u := hs.mono h subset.rfl lemma absorbs.mono_right (hs : absorbs 𝕜 s u) (h : v ⊆ u) : absorbs 𝕜 s v := hs.mono subset.rfl h lemma absorbs.union (hu : absorbs 𝕜 s u) (hv : absorbs 𝕜 s v) : absorbs 𝕜 s (u ∪ v) := begin obtain ⟨a, ha, hu⟩ := hu, obtain ⟨b, hb, hv⟩ := hv, exact ⟨max a b, lt_max_of_lt_left ha, λ c hc, union_subset (hu _ $ le_of_max_le_left hc) (hv _ $ le_of_max_le_right hc)⟩, end @[simp] lemma absorbs_union : absorbs 𝕜 s (u ∪ v) ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 s v := ⟨λ h, ⟨h.mono_right $ subset_union_left _ _, h.mono_right $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ lemma absorbs_Union_finset {ι : Type*} {t : finset ι} {f : ι → set E} : absorbs 𝕜 s (⋃ i ∈ t, f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin classical, induction t using finset.induction_on with i t ht hi, { simp only [finset.not_mem_empty, set.Union_false, set.Union_empty, absorbs_empty, is_empty.forall_iff, implies_true_iff] }, rw [finset.set_bUnion_insert, absorbs_union, hi], split; intro h, { refine λ _ hi', (finset.mem_insert.mp hi').elim _ (h.2 _), exact (λ hi'', by { rw hi'', exact h.1 }) }, exact ⟨h i (finset.mem_insert_self i t), λ i' hi', h i' (finset.mem_insert_of_mem hi')⟩, end lemma set.finite.absorbs_Union {ι : Type*} {s : set E} {t : set ι} {f : ι → set E} (hi : t.finite) : absorbs 𝕜 s (⋃ i ∈ t, f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin lift t to finset ι using hi, simp only [finset.mem_coe], exact absorbs_Union_finset, end variables (𝕜) /-- A set is absorbent if it absorbs every singleton. -/ def absorbent (A : set E) := ∀ x, ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → x ∈ a • A variables {𝕜} lemma absorbent.subset (hA : absorbent 𝕜 A) (hAB : A ⊆ B) : absorbent 𝕜 B := begin refine forall_imp (λ x, _) hA, exact Exists.imp (λ r, and.imp_right $ forall₂_imp $ λ a ha hx, set.smul_set_mono hAB hx), end lemma absorbent_iff_forall_absorbs_singleton : absorbent 𝕜 A ↔ ∀ x, absorbs 𝕜 A {x} := by simp_rw [absorbs, absorbent, singleton_subset_iff] lemma absorbent.absorbs (hs : absorbent 𝕜 s) {x : E} : absorbs 𝕜 s {x} := absorbent_iff_forall_absorbs_singleton.1 hs _ lemma absorbent_iff_nonneg_lt : absorbent 𝕜 A ↔ ∀ x, ∃ r, 0 ≤ r ∧ ∀ ⦃a : 𝕜⦄, r < ∥a∥ → x ∈ a • A := forall_congr $ λ x, ⟨λ ⟨r, hr, hx⟩, ⟨r, hr.le, λ a ha, hx a ha.le⟩, λ ⟨r, hr, hx⟩, ⟨r + 1, add_pos_of_nonneg_of_pos hr zero_lt_one, λ a ha, hx ((lt_add_of_pos_right r zero_lt_one).trans_le ha)⟩⟩ lemma absorbent.absorbs_finite {s : set E} (hs : absorbent 𝕜 s) {v : set E} (hv : v.finite) : absorbs 𝕜 s v := begin rw ←set.bUnion_of_singleton v, exact hv.absorbs_Union.mpr (λ _ _, hs.absorbs), end variables (𝕜) /-- A set `A` is balanced if `a • A` is contained in `A` whenever `a` has norm at most `1`. -/ def balanced (A : set E) := ∀ a : 𝕜, ∥a∥ ≤ 1 → a • A ⊆ A variables {𝕜} lemma balanced_iff_smul_mem : balanced 𝕜 s ↔ ∀ ⦃a : 𝕜⦄, ∥a∥ ≤ 1 → ∀ ⦃x : E⦄, x ∈ s → a • x ∈ s := forall₂_congr $ λ a ha, smul_set_subset_iff alias balanced_iff_smul_mem ↔ balanced.smul_mem _ @[simp] lemma balanced_empty : balanced 𝕜 (∅ : set E) := λ _ _, by { rw smul_set_empty } @[simp] lemma balanced_univ : balanced 𝕜 (univ : set E) := λ a ha, subset_univ _ lemma balanced.union (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∪ B) := λ a ha, smul_set_union.subset.trans $ union_subset_union (hA _ ha) $ hB _ ha lemma balanced.inter (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∩ B) := λ a ha, smul_set_inter_subset.trans $ inter_subset_inter (hA _ ha) $ hB _ ha lemma balanced_Union {f : ι → set E} (h : ∀ i, balanced 𝕜 (f i)) : balanced 𝕜 (⋃ i, f i) := λ a ha, (smul_set_Union _ _).subset.trans $ Union_mono $ λ _, h _ _ ha lemma balanced_Union₂ {f : Π i, κ i → set E} (h : ∀ i j, balanced 𝕜 (f i j)) : balanced 𝕜 (⋃ i j, f i j) := balanced_Union $ λ _, balanced_Union $ h _ lemma balanced_Inter {f : ι → set E} (h : ∀ i, balanced 𝕜 (f i)) : balanced 𝕜 (⋂ i, f i) := λ a ha, (smul_set_Inter_subset _ _).trans $ Inter_mono $ λ _, h _ _ ha lemma balanced_Inter₂ {f : Π i, κ i → set E} (h : ∀ i j, balanced 𝕜 (f i j)) : balanced 𝕜 (⋂ i j, f i j) := balanced_Inter $ λ _, balanced_Inter $ h _ variables [has_smul 𝕝 E] [smul_comm_class 𝕜 𝕝 E] lemma balanced.smul (a : 𝕝) (hs : balanced 𝕜 s) : balanced 𝕜 (a • s) := λ b hb, (smul_comm _ _ _).subset.trans $ smul_set_mono $ hs _ hb end has_smul section module variables [add_comm_group E] [module 𝕜 E] {s s₁ s₂ t t₁ t₂ : set E} lemma absorbs.neg : absorbs 𝕜 s t → absorbs 𝕜 (-s) (-t) := Exists.imp $ λ r, and.imp_right $ forall₂_imp $ λ _ _ h, (neg_subset_neg.2 h).trans (smul_set_neg _ _).superset lemma balanced.neg : balanced 𝕜 s → balanced 𝕜 (-s) := forall₂_imp $ λ _ _ h, (smul_set_neg _ _).subset.trans $ neg_subset_neg.2 h lemma absorbs.add : absorbs 𝕜 s₁ t₁ → absorbs 𝕜 s₂ t₂ → absorbs 𝕜 (s₁ + s₂) (t₁ + t₂) := λ ⟨r₁, hr₁, h₁⟩ ⟨r₂, hr₂, h₂⟩, ⟨max r₁ r₂, lt_max_of_lt_left hr₁, λ a ha, (add_subset_add (h₁ _ $ le_of_max_le_left ha) $ h₂ _ $ le_of_max_le_right ha).trans (smul_add _ _ _).superset⟩ lemma balanced.add (hs : balanced 𝕜 s) (ht : balanced 𝕜 t) : balanced 𝕜 (s + t) := λ a ha, (smul_add _ _ _).subset.trans $ add_subset_add (hs _ ha) $ ht _ ha lemma absorbs.sub (h₁ : absorbs 𝕜 s₁ t₁) (h₂ : absorbs 𝕜 s₂ t₂) : absorbs 𝕜 (s₁ - s₂) (t₁ - t₂) := by { simp_rw sub_eq_add_neg, exact h₁.add h₂.neg } lemma balanced.sub (hs : balanced 𝕜 s) (ht : balanced 𝕜 t) : balanced 𝕜 (s - t) := by { simp_rw sub_eq_add_neg, exact hs.add ht.neg } lemma balanced_zero : balanced 𝕜 (0 : set E) := λ a ha, (smul_zero _).subset end module end semi_normed_ring section normed_field variables [normed_field 𝕜] [normed_ring 𝕝] [normed_space 𝕜 𝕝] [add_comm_group E] [module 𝕜 E] [smul_with_zero 𝕝 E] [is_scalar_tower 𝕜 𝕝 E] {s t u v A B : set E} {x : E} {a b : 𝕜} /-- Scalar multiplication (by possibly different types) of a balanced set is monotone. -/ lemma balanced.smul_mono (hs : balanced 𝕝 s) {a : 𝕝} {b : 𝕜} (h : ∥a∥ ≤ ∥b∥) : a • s ⊆ b • s := begin obtain rfl | hb := eq_or_ne b 0, { rw norm_zero at h, rw norm_eq_zero.1 (h.antisymm $ norm_nonneg _), obtain rfl | h := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty] }, { simp_rw [zero_smul_set h] } }, rintro _ ⟨x, hx, rfl⟩, refine ⟨b⁻¹ • a • x, _, smul_inv_smul₀ hb _⟩, rw ←smul_assoc, refine hs _ _ (smul_mem_smul_set hx), rw [norm_smul, norm_inv, ←div_eq_inv_mul], exact div_le_one_of_le h (norm_nonneg _), end /-- A balanced set absorbs itself. -/ lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A := begin refine ⟨1, zero_lt_one, λ a ha x hx, _⟩, rw mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), refine hA a⁻¹ _ (smul_mem_smul_set hx), rw norm_inv, exact inv_le_one ha, end lemma balanced.subset_smul (hA : balanced 𝕜 A) (ha : 1 ≤ ∥a∥) : A ⊆ a • A := begin refine (subset_set_smul_iff₀ _).2 (hA (a⁻¹) _), { rintro rfl, rw norm_zero at ha, exact zero_lt_one.not_le ha }, { rw norm_inv, exact inv_le_one ha } end lemma balanced.smul_eq (hA : balanced 𝕜 A) (ha : ∥a∥ = 1) : a • A = A := (hA _ ha.le).antisymm $ hA.subset_smul ha.ge lemma balanced.mem_smul_iff (hs : balanced 𝕜 s) (h : ∥a∥ = ∥b∥) : a • x ∈ s ↔ b • x ∈ s := begin obtain rfl | hb := eq_or_ne b 0, { rw [norm_zero, norm_eq_zero] at h, rw h }, have ha : a ≠ 0 := norm_ne_zero_iff.1 (ne_of_eq_of_ne h $ norm_ne_zero_iff.2 hb), split; intro h'; [rw ←inv_mul_cancel_right₀ ha b, rw ←inv_mul_cancel_right₀ hb a]; { rw [←smul_eq_mul, smul_assoc], refine hs.smul_mem _ h', simp [←h, ha] } end lemma balanced.neg_mem_iff (hs : balanced 𝕜 s) : -x ∈ s ↔ x ∈ s := by convert hs.mem_smul_iff (norm_neg 1); simp only [neg_smul, one_smul] lemma absorbs.inter (hs : absorbs 𝕜 s u) (ht : absorbs 𝕜 t u) : absorbs 𝕜 (s ∩ t) u := begin obtain ⟨a, ha, hs⟩ := hs, obtain ⟨b, hb, ht⟩ := ht, have h : 0 < max a b := lt_max_of_lt_left ha, refine ⟨max a b, lt_max_of_lt_left ha, λ c hc, _⟩, rw smul_set_inter₀ (norm_pos_iff.1 $ h.trans_le hc), exact subset_inter (hs _ $ le_of_max_le_left hc) (ht _ $ le_of_max_le_right hc), end @[simp] lemma absorbs_inter : absorbs 𝕜 (s ∩ t) u ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 t u := ⟨λ h, ⟨h.mono_left $ inter_subset_left _ _, h.mono_left $ inter_subset_right _ _⟩, λ h, h.1.inter h.2⟩ lemma absorbent_univ : absorbent 𝕜 (univ : set E) := begin refine λ x, ⟨1, zero_lt_one, λ a ha, _⟩, rw smul_set_univ₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), exact trivial, end variables [topological_space E] [has_continuous_smul 𝕜 E] /-- Every neighbourhood of the origin is absorbent. -/ lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A := begin intro x, obtain ⟨w, hw₁, hw₂, hw₃⟩ := mem_nhds_iff.mp hA, have hc : continuous (λ t : 𝕜, t • x) := continuous_id.smul continuous_const, obtain ⟨r, hr₁, hr₂⟩ := metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul]), have hr₃ := inv_pos.mpr (half_pos hr₁), refine ⟨(r / 2)⁻¹, hr₃, λ a ha₁, _⟩, have ha₂ : 0 < ∥a∥ := hr₃.trans_le ha₁, refine (mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp ha₂) _ _).2 (hw₁ $ hr₂ _), rw [metric.mem_ball, dist_zero_right, norm_inv], calc ∥a∥⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁ ... < r : half_lt_self hr₁, end /-- The union of `{0}` with the interior of a balanced set is balanced. -/ lemma balanced_zero_union_interior (hA : balanced 𝕜 A) : balanced 𝕜 ((0 : set E) ∪ interior A) := begin intros a ha, obtain rfl | h := eq_or_ne a 0, { rw zero_smul_set, exacts [subset_union_left _ _, ⟨0, or.inl rfl⟩] }, { rw [←image_smul, image_union], apply union_subset_union, { rw [image_zero, smul_zero], refl }, { calc a • interior A ⊆ interior (a • A) : (is_open_map_smul₀ h).image_interior_subset A ... ⊆ interior A : interior_mono (hA _ ha) } } end /-- The interior of a balanced set is balanced if it contains the origin. -/ lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) : balanced 𝕜 (interior A) := begin rw ←union_eq_self_of_subset_left (singleton_subset_iff.2 h), exact balanced_zero_union_interior hA, end lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) := λ a ha, (image_closure_subset_closure_image $ continuous_id.const_smul _).trans $ closure_mono $ hA _ ha end normed_field section nontrivially_normed_field variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {s : set E} lemma absorbs_zero_iff : absorbs 𝕜 s 0 ↔ (0 : E) ∈ s := begin refine ⟨_, λ h, ⟨1, zero_lt_one, λ a _, zero_subset.2 $ zero_mem_smul_set h⟩⟩, rintro ⟨r, hr, h⟩, obtain ⟨a, ha⟩ := normed_space.exists_lt_norm 𝕜 𝕜 r, have := h _ ha.le, rwa [zero_subset, zero_mem_smul_set_iff] at this, exact norm_ne_zero_iff.1 (hr.trans ha).ne', end lemma absorbent.zero_mem (hs : absorbent 𝕜 s) : (0 : E) ∈ s := absorbs_zero_iff.1 $ absorbent_iff_forall_absorbs_singleton.1 hs _ end nontrivially_normed_field section real variables [add_comm_group E] [module ℝ E] {s : set E} lemma balanced_iff_neg_mem (hs : convex ℝ s) : balanced ℝ s ↔ ∀ ⦃x⦄, x ∈ s → -x ∈ s := begin refine ⟨λ h x, h.neg_mem_iff.2, λ h a ha, smul_set_subset_iff.2 $ λ x hx, _⟩, rw [real.norm_eq_abs, abs_le] at ha, rw [show a = -((1 - a) / 2) + (a - -1)/2, by ring, add_smul, neg_smul, ←smul_neg], exact hs (h hx) hx (div_nonneg (sub_nonneg_of_le ha.2) zero_le_two) (div_nonneg (sub_nonneg_of_le ha.1) zero_le_two) (by ring), end end real
e3d8fb3423ede85d1bd0a05b50b44839f9f93569
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/category/constructions/set.hlean
826bee75fa9fddee0fe53229483d2559ee036c34
[ "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
3,570
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Category of sets -/ import ..functor.basic ..category types.equiv types.lift open eq category equiv iso is_equiv is_trunc function sigma namespace category definition precategory_Set.{u} [reducible] [constructor] : precategory Set.{u} := precategory.mk (λx y : Set, x → y) (λx y z g f a, g (f a)) (λx a, a) (λx y z w h g f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) definition Precategory_Set [reducible] [constructor] : Precategory := Precategory.mk Set precategory_Set abbreviation set [constructor] := Precategory_Set namespace set local attribute is_equiv_subtype_eq [instance] definition iso_of_equiv [constructor] {A B : set} (f : A ≃ B) : A ≅ B := iso.MK (to_fun f) (to_inv f) (eq_of_homotopy (left_inv (to_fun f))) (eq_of_homotopy (right_inv (to_fun f))) definition equiv_of_iso [constructor] {A B : set} (f : A ≅ B) : A ≃ B := begin apply equiv.MK (to_hom f) (iso.to_inv f), exact ap10 (to_right_inverse f), exact ap10 (to_left_inverse f) end definition is_equiv_iso_of_equiv [constructor] (A B : set) : is_equiv (@iso_of_equiv A B) := adjointify _ (λf, equiv_of_iso f) (λf, proof iso_eq idp qed) (λf, equiv_eq idp) local attribute is_equiv_iso_of_equiv [instance] definition iso_of_eq_eq_compose (A B : Set) : @iso_of_eq _ _ A B = @iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B := eq_of_homotopy (λp, eq.rec_on p idp) definition equiv_equiv_iso (A B : set) : (A ≃ B) ≃ (A ≅ B) := equiv.MK (λf, iso_of_equiv f) (λf, proof equiv.MK (to_hom f) (iso.to_inv f) (ap10 (to_right_inverse f)) (ap10 (to_left_inverse f)) qed) (λf, proof iso_eq idp qed) (λf, proof equiv_eq idp qed) definition equiv_eq_iso (A B : set) : (A ≃ B) = (A ≅ B) := ua !equiv_equiv_iso definition is_univalent_Set (A B : set) : is_equiv (iso_of_eq : A = B → A ≅ B) := have H₁ : is_equiv (@iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B), from @is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ _ (@is_equiv_subtype_eq_inv _ _ _ _ _)) !univalence) !is_equiv_iso_of_equiv, let H₂ := (iso_of_eq_eq_compose A B)⁻¹ in begin rewrite H₂ at H₁, assumption end end set definition category_Set [instance] [constructor] : category Set := category.mk precategory_Set set.is_univalent_Set definition Category_Set [reducible] [constructor] : Category := Category.mk Set category_Set abbreviation cset [constructor] := Category_Set open functor lift definition functor_lift.{u v} [constructor] : set.{u} ⇒ set.{max u v} := functor.mk tlift (λa b, lift_functor) (λa, eq_of_homotopy (λx, by induction x; reflexivity)) (λa b c g f, eq_of_homotopy (λx, by induction x; reflexivity)) end category
464a11951f87f935c199fd3983627c6cc12bd871
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/group_ring_action.lean
e9e32e21882d7b1360ae04080852117f4ffc84df
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,460
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import group_theory.group_action.group import data.equiv.ring import deprecated.subring /-! # Group action on rings This file defines the typeclass of monoid acting on semirings `mul_semiring_action M R`, and the corresponding typeclass of invariant subrings. Note that `algebra` does not satisfy the axioms of `mul_semiring_action`. ## Implementation notes There is no separate typeclass for group acting on rings, group acting on fields, etc. They are all grouped under `mul_semiring_action`. ## Tags group action, invariant subring -/ universes u v open_locale big_operators /-- Typeclass for multiplicative actions by monoids on semirings. -/ class mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends distrib_mul_action M R := (smul_one : ∀ (g : M), (g • 1 : R) = 1) (smul_mul : ∀ (g : M) (x y : R), g • (x * y) = (g • x) * (g • y)) export mul_semiring_action (smul_one) /-- Typeclass for faithful multiplicative actions by monoids on semirings. -/ class faithful_mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends mul_semiring_action M R := (eq_of_smul_eq_smul' : ∀ {m₁ m₂ : M}, (∀ r : R, m₁ • r = m₂ • r) → m₁ = m₂) section semiring variables (M G : Type u) [monoid M] [group G] variables (A R S F : Type v) [add_monoid A] [semiring R] [comm_semiring S] [field F] variables {M R} lemma smul_mul' [mul_semiring_action M R] (g : M) (x y : R) : g • (x * y) = (g • x) * (g • y) := mul_semiring_action.smul_mul g x y variables {M} (R) theorem eq_of_smul_eq_smul [faithful_mul_semiring_action M R] {m₁ m₂ : M} : (∀ r : R, m₁ • r = m₂ • r) → m₁ = m₂ := faithful_mul_semiring_action.eq_of_smul_eq_smul' variables (M R) /-- Each element of the monoid defines a additive monoid homomorphism. -/ def distrib_mul_action.to_add_monoid_hom [distrib_mul_action M A] (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } /-- Each element of the group defines an additive monoid isomorphism. -/ def distrib_mul_action.to_add_equiv [distrib_mul_action G A] (x : G) : A ≃+ A := { .. distrib_mul_action.to_add_monoid_hom G A x, .. mul_action.to_perm G A x } /-- Each element of the group defines an additive monoid homomorphism. -/ def distrib_mul_action.hom_add_monoid_hom [distrib_mul_action M A] : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom M A, map_one' := add_monoid_hom.ext $ λ x, one_smul M x, map_mul' := λ x y, add_monoid_hom.ext $ λ z, mul_smul x y z } /-- Each element of the monoid defines a semiring homomorphism. -/ def mul_semiring_action.to_semiring_hom [mul_semiring_action M R] (x : M) : R →+* R := { map_one' := smul_one x, map_mul' := smul_mul' x, .. distrib_mul_action.to_add_monoid_hom M R x } theorem injective_to_semiring_hom [faithful_mul_semiring_action M R] : function.injective (mul_semiring_action.to_semiring_hom M R) := λ m₁ m₂ h, eq_of_smul_eq_smul R $ λ r, ring_hom.ext_iff.1 h r /-- Each element of the group defines a semiring isomorphism. -/ def mul_semiring_action.to_semiring_equiv [mul_semiring_action G R] (x : G) : R ≃+* R := { .. distrib_mul_action.to_add_equiv G R x, .. mul_semiring_action.to_semiring_hom G R x } section prod variables [mul_semiring_action M R] [mul_semiring_action M S] lemma list.smul_prod (g : M) (L : list R) : g • L.prod = (L.map $ (•) g).prod := monoid_hom.map_list_prod (mul_semiring_action.to_semiring_hom M R g : R →* R) L lemma multiset.smul_prod (g : M) (m : multiset S) : g • m.prod = (m.map $ (•) g).prod := monoid_hom.map_multiset_prod (mul_semiring_action.to_semiring_hom M S g : S →* S) m lemma smul_prod (g : M) {ι : Type*} (f : ι → S) (s : finset ι) : g • ∏ i in s, f i = ∏ i in s, g • f i := monoid_hom.map_prod (mul_semiring_action.to_semiring_hom M S g : S →* S) f s end prod section simp_lemmas variables {M G A R} attribute [simp] smul_one smul_mul' smul_zero smul_add @[simp] lemma smul_inv [mul_semiring_action M F] (x : M) (m : F) : x • m⁻¹ = (x • m)⁻¹ := (mul_semiring_action.to_semiring_hom M F x).map_inv _ @[simp] lemma smul_pow [mul_semiring_action M R] (x : M) (m : R) (n : ℕ) : x • m ^ n = (x • m) ^ n := nat.rec_on n (smul_one x) $ λ n ih, (smul_mul' x m (m ^ n)).trans $ congr_arg _ ih end simp_lemmas end semiring section ring variables (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R] variables (S : set R) [is_subring S] open mul_action set_option old_structure_cmd false /-- A subring invariant under the action. -/ class is_invariant_subring : Prop := (smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S) variables [is_invariant_subring M S] local attribute [instance] subset.ring instance is_invariant_subring.to_mul_semiring_action : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subring.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } end ring
20652e0e3d4eba64e994a0fd9bd14ad976459cb5
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/order/filter/ennreal.lean
da040c9193c1f7e3106a73e85de085bff8187c6a
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
3,945
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import data.real.ennreal import order.filter.countable_Inter import order.liminf_limsup /-! # Order properties of extended non-negative reals This file compiles filter-related results about `ℝ≥0∞` (see data/real/ennreal.lean). -/ open filter open_locale filter ennreal namespace ennreal variables {α : Type*} {f : filter α} lemma eventually_le_limsup [countable_Inter_filter f] (u : α → ℝ≥0∞) : ∀ᶠ y in f, u y ≤ f.limsup u := begin by_cases hx_top : f.limsup u = ⊤, { simp_rw hx_top, exact eventually_of_forall (λ a, le_top), }, have h_forall_le : ∀ᶠ y in f, ∀ n : ℕ, u y < f.limsup u + (1:ℝ≥0∞)/n, { rw eventually_countable_forall, refine λ n, eventually_lt_of_limsup_lt _, nth_rewrite 0 ←add_zero (f.limsup u), exact (add_lt_add_iff_left (lt_top_iff_ne_top.mpr hx_top)).mpr (by simp), }, refine h_forall_le.mono (λ y hy, le_of_forall_pos_le_add (λ r hr_pos hx_top, _)), have hr_ne_zero : (r : ℝ≥0∞) ≠ 0, { rw [ne.def, coe_eq_zero], exact (ne_of_lt hr_pos).symm, }, cases (exists_inv_nat_lt hr_ne_zero) with i hi, rw inv_eq_one_div at hi, exact le_trans (le_of_lt (hy i)) (add_le_add_left hi.le (f.limsup u)), end lemma limsup_eq_zero_iff [countable_Inter_filter f] {u : α → ℝ≥0∞} : f.limsup u = 0 ↔ u =ᶠ[f] 0 := begin split; intro h, { have hu_zero := eventually_le.trans (eventually_le_limsup u) (eventually_of_forall (λ _, le_of_eq h)), exact hu_zero.mono (λ x hx, le_antisymm hx (zero_le _)), }, { rw limsup_congr h, simp_rw [pi.zero_apply, ←ennreal.bot_eq_zero, limsup_const_bot] }, end lemma limsup_const_mul_of_ne_top {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha_top : a ≠ ⊤) : f.limsup (λ (x : α), a * (u x)) = a * f.limsup u := begin by_cases ha_zero : a = 0, { simp_rw [ha_zero, zero_mul, ←ennreal.bot_eq_zero], exact limsup_const_bot, }, let g := λ x : ℝ≥0∞, a * x, have hg_bij : function.bijective g, from function.bijective_iff_has_inverse.mpr ⟨(λ x, a⁻¹ * x), ⟨λ x, by simp [←mul_assoc, inv_mul_cancel ha_zero ha_top], λ x, by simp [g, ←mul_assoc, mul_inv_cancel ha_zero ha_top]⟩⟩, have hg_mono : strict_mono g, from strict_mono_of_monotone_of_injective (λ _ _ _, by rwa mul_le_mul_left ha_zero ha_top) hg_bij.1, let g_iso := strict_mono.order_iso_of_surjective g hg_mono hg_bij.2, refine (order_iso.limsup_apply g_iso _ _ _ _).symm, all_goals { by is_bounded_default }, end lemma limsup_const_mul [countable_Inter_filter f] {u : α → ℝ≥0∞} {a : ℝ≥0∞} : f.limsup (λ (x : α), a * (u x)) = a * f.limsup u := begin by_cases ha_top : a ≠ ⊤, { exact limsup_const_mul_of_ne_top ha_top, }, push_neg at ha_top, by_cases hu : u =ᶠ[f] 0, { have hau : (λ x, a * (u x)) =ᶠ[f] 0, { refine hu.mono (λ x hx, _), rw pi.zero_apply at hx, simp [hx], }, simp only [limsup_congr hu, limsup_congr hau, pi.zero_apply, ← bot_eq_zero, limsup_const_bot], simp, }, { simp_rw [ha_top, top_mul], have hu_mul : ∃ᶠ (x : α) in f, ⊤ ≤ ite (u x = 0) (0 : ℝ≥0∞) ⊤, { rw [eventually_eq, not_eventually] at hu, refine hu.mono (λ x hx, _), rw pi.zero_apply at hx, simp [hx], }, have h_top_le : f.limsup (λ (x : α), ite (u x = 0) (0 : ℝ≥0∞) ⊤) = ⊤, from eq_top_iff.mpr (le_limsup_of_frequently_le hu_mul), have hfu : f.limsup u ≠ 0, from mt limsup_eq_zero_iff.1 hu, simp only [h_top_le, hfu, if_false], }, end lemma limsup_add_le [countable_Inter_filter f] (u v : α → ℝ≥0∞) : f.limsup (u + v) ≤ f.limsup u + f.limsup v := Inf_le ((eventually_le_limsup u).mp ((eventually_le_limsup v).mono (λ _ hxg hxf, add_le_add hxf hxg))) end ennreal
b9ce5333c5b0f2463d0e2d95cd692493325bc001
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/int/basic.lean
2747196bd24ef695930f9d932b9b826e28265077
[ "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
47,475
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. -/ import data.nat.basic data.list.basic algebra.char_zero algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨0⟩ meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩ attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] @[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i, p i → p (i + 1)) (hn : ∀i, p i → p (i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { have := hn _ n_ih, simpa } }, exact this (i + 1) } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have, { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp [(*), int.mul, nat_abs_neg_of_nat] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : b > 0) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) @[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ @[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ @[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0 | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] @[simp] theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] lemma mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show (2 : ℤ) ≥ 0, from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : n % 2 ≥ 0 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw int.mul_div_cancel_left, rw mul_assoc at h, apply _root_.eq_of_mul_eq_mul_left _ h, repeat {assumption} end theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd]; cases m.bodd; cases n.bodd; refl @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd]; cases m.bodd; cases n.bodd; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) @[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩ @[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl @[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl @[simp] theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n := by simp @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add]; apply congr_arg (λ x:ℕ, -(x:α)); simp @[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 @[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] theorem eq_cast [add_group α] [has_one α] (f : ℤ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n := begin have H : ∀ (n : ℕ), f n = n := nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y), cases n, {apply H}, apply eq_neg_of_add_eq_zero, rw [← nat.cast_zero, ← H 0, int.coe_nat_zero, ← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1), Hadd, show f (n+1) = n+1, from H (n+1)] end @[simp] theorem cast_id (n : ℤ) : ↑n = n := (eq_cast id rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast section decidable def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end decidable end int
d2adbde102a21b22f70675126723ede9b7dfc784
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/int/basic.lean
433b7cb209aceceaec82a93b377ac72a0e9e995e
[ "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
19,326
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.nat.basic import order.monotone.basic /-! # Basic instances on the integers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains: * instances on `ℤ`. The stronger one is `int.comm_ring`. See `data/int/defs/order` for `int.linear_ordered_comm_ring`. * basic lemmas about the integers, but which do not use the ordered algebra hierarchy. -/ open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring ℤ := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, sub := int.sub, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm, nat_cast := int.of_nat, nat_cast_zero := rfl, nat_cast_succ := λ n, rfl, int_cast := λ n, n, int_cast_of_nat := λ n, rfl, int_cast_neg_succ_of_nat := λ n, rfl, zsmul := (*), zsmul_zero' := int.zero_mul, zsmul_succ' := λ n x, by rw [nat.succ_eq_add_one, nat.add_comm, of_nat_add, int.distrib_right, of_nat_one, int.one_mul], zsmul_neg' := λ n x, int.neg_mul_eq_neg_mul_symm (n.succ : ℤ) x } /-! ### Extra instances to short-circuit type class resolution These also prevent non-computable instances like `int.normed_comm_ring` being used to construct these instances non-computably. -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid ℤ := by apply_instance instance : add_monoid ℤ := by apply_instance instance : monoid ℤ := by apply_instance instance : comm_monoid ℤ := by apply_instance instance : comm_semigroup ℤ := by apply_instance instance : semigroup ℤ := by apply_instance instance : add_comm_group ℤ := by apply_instance instance : add_group ℤ := by apply_instance instance : add_comm_semigroup ℤ := by apply_instance instance : add_semigroup ℤ := by apply_instance instance : comm_semiring ℤ := by apply_instance instance : semiring ℤ := by apply_instance instance : ring ℤ := by apply_instance instance : distrib ℤ := by apply_instance end int namespace int @[simp] lemma add_neg_one (i : ℤ) : i + -1 = i - 1 := rfl @[simp] lemma default_eq_zero : default = (0 : ℤ) := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ section -- Note that here we are disabling the "safety" of reflected, to allow us to reuse `int.mk_numeral`. -- The usual way to provide the required `reflected` instance would be via rewriting to prove that -- the expression we use here is equivalent. local attribute [semireducible] reflected meta instance reflect : has_reflect ℤ := int.mk_numeral `(ℤ) `(by apply_instance : has_zero ℤ) `(by apply_instance : has_one ℤ) `(by apply_instance : has_add ℤ) `(by apply_instance : has_neg ℤ) end attribute [simp] int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] lemma neg_succ_not_nonneg (n : ℕ) : 0 ≤ -[1+ n] ↔ false := by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, } @[simp] lemma neg_succ_not_pos (n : ℕ) : 0 < -[1+ n] ↔ false := by simp only [not_lt, iff_false] @[simp] lemma neg_succ_sub_one (n : ℕ) : -[1+ n] - 1 = -[1+ (n+1)] := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n lemma coe_nat_strict_mono : strict_mono (coe : ℕ → ℤ) := λ _ _, int.coe_nat_lt.2 lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) @[simp] lemma neg_of_nat_ne_zero (n : ℕ) : -[1+ n] ≠ 0 := λ h, int.no_confusion h @[simp] lemma zero_ne_neg_of_nat (n : ℕ) : 0 ≠ -[1+ n] := λ h, int.no_confusion h /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl @[norm_cast] lemma coe_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by { cases n, cases h, simp, } @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀ i : ℕ, p i → p (i + 1)) (hn : ∀ i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀ n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end /-! ### nat abs -/ variables {a b : ℤ} {n : ℕ} attribute [simp] nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ (λ i n e, _) rfl), { rintro i n rfl, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end lemma nat_abs_sub_le (a b : ℤ) : nat_abs (a - b) ≤ nat_abs a + nat_abs b := by { rw [sub_eq_add_neg, ← int.nat_abs_neg b], apply nat_abs_add_le } theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) : a.nat_abs * b.nat_abs = c := by rw [← nat_abs_mul, h, nat_abs_of_nat] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_ne_zero {a : ℤ} : a.nat_abs ≠ 0 ↔ a ≠ 0 := not_congr int.nat_abs_eq_zero lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa [coe_nat_lt] using w₂, end lemma nat_abs_eq_nat_abs_iff {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a = b ∨ a = -b := begin split; intro h, { cases int.nat_abs_eq a with h₁ h₁; cases int.nat_abs_eq b with h₂ h₂; rw [h₁, h₂]; simp [h], }, { cases h; rw h, rw int.nat_abs_neg, }, end lemma nat_abs_eq_iff {a : ℤ} {n : ℕ} : a.nat_abs = n ↔ a = n ∨ a = -n := by rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_of_nat] /-! ### `/` -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end -- Will be generalized to Euclidean domains. local attribute [simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | (n:ℕ) := show of_nat _ = _, by simp | -[1+ n] := show -of_nat _ = _, by simp local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | (n:ℕ) := show of_nat _ = _, by simp | -[1+ n] := rfl @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | (m : ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | (n:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end /-! ### mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := rfl local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) (n : ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) -[1+ n] := show (_ + -(n+1) * -((m) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem div_add_mod (a b : ℤ) : b * (a / b) + a % b = a := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℤ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℤ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) /-! ### properties of `/` and `%` -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (H : 0 < b) (c : ℤ) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (H : 0 < a) (b c : ℤ) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma nat_abs_sign (z : ℤ) : z.sign.nat_abs = if z = 0 then 0 else 1 := by rcases z with (_ | _) | _; refl lemma nat_abs_sign_of_nonzero {z : ℤ} (hz : z ≠ 0) : z.sign.nat_abs = 1 := by rw [int.nat_abs_sign, if_neg hz] lemma sign_coe_nat_of_nonzero {n : ℕ} (hn : n ≠ 0) : int.sign n = 1 := begin obtain ⟨n, rfl⟩ := nat.exists_eq_succ_of_ne_zero hn, exact int.sign_of_succ n end @[simp] lemma sign_neg (z : ℤ) : int.sign (-z) = -int.sign z := by rcases z with (_ | _)| _; refl theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /-! ### to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp]lemma le_to_nat_iff {n : ℕ} {z : ℤ} (h : 0 ≤ z) : n ≤ z.to_nat ↔ (n : ℤ) ≤ z := by rw [←int.coe_nat_le_coe_nat_iff, int.to_nat_of_nonneg h] lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_nat {a : ℤ} (ha : 0 ≤ a) (n : ℕ) : (a + n).to_nat = a.to_nat + n := begin lift a to ℕ using ha, norm_cast, end @[simp] lemma pred_to_nat : ∀ (i : ℤ), (i - 1).to_nat = i.to_nat - 1 | (0:ℕ) := rfl | (n+1:ℕ) := by simp | -[1+ n] := rfl @[simp] lemma to_nat_sub_to_nat_neg : ∀ (n : ℤ), ↑n.to_nat - ↑((-n).to_nat) = n | (0 : ℕ) := rfl | (n+1 : ℕ) := show ↑(n+1) - (0:ℤ) = n+1, from sub_zero _ | -[1+ n] := show 0 - (n+1 : ℤ) = _, from zero_sub _ @[simp] lemma to_nat_add_to_nat_neg_eq_nat_abs : ∀ (n : ℤ), (n.to_nat) + ((-n).to_nat) = n.nat_abs | (0 : ℕ) := rfl | (n+1 : ℕ) := show (n+1) + 0 = n+1, from add_zero _ | -[1+ n] := show 0 + (n+1) = n+1, from zero_add _ /-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`. -/ def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h @[simp] lemma to_nat_neg_nat : ∀ (n : ℕ), (-(n : ℤ)).to_nat = 0 | 0 := rfl | (n + 1) := rfl end int attribute [irreducible] int.nonneg
e2b3ccffd2a144788c2c6053e53c2896215fba16
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/measure_theory/integration.lean
a4588bff434a05c3eceb92b8e5e03ed2b269dc20
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
37,973
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Lebesgue integral on `ennreal`. We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. -/ import algebra.pi_instances measure_theory.measure_space measure_theory.borel_space noncomputable theory open lattice set filter local attribute [instance] classical.prop_decidable section sequence_of_directed variables {α : Type*} {β : Type*} [encodable α] [inhabited α] open encodable noncomputable def sequence_of_directed (r : β → β → Prop) (f : α → β) (hf : directed r f) : ℕ → α | 0 := default α | (n + 1) := let p := sequence_of_directed n in match decode α n with | none := p | (some a) := classical.some (hf p a) end lemma monotone_sequence_of_directed [partial_order β] (f : α → β) (hf : directed (≤) f) : monotone (f ∘ sequence_of_directed (≤) f hf) := monotone_of_monotone_nat $ assume n, begin dsimp [sequence_of_directed], generalize eq : sequence_of_directed (≤) f hf n = p, cases h : decode α n with a, { refl }, { exact (classical.some_spec (hf p a)).1 } end lemma le_sequence_of_directed [partial_order β] (f : α → β) (hf : directed (≤) f) (a : α) : f a ≤ f (sequence_of_directed (≤) f hf (encode a + 1)) := begin simp [sequence_of_directed, -add_comm, encodek], exact (classical.some_spec (hf _ a)).2 end end sequence_of_directed namespace measure_theory variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ @[extensionality] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := by cases f; cases g; congr; exact funext H protected def range (f : α →ₛ β) := f.finite.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b := finite.mem_to_finset def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩ @[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl lemma range_const (α) [measure_space α] [ne : nonempty α] (b : β) : (const α b).range = {b} := begin ext b', simp [mem_range], exact ⟨assume ⟨_, h⟩, h.symm, assume h, ne.elim $ λa, ⟨a, h.symm⟩⟩ end lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} := begin rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}), { exact is_measurable.bUnion (countable_finite f.finite) (λ b _, is_measurable.inter (h b) (f.measurable_sn _)) }, ext a, simp, exact ⟨λ h, ⟨_, ⟨a, rfl⟩, h, rfl⟩, λ ⟨_, ⟨a', rfl⟩, h', e⟩, e.symm ▸ h'⟩ end theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const]) theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, preimage_measurable f s def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨λ a, if a ∈ s then f a else g a, λ x, by letI : measurable_space β := ⊤; exact measurable.if hs f.measurable g.measurable _ trivial, finite_subset (finite_union f.finite g.finite) begin rintro _ ⟨a, rfl⟩, by_cases a ∈ s; simp [h], exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] end⟩ @[simp] theorem ite_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c), finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨_, ⟨a, rfl⟩, _, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then ite hs f (const α 0) else const α 0 @[simp] theorem restrict_apply [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by unfold_coes; simp [restrict, hs]; apply ite_apply hs theorem restrict_preimage [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by ext a; dsimp; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht] def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) @[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := begin ext c, simp [mem_range], split, { rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ }, { rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ } end def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := { add := (+), zero := 0, add_assoc := assume f g h, ext (assume a, add_assoc _ _ _), zero_add := assume f, ext (assume a, zero_add _), add_zero := assume f, ext (assume a, add_zero _) } instance [semiring β] [add_monoid β] : has_scalar β (α →ₛ β) := ⟨λb f, f.map (λa, b * a)⟩ instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice.lattice, .. simple_func.lattice.order_bot, .. simple_func.lattice.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section approx section variables [topological_space β] [semilattice_sup_bot β] [has_zero β] def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [ordered_topology β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf.preimage $ is_measurable_of_is_closed $ is_closed_ge' _) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [ordered_topology β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : _root_.measurable f) (hg : _root_.measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hg.comp hf)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [ordered_topology β] [has_zero β] (i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥): (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox def ennreal_rat_embed (n : ℕ) : ennreal := nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) (hq : 0 ≤ q) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q hq], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : _root_.measurable f) (hg : _root_.measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measure_space α] def integral (f : α →ₛ ennreal) : ennreal := f.range.sum (λ x, x * volume (f ⁻¹' {x})) -- TODO: slow simp proofs lemma map_integral (g : β → ennreal) (f : α →ₛ β) : (f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) := begin simp only [integral, coe_map, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), have : g ∘ ⇑f ⁻¹' {g (f a)} = (⋃b∈s', ⇑f ⁻¹' {b}), { ext a', simp, split, { assume eq, exact ⟨⟨_, rfl⟩, eq⟩ }, { rintros ⟨_, eq⟩, exact eq } }, calc g (f a) * volume (g ∘ ⇑f ⁻¹' {g (f a)}) = g (f a) * volume (⋃b∈s', ⇑f ⁻¹' {b}) : by rw [this] ... = g (f a) * s'.sum (λb, volume (f ⁻¹' {b})) : begin rw [volume_bUnion_finset], { simp [pairwise_on, (on)], rintros b a₀ rfl eq₀ b a₁ rfl eq₁ ne a ⟨h₁, h₂⟩, simp at h₁ h₂, rw [← h₁, h₂] at ne, exact ne rfl }, exact assume a ha, preimage_measurable _ _ end ... = s'.sum (λb, g (f a) * volume (f ⁻¹' {b})) : by rw [finset.mul_sum] ... = s'.sum (λb, g b * volume (f ⁻¹' {b})) : finset.sum_congr rfl $ by simp {contextual := tt} end lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 := begin refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _, assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, exact zero_mul _ end lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral := calc (f + g).integral = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) + (pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral : by rw [map_integral, map_integral] ... = integral f + integral g : rfl lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).integral = x * f.integral := calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) : by rw [map_integral] ... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.integral : finset.mul_sum.symm lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) := begin simp only [mem_range, restrict_apply, hs], split, { rintros ⟨a, ha⟩, split_ifs at ha, { exact or.inr ⟨a, h, ha⟩ }, { exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } }, { rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩), { have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this, rcases not_forall.1 this with ⟨a, ha⟩, refine ⟨a, _⟩, rw [if_neg ha] }, { refine ⟨a, _⟩, rw [if_pos ha] } } end lemma restrict_preimage' {r : ennreal} {s : set α} (f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0): (restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) := begin ext a, by_cases a ∈ s; simp [hs, h, hr.symm] end lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) : (restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { assume r hr, rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩, { simp }, { assume _, exact mem_range.2 ⟨a, rfl⟩ } }, { assume a b _ _ _ _ h, exact h }, { assume r hr, by_cases r0 : r = 0, { simp [r0] }, assume h0, rcases mem_range.1 hr with ⟨a, rfl⟩, have : f ⁻¹' {f a} ∩ s ≠ ∅, { assume h, simpa [h] using h0 }, rcases ne_empty_iff_exists_mem.1 this with ⟨a', eq', ha'⟩, refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩, { simpa using eq' }, { rwa [restrict_preimage' _ hs r0] } }, { assume r hr ne, by_cases r = 0, { simp [h] }, rw [restrict_preimage' _ hs h] } end lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) : (restrict (const α c) s).integral = c * volume s := have (@const α ennreal _ c) ⁻¹' {c} = univ, begin refine eq_univ_of_forall (assume a, _), simp, end, calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) : begin rw [restrict_integral (const α c) s hs], refine finset.sum_eq_single c _ _, { assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction }, { by_cases nonempty α, { assume ne, rcases h with ⟨a⟩, exfalso, exact ne (mem_range.2 ⟨a, rfl⟩) }, { assume empty, have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅, { ext a, exfalso, exact h ⟨a⟩ }, simp only [this, volume_empty, mul_zero] } } end ... = c * volume s : by rw [this, univ_inter] lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral := calc f.integral ⊔ g.integral = ((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl ... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) : begin rw [map_integral, map_integral], refine sup_le _ _; refine finset.sum_le_sum' (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral] lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral := calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left ... ≤ (f ⊔ g).integral : integral_sup_le _ _ ... = g.integral : by rw [sup_of_le_right h] lemma integral_congr (f g : α →ₛ ennreal) (h : {a | f a = g a} ∈ (@measure_space.μ α _).a_e.sets) : f.integral = g.integral := show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from begin rw [map_integral, map_integral], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp [this] } end lemma integral_map {β} [measure_space β] (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (hm : _root_.measurable m) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → volume s = volume (m ⁻¹' s)) : f.integral = g.integral := have f_eq : (f : α → ennreal) = g ∘ m := funext eq, have vol_f : ∀r, volume (f ⁻¹' {r}) = volume (g ⁻¹' {r}), by { assume r, rw [h, f_eq, preimage_comp], exact measurable_sn _ _ }, begin simp [integral, vol_f], refine finset.sum_subset _ _, { simp [finset.subset_iff, f_eq], rintros r a rfl, exact ⟨_, rfl⟩ }, { assume r hrg hrf, rw [simple_func.mem_range, not_exists] at hrf, have : f ⁻¹' {r} = ∅ := set.eq_empty_of_subset_empty (assume a, by simpa using hrf a), simp [(vol_f _).symm, this] } end end measure end simple_func section lintegral open simple_func variable [measure_space α] /-- The lower Lebesgue integral -/ def lintegral (f : α → ennreal) : ennreal := ⨆ (s : α →ₛ ennreal) (hf : f ≥ s), s.integral notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral := le_antisymm (supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs) (le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _) lemma lintegral_le_lintegral (f g : α → ennreal) (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := supr_le_supr $ assume s, supr_le $ assume hs, le_supr_of_le (le_trans hs h) (le_refl _) lemma lintegral_eq_nnreal (f : α → ennreal) : (∫⁻ a, f a) = (⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)), (s.map (coe : nnreal → ennreal)).integral) := begin let c : nnreal → ennreal := coe, refine le_antisymm (supr_le $ assume s, supr_le $ assume hs, _) (supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs), by_cases {a | s a ≠ ⊤} ∈ ((@measure_space.μ α _).a_e).sets, { have : f ≥ (s.map ennreal.to_nnreal).map c := le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs, refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)), exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) }, { have h_vol_s : volume {a : α | s a = ⊤} ≠ 0, { simp [measure.a_e, set.compl_set_of] at h, assumption }, let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}), have n_le_s : ∀i, (n i).map c ≤ s, { assume i a, dsimp [n, c], rw [restrict_apply _ (s.preimage_measurable _)], split_ifs with ha, { simp at ha, exact ha.symm ▸ le_top }, { exact zero_le _ } }, have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)), { assume i, have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp }, rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)], { refine integral_le_integral _ _ (assume a, le_of_eq _), simp [n, c, restrict_apply, s.preimage_measurable], split_ifs; simp [ennreal.coe_nat] }, }, calc s.integral ≤ ⊤ : le_top ... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) : by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s] ... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s ... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral : have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs, (supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) } end /-- Monotone convergence theorem -- somtimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let c : nnreal → ennreal := coe in let F (a:α) := ⨆n, f n a in have hF : measurable F := measurable.supr hf, show (∫⁻ a, F a) = (⨆n, ∫⁻ a, f n a), begin refine le_antisymm _ _, { rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union_left, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) : by rw [← const_mul_integral, integral, eq_rs] ... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr], { assume i, refine is_measurable.inter ((rs.map c).preimage_measurable _) _, refine (hf i).preimage _, exact is_measurable_of_is_closed (is_closed_ge' _) } end) ... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) : begin refine supr_le_supr (assume n, _), rw [restrict_integral _ _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2, ext a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_integral], refine lintegral_le_lintegral _ _ (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end }, { exact supr_le (assume n, lintegral_le_lintegral _ _ $ assume a, le_supr _ n) } end lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a) = (⨆n, (eapprox f n).integral) := calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) := calc (∫⁻ a, f a + g a) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl }, { assume n, exact measurable_add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) } ... = (∫⁻ a, f a) + (∫⁻ a, g a) : by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg] @[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 := show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, s.sum (λb, f b a)) = s.sum (λb, ∫⁻ a, f b a) := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp [has], rw [lintegral_add (hf _) (measurable_finset_sum s hf), ih] } end lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) : by congr; funext a; rw [← supr_eapprox_apply f hf, ennreal.mul_supr]; refl ... = (⨆n, r * (eapprox f n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf] lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) : (∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s := begin rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral], congr; ext a; by_cases a ∈ s; simp [h, hs] end lemma lintegral_le_lintegral_ae {f g : α → ennreal} (h : ∀ₘ a, f a ≤ g a) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : - t ∈ (@measure_space.μ α _).a_e.sets, { rw [measure.mem_a_e_iff, lattice.neg_neg, ht0] }, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict (- t)) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, simple_func.restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (s.integral_congr _ _), filter_upwards [this], refine assume a hnt, _, by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : ∀ₘ a, f a = g a) : (∫⁻ a, f a) = (∫⁻ a, g a) := le_antisymm (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h) (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h.symm) lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : lintegral f = 0 ↔ (∀ₘ a, f a = 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ₘ a, f a < n⁻¹, { assume n, have : is_measurable {a : α | f a ≥ n⁻¹ }, { exact hf _ (is_measurable_of_is_closed $ is_closed_ge' _) }, have : (n : ennreal)⁻¹ * volume {a | f a ≥ n⁻¹ } = 0, { rw [← simple_func.restrict_const_integral _ _ this, ← le_zero_iff_eq, ← simple_func.lintegral_eq_integral], refine le_trans (lintegral_le_lintegral _ _ _) (le_of_eq h), assume a, by_cases h : (n : ennreal)⁻¹ ≤ f a; simp [h, (≥), this] }, rw [ennreal.mul_eq_zero, ennreal.inv_eq_zero] at this, simpa [ennreal.nat_ne_top, all_ae_iff] using this }, filter_upwards [all_ae_all_iff.2 this], dsimp, assume a ha, by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc lintegral f = lintegral (λa:α, 0) : lintegral_congr_ae h ... = 0 : lintegral_zero } end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : (∫⁻ a, ⨆b, f b a) = (⨆b, ∫⁻ a, f b a) := begin by_cases hβ : ¬ nonempty β, { have : ∀f : β → ennreal, (⨆(b : β), f b) = 0 := assume f, supr_eq_bot.2 (assume b, (hβ ⟨b⟩).elim), simp [this] }, cases of_not_not hβ with b, haveI iβ : inhabited β := ⟨b⟩, clear hβ b, have : ∀a, (⨆ b, f b a) = (⨆ n, f (sequence_of_directed (≤) f h_directed n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (le_sequence_of_directed f h_directed b a) }, calc (∫⁻ a, ⨆ b, f b a) = (∫⁻ a, ⨆ n, f (sequence_of_directed (≤) f h_directed n) a) : by simp only [this] ... = (⨆ n, ∫⁻ a, f (sequence_of_directed (≤) f h_directed n) a) : lintegral_supr (assume n, hf _) (monotone_sequence_of_directed f h_directed) ... = (⨆ b, ∫⁻ a, f b a) : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, lintegral (f b)) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_le_lintegral _ _ $ le_sequence_of_directed f h_directed b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : (∫⁻ a, ∑ i, f i a) = (∑ i, ∫⁻ a, f i a) := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact measurable_finset_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end end lintegral namespace measure def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal := @lintegral α { μ := m } f variables [measurable_space α] {m : measure α} @[simp] lemma integral_zero : m.integral (λa, 0) = 0 := @lintegral_zero α { μ := m } lemma integral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : (map g m).integral f = m.integral (f ∘ g) := begin rw [integral, integral, lintegral_eq_supr_eapprox_integral, lintegral_eq_supr_eapprox_integral], { congr, funext n, symmetry, apply simple_func.integral_map, { exact hg }, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, exact hg.comp hf, assumption end lemma integral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : (dirac a).integral f = f a := have ∀f:α →ₛ ennreal, @simple_func.integral α {μ := dirac a} f = f a, begin assume f, have : ∀r, @volume α { μ := dirac a } (⇑f ⁻¹' {r}) = ⨆ h : f a = r, 1, { assume r, transitivity, apply dirac_apply, apply simple_func.measurable_sn, refine supr_congr_Prop _ _; simp }, transitivity, apply finset.sum_eq_single (f a), { assume b hb h, simp [this, ne.symm h], }, { assume h, simp at h, exact (h a rfl).elim }, { rw [this], simp } end, begin rw [integral, lintegral_eq_supr_eapprox_integral], { simp [this, simple_func.supr_eapprox_apply f hf] }, assumption end def with_density (m : measure α) (f : α → ennreal) : measure α := if hf : measurable f then measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a)) (by simp) begin assume s hs hd, have : ∀a, (⨆ (h : a ∈ ⋃i, s i), f a) = (∑i, (⨆ (h : a ∈ s i), f a)), { assume a, by_cases ha : ∃j, a ∈ s j, { rcases ha with ⟨j, haj⟩, have : ∀i, a ∈ s i ↔ j = i := assume i, iff.intro (assume hai, by_contradiction $ assume hij, hd j i hij ⟨haj, hai⟩) (by rintros rfl; assumption), simp [this, ennreal.tsum_supr_eq] }, { have : ∀i, ¬ a ∈ s i, { simpa using ha }, simp [this] } }, simp only [this], apply lintegral_tsum, { assume i, simp [supr_eq_if], exact measurable.if (hs i) hf measurable_const } end else 0 lemma with_density_apply {m : measure α} {f : α → ennreal} {s : set α} (hf : measurable f) (hs : is_measurable s) : m.with_density f s = m.integral (λa, ⨆(h : a ∈ s), f a) := by rw [with_density, dif_pos hf]; exact measure.of_measurable_apply s hs end measure end measure_theory
a47b6d1df9a7bb633a5f9464371952bfbbdf8182
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/Subst.lean
2e7b6f32563be906ff91c25a9d8222dc6560e5ae
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
8,376
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.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean.Meta def substCore (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) (tryToSkip := false) : MetaM (FVarSubst × MVarId) := withMVarContext mvarId do let tag ← getMVarTag mvarId checkNotAssigned mvarId `subst let hFVarIdOriginal := hFVarId let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => throwTacticEx `subst mvarId "argument must be an equality proof" | some (α, lhs, rhs) => do let a ← instantiateMVars <| if symm then rhs else lhs let b ← instantiateMVars <| if symm then lhs else rhs match a with | Expr.fvar aFVarId _ => do let aFVarIdOriginal := aFVarId trace[Meta.Tactic.subst] "substituting {a} (id: {aFVarId.name}) with {b}" let mctx ← getMCtx if mctx.exprDependsOn b aFVarId then throwTacticEx `subst mvarId m!"'{a}' occurs at{indentExpr b}" let aLocalDecl ← getLocalDecl aFVarId let (vars, mvarId) ← revert mvarId #[aFVarId, hFVarId] true trace[Meta.Tactic.subst] "after revert {MessageData.ofGoal mvarId}" let (twoVars, mvarId) ← introNP mvarId 2 trace[Meta.Tactic.subst] "after intro2 {MessageData.ofGoal mvarId}" trace[Meta.Tactic.subst] "reverted variables {vars.map (·.name)}" let aFVarId := twoVars[0] let a := mkFVar aFVarId let hFVarId := twoVars[1] let h := mkFVar hFVarId /- Set skip to true if there is no local variable nor the target depend on the equality -/ let skip ← if !tryToSkip || vars.size != 2 then pure false else let mvarType ← getMVarType mvarId let mctx ← getMCtx pure (!mctx.exprDependsOn mvarType aFVarId && !mctx.exprDependsOn mvarType hFVarId) if skip then if clearH then let mvarId ← clear mvarId hFVarId let mvarId ← clear mvarId aFVarId pure ({}, mvarId) else pure ({}, mvarId) else withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId let type := mvarDecl.type let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => unreachable! | some (α, lhs, rhs) => do let b ← instantiateMVars <| if symm then lhs else rhs let mctx ← getMCtx let depElim := mctx.exprDependsOn mvarDecl.type hFVarId let cont (motive : Expr) (newType : Expr) : MetaM (FVarSubst × MVarId) := do let major ← if symm then pure h else mkEqSymm h let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let minor := newMVar let newVal ← if depElim then mkEqRec motive minor major else mkEqNDRec motive minor major assignExprMVar mvarId newVal let mvarId := newMVar.mvarId! let mvarId ← if clearH then let mvarId ← clear mvarId hFVarId clear mvarId aFVarId else pure mvarId let (newFVars, mvarId) ← introNP mvarId (vars.size - 2) trace[Meta.Tactic.subst] "after intro rest {vars.size - 2} {MessageData.ofGoal mvarId}" let fvarSubst ← newFVars.size.foldM (init := fvarSubst) fun i (fvarSubst : FVarSubst) => let var := vars[i+2] let newFVar := newFVars[i] pure $ fvarSubst.insert var (mkFVar newFVar) let fvarSubst := fvarSubst.insert aFVarIdOriginal (if clearH then b else mkFVar aFVarId) let fvarSubst := fvarSubst.insert hFVarIdOriginal (mkFVar hFVarId) pure (fvarSubst, mvarId) if depElim then do let newType := type.replaceFVar a b let reflB ← mkEqRefl b let newType := newType.replaceFVar h reflB if symm then let motive ← mkLambdaFVars #[a, h] type cont motive newType else /- `type` depends on (h : a = b). So, we use the following trick to avoid a type incorrect motive. 1- Create a new local (hAux : b = a) 2- Create newType := type [hAux.symm / h] `newType` is type correct because `h` and `hAux.symm` are definitionally equal by proof irrelevance. 3- Create motive by abstracting `a` and `hAux` in `newType`. -/ let hAuxType ← mkEq b a let motive ← withLocalDeclD `_h hAuxType fun hAux => do let hAuxSymm ← mkEqSymm hAux /- replace h in type with hAuxSymm -/ let newType := type.replaceFVar h hAuxSymm mkLambdaFVars #[a, hAux] newType cont motive newType else let motive ← mkLambdaFVars #[a] type let newType := type.replaceFVar a b cont motive newType | _ => let eqMsg := if symm then "(t = x)" else "(x = t)" throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form {eqMsg}{indentExpr hLocalDecl.type}\nafter WHNF, variable expected, but obtained{indentExpr a}" def subst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := withMVarContext mvarId do let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | some (α, lhs, rhs) => let substReduced (newType : Expr) (symm : Bool) : MetaM MVarId := do let mvarId ← assert mvarId hLocalDecl.userName newType (mkFVar hFVarId) let (hFVarId', mvarId) ← intro1P mvarId let mvarId ← clear mvarId hFVarId return (← substCore mvarId hFVarId' (symm := symm) (tryToSkip := true)).2 let rhs' ← whnf rhs if rhs'.isFVar then if rhs != rhs' then substReduced (← mkEq lhs rhs') true else return (← substCore mvarId hFVarId (symm := true) (tryToSkip := true)).2 else do let lhs' ← whnf lhs if lhs'.isFVar then if lhs != lhs' then substReduced (← mkEq lhs' rhs) false else return (← substCore mvarId hFVarId (symm := false) (tryToSkip := true)).2 else do throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form (x = t) or (t = x){indentExpr hLocalDecl.type}" | none => if hLocalDecl.isLet then throwTacticEx `subst mvarId m!"variable '{mkFVar hFVarId}' is a let-declaration" let mctx ← getMCtx let lctx ← getLCtx let some (fvarId, symm) ← lctx.findDeclM? fun localDecl => do if localDecl.isAuxDecl then return none else match (← matchEq? localDecl.type) with | some (α, lhs, rhs) => if rhs.isFVar && rhs.fvarId! == hFVarId && !mctx.exprDependsOn lhs hFVarId then return some (localDecl.fvarId, true) else if lhs.isFVar && lhs.fvarId! == hFVarId && !mctx.exprDependsOn rhs hFVarId then return some (localDecl.fvarId, false) else return none | _ => return none | throwTacticEx `subst mvarId m!"did not find equation for eliminating '{mkFVar hFVarId}'" return (← substCore mvarId fvarId (symm := symm) (tryToSkip := true)).2 def trySubst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := do match (← observing? (subst mvarId hFVarId)) with | some mvarId => return mvarId | none => return mvarId builtin_initialize registerTraceClass `Meta.Tactic.subst end Meta end Lean
6af14541c2afd40cd17f5c0d36184250e00cfc0f
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/measure_theory/borel_space.lean
cbe64c5a052595c5ecbcba858fe75600d291afb7
[ "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
29,479
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, Yury Kudryashov -/ import measure_theory.measurable_space import topology.instances.ennreal import analysis.normed_space.basic /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ennreal`. ## Main statements * `is_open.is_measurable`, `is_closed.is_measurable`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `measurable.ennreal*` : special cases for arithmetic operations on `ennreal`s. -/ noncomputable theory open classical set open_locale classical big_operators universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply is_measurable.bUnion s.countable_encodable, intros x hx, apply is_measurable.of_compl, apply generate_measurable.basic, exact is_closed_singleton end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @is_measurable.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @is_measurable.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @is_measurable.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma borel_eq_generate_Iio (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Ioi) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H}, by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a', { rcases h with ⟨a', ha'⟩, rw (_ : Iio a = (Ioi a')ᶜ), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a' < a}, {b | b < a'.1}) (λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Iio a = ⋃ x : v, (Ioi x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), λ h, lt_of_le_of_lt h ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ (is_open_lt' _) } end lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hf s hs) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma is_open.is_measurable (h : is_open s) : is_measurable s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h lemma is_measurable_interior : is_measurable (interior s) := is_open_interior.is_measurable lemma is_closed.is_measurable (h : is_closed s) : is_measurable s := is_measurable.compl_iff.1 $ h.is_measurable lemma is_compact.is_measurable [t2_space α] (h : is_compact s) : is_measurable s := h.is_closed.is_measurable lemma is_measurable_closure : is_measurable (closure s) := is_closed_closure.is_measurable @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.is_measurable⟩ section order_closed_topology variables [preorder α] [order_closed_topology α] {a b : α} lemma is_measurable_Ici : is_measurable (Ici a) := is_closed_Ici.is_measurable lemma is_measurable_Iic : is_measurable (Iic a) := is_closed_Iic.is_measurable lemma is_measurable_Icc : is_measurable (Icc a b) := is_closed_Icc.is_measurable end order_closed_topology section order_closed_topology variables [linear_order α] [order_closed_topology α] {a b : α} lemma is_measurable_Iio : is_measurable (Iio a) := is_open_Iio.is_measurable lemma is_measurable_Ioi : is_measurable (Ioi a) := is_open_Ioi.is_measurable lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_open_Ioo.is_measurable lemma is_measurable_Ioc : is_measurable (Ioc a b) := is_measurable_Ioi.inter is_measurable_Iic lemma is_measurable_Ico : is_measurable (Ico a b) := is_measurable_Ici.inter is_measurable_Iio end order_closed_topology lemma is_measurable_interval [decidable_linear_order α] [order_closed_topology α] {a b : α} : is_measurable (interval a b) := is_measurable_Icc instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin refine ⟨_⟩, rcases is_open_generated_countable_inter α with ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩, rcases is_open_generated_countable_inter β with ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩, have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v}, { rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨u, hu, v, hv, rfl⟩, have hu : is_open u, by { rw [ha₅], exact generate_open.basic _ hu }, have hv : is_open v, by { rw [hb₅], exact generate_open.basic _ hv }, exact hu.is_measurable.prod hv.is_measurable end /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv {α : Type*} {β : Type*} [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] (h : α ≃ₜ β) : measurable_equiv α β := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {x | x ≠ a}) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λp:α×β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λa, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma measurable.smul [semiring α] [second_countable_topology α] [add_comm_monoid γ] [second_countable_topology γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → α} {g : δ → γ} (hf : measurable f) (hg : measurable g) : measurable (λ c, f c • g c) := continuous_smul.measurable2 hf hg lemma measurable.const_smul {α : Type*} [topological_space α] [semiring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} (hf : measurable f) (c : α) : measurable (λ x, c • f x) := (continuous_const.smul continuous_id).measurable.comp hf lemma measurable_const_smul_iff {α : Type*} [topological_space α] [division_ring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} {c : α} (hc : c ≠ 0) : measurable (λ x, c • f x) ↔ measurable f := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.const_smul c⁻¹, λ h, h.const_smul c⟩ lemma is_measurable_le' [partial_order α] [order_closed_topology α] [second_countable_topology α] : is_measurable {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.is_measurable lemma is_measurable_le [partial_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : is_measurable {a | f a ≤ g a} := hf.prod_mk hg is_measurable_le' lemma measurable.max [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, max (f a) (g a)) := hg.piecewise (is_measurable_le hf hg) hf lemma measurable.min [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, min (f a) (g a)) := hf.piecewise (is_measurable_le hf hg) hg end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ @[to_additive] lemma measurable_mul [monoid α] [has_continuous_mul α] [second_countable_topology α] : measurable (λ p : α × α, p.1 * p.2) := continuous_mul.measurable @[to_additive] lemma measurable.mul [monoid α] [has_continuous_mul α] [second_countable_topology α] {f : δ → α} {g : δ → α} : measurable f → measurable g → measurable (λa, f a * g a) := continuous_mul.measurable2 @[to_additive] lemma finset.measurable_prod {ι : Type*} [comm_monoid α] [has_continuous_mul α] [second_countable_topology α] {f : ι → δ → α} (s : finset ι) (hf : ∀i, measurable (f i)) : measurable (λa, ∏ i in s, f i a) := finset.induction_on s (by simp only [finset.prod_empty, measurable_const]) (assume i s his ih, by simpa [his] using (hf i).mul ih) @[to_additive] lemma measurable_inv [group α] [topological_group α] : measurable (has_inv.inv : α → α) := continuous_inv.measurable @[to_additive] lemma measurable.inv [group α] [topological_group α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv.comp hf lemma measurable_inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] : measurable (has_inv.inv : α → α) := measurable_of_continuous_on_compl_singleton 0 normed_field.continuous_on_inv lemma measurable.inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv'.comp hf @[to_additive] lemma measurable.of_inv [group α] [topological_group α] {f : δ → α} (hf : measurable (λ a, (f a)⁻¹)) : measurable f := by simpa only [inv_inv] using hf.inv @[simp, to_additive] lemma measurable_inv_iff [group α] [topological_group α] {f : δ → α} : measurable (λ a, (f a)⁻¹) ↔ measurable f := ⟨measurable.of_inv, measurable.inv⟩ lemma measurable.sub [add_group α] [topological_add_group α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x - g x) := hf.add hg.neg lemma measurable.is_lub [linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp only [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i (is_open_lt' _).is_measurable) end lemma measurable.is_glb [linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp only [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i (is_open_gt' _).is_measurable) end lemma measurable_supr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr lemma measurable_infi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) lemma measurable_bsupr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i (hi : p i), f i b) := measurable_supr $ λ i, (hf i).supr_Prop (p i) lemma measurable_binfi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i (hi : p i), f i b) := measurable_infi $ λ i, (hf i).infi_Prop (p i) /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : measurable_equiv α β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space nnreal := borel nnreal instance nnreal.borel_space : borel_space nnreal := ⟨rfl⟩ instance ennreal.measurable_space : measurable_space ennreal := borel ennreal instance ennreal.borel_space : borel_space ennreal := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ℝ} lemma is_measurable_ball : is_measurable (metric.ball x ε) := metric.is_open_ball.is_measurable lemma is_measurable_closed_ball : is_measurable (metric.closed_ball x ε) := metric.is_closed_ball.is_measurable lemma measurable_dist [second_countable_topology α] : measurable (λp:α×α, dist p.1 p.2) := continuous_dist.measurable lemma measurable.dist [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := continuous_dist.measurable2 hf hg lemma measurable_nndist [second_countable_topology α] : measurable (λp:α×α, nndist p.1 p.2) := continuous_nndist.measurable lemma measurable.nndist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, nndist (f b) (g b)) := continuous_nndist.measurable2 end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ennreal} lemma is_measurable_eball : is_measurable (emetric.ball x ε) := emetric.is_open_ball.is_measurable lemma measurable_edist [second_countable_topology α] : measurable (λp:α×α, edist p.1 p.2) := continuous_edist.measurable lemma measurable.edist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, edist (f b) (g b)) := continuous_edist.measurable2 end emetric_space namespace real open measurable_space lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2 lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃a:ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, H⟩, rw [mem_singleton_iff.1 H], rw (set.ext (λ x, _) : Ioo (a:ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀q:ℚ, g.is_measurable (Iio q) := λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩), refine @is_measurable.inter _ g _ _ _ (hg _), refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @is_measurable.compl _ _ g (hg _) }, { simp [Ioo, Iio], refine and_congr _ iff.rfl, exact ⟨λ h, let ⟨c, ac, cx⟩ := exists_rat_btwn h in ⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩, λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } }, { simp, rintro r rfl, exact is_open_Iio.is_measurable } end end real lemma measurable.sub_nnreal [measurable_space α] {f g : α → nnreal} : measurable f → measurable g → measurable (λ a, f a - g a) := nnreal.continuous_sub.measurable2 lemma measurable.nnreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, nnreal.of_real (f x)) := nnreal.continuous_of_real.measurable.comp hf lemma measurable.nnreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := nnreal.continuous_coe.measurable.comp hf lemma measurable.ennreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ennreal)) := (ennreal.continuous_coe.2 continuous_id).measurable.comp hf lemma measurable.ennreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ennreal` numbers is `measurable_equiv` to `nnreal`. -/ def measurable_equiv.ennreal_equiv_nnreal : measurable_equiv {r : ennreal | r ≠ ⊤} nnreal := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal open filter lemma measurable_coe : measurable (coe : nnreal → ennreal) := measurable_id.ennreal_coe lemma measurable_of_measurable_nnreal [measurable_space α] {f : ennreal → α} (h : measurable (λp:nnreal, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ⊤ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ennreal` is `measurable_equiv` to `nnreal ⊕ unit`. -/ def ennreal_equiv_sum : measurable_equiv ennreal (nnreal ⊕ unit) := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe (@measurable_const ennreal unit _ _ ⊤), .. equiv.option_equiv_sum_punit nnreal } lemma measurable_of_measurable_nnreal_nnreal [measurable_space α] [measurable_space β] (f : ennreal → ennreal → β) {g : α → ennreal} {h : α → ennreal} (h₁ : measurable (λp:nnreal × nnreal, f p.1 p.2)) (h₂ : measurable (λr:nnreal, f ⊤ r)) (h₃ : measurable (λr:nnreal, f r ⊤)) (hg : measurable g) (hh : measurable h) : measurable (λa, f (g a) (h a)) := let e : measurable_equiv (ennreal × ennreal) (((nnreal × nnreal) ⊕ (nnreal × unit)) ⊕ ((unit × nnreal) ⊕ (unit × unit))) := (measurable_equiv.prod_congr ennreal_equiv_sum ennreal_equiv_sum).trans (measurable_equiv.sum_prod_sum _ _ _ _) in have measurable (λp:ennreal×ennreal, f p.1 p.2), begin refine e.symm.measurable_coe_iff.1 (measurable_sum (measurable_sum _ _) (measurable_sum _ _)), { show measurable (λp:nnreal × nnreal, f p.1 p.2), exact h₁ }, { show measurable (λp:nnreal × unit, f p.1 ⊤), exact h₃.comp (measurable.fst measurable_id) }, { show measurable ((λp:nnreal, f ⊤ p) ∘ (λp:unit × nnreal, p.2)), exact h₂.comp (measurable.snd measurable_id) }, { show measurable (λp:unit × unit, f ⊤ ⊤), exact measurable_const } end, this.comp (measurable.prod_mk hg hh) lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable end ennreal lemma measurable.ennreal_mul {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a * g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (*) _ _ _, { simp only [ennreal.coe_mul.symm], exact ennreal.measurable_coe.comp measurable_mul }, { simp [ennreal.top_mul], exact measurable_const.piecewise (is_closed_eq continuous_id continuous_const).is_measurable measurable_const }, { simp [ennreal.mul_top], exact measurable_const.piecewise (is_closed_eq continuous_id continuous_const).is_measurable measurable_const } end lemma measurable.ennreal_add {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a + g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (+) _ _ _, { simp only [ennreal.coe_add.symm], exact ennreal.measurable_coe.comp measurable_add }, { simp [measurable_const] }, { simp [measurable_const] } end lemma measurable.ennreal_sub {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a - g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (has_sub.sub) _ _ _, { simp only [ennreal.coe_sub.symm], exact ennreal.measurable_coe.comp nnreal.continuous_sub.measurable }, { simp [measurable_const] }, { simp [measurable_const] } end section normed_group variables [measurable_space α] [normed_group α] [opens_measurable_space α] [measurable_space β] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λa, norm (f a)) := measurable_norm.comp hf lemma measurable_nnnorm : measurable (nnnorm : α → nnreal) := continuous_nnnorm.measurable lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λa, nnnorm (f a)) := measurable_nnnorm.comp hf lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λa, (nnnorm (f a) : ennreal)) := hf.nnnorm.ennreal_coe end normed_group
f128a7a74a902bee1153059814b5e0cf5048c08b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/dfinsupp.lean
225d7c9c707567a9fffa6659f8290a4ed54ecf4d
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
19,841
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import data.finsupp.to_dfinsupp import linear_algebra.basis /-! # Properties of the module `Π₀ i, M i` Given an indexed collection of `R`-modules `M i`, the `R`-module structure on `Π₀ i, M i` is defined in `data.dfinsupp`. In this file we define `linear_map` versions of various maps: * `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map; * `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map; * `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`; ## Implementation notes This file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is much more developed, but many lemmas in that file should be eligible to copy over. ## Tags function with finite support, module, linear algebra -/ variables {ι : Type*} {R : Type*} {S : Type*} {M : ι → Type*} {N : Type*} variables [dec_ι : decidable_eq ι] namespace dfinsupp variables [semiring R] [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] variables [add_comm_monoid N] [module R N] include dec_ι /-- `dfinsupp.mk` as a `linear_map`. -/ def lmk (s : finset ι) : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i := { to_fun := mk s, map_add' := λ _ _, mk_add, map_smul' := λ c x, mk_smul c x} /-- `dfinsupp.single` as a `linear_map` -/ def lsingle (i) : M i →ₗ[R] Π₀ i, M i := { to_fun := single i, map_smul' := single_smul, .. dfinsupp.single_add_hom _ _ } /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄ (h : ∀ i x, φ (single i x) = ψ (single i x)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. See note [partially-applied ext lemmas]. After apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄ (h : ∀ i, φ.comp (lsingle i) = ψ.comp (lsingle i)) : φ = ψ := lhom_ext $ λ i, linear_map.congr_fun (h i) omit dec_ι /-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/ def lapply (i : ι) : (Π₀ i, M i) →ₗ[R] M i := { to_fun := λ f, f i, map_add' := λ f g, add_apply f g i, map_smul' := λ c f, smul_apply c f i} include dec_ι @[simp] lemma lmk_apply (s : finset ι) (x) : (lmk s : _ →ₗ[R] Π₀ i, M i) x = mk s x := rfl @[simp] lemma lsingle_apply (i : ι) (x : M i) : (lsingle i : _ →ₗ[R] _) x = single i x := rfl omit dec_ι @[simp] lemma lapply_apply (i : ι) (f : Π₀ i, M i) : (lapply i : _ →ₗ[R] _) f = f i := rfl section lsum /-- Typeclass inference can't find `dfinsupp.add_comm_monoid` without help for this case. This instance allows it to be found where it is needed on the LHS of the colon in `dfinsupp.module_of_linear_map`. -/ instance add_comm_monoid_of_linear_map : add_comm_monoid (Π₀ (i : ι), M i →ₗ[R] N) := @dfinsupp.add_comm_monoid _ (λ i, M i →ₗ[R] N) _ /-- Typeclass inference can't find `dfinsupp.module` without help for this case. This is needed to define `dfinsupp.lsum` below. The cause seems to be an inability to unify the `Π i, add_comm_monoid (M i →ₗ[R] N)` instance that we have with the `Π i, has_zero (M i →ₗ[R] N)` instance which appears as a parameter to the `dfinsupp` type. -/ instance module_of_linear_map [semiring S] [module S N] [smul_comm_class R S N] : module S (Π₀ (i : ι), M i →ₗ[R] N) := @dfinsupp.module _ _ (λ i, M i →ₗ[R] N) _ _ _ variables (S) include dec_ι /-- The `dfinsupp` version of `finsupp.lsum`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def lsum [semiring S] [module S N] [smul_comm_class R S N] : (Π i, M i →ₗ[R] N) ≃ₗ[S] ((Π₀ i, M i) →ₗ[R] N) := { to_fun := λ F, { to_fun := sum_add_hom (λ i, (F i).to_add_monoid_hom), map_add' := (lift_add_hom (λ i, (F i).to_add_monoid_hom)).map_add, map_smul' := λ c f, by { dsimp, apply dfinsupp.induction f, { rw [smul_zero, add_monoid_hom.map_zero, smul_zero] }, { intros a b f ha hb hf, rw [smul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, smul_add, hf, ←single_smul, sum_add_hom_single, sum_add_hom_single, linear_map.to_add_monoid_hom_coe, linear_map.map_smul], } } }, inv_fun := λ F i, F.comp (lsingle i), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ c F, by { ext, simp } } /-- While `simp` can prove this, it is often convenient to avoid unfolding `lsum` into `sum_add_hom` with `dfinsupp.lsum_apply_apply`. -/ lemma lsum_single [semiring S] [module S N] [smul_comm_class R S N] (F : Π i, M i →ₗ[R] N) (i) (x : M i) : lsum S F (single i x) = F i x := sum_add_hom_single _ _ _ end lsum /-! ### Bundled versions of `dfinsupp.map_range` The names should match the equivalent bundled `finsupp.map_range` definitions. -/ section map_range variables {β β₁ β₂: ι → Type*} variables [Π i, add_comm_monoid (β i)] [Π i, add_comm_monoid (β₁ i)] [Π i, add_comm_monoid (β₂ i)] variables [Π i, module R (β i)] [Π i, module R (β₁ i)] [Π i, module R (β₂ i)] lemma map_range_smul (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (r : R) (hf' : ∀ i x, f i (r • x) = r • f i x) (g : Π₀ i, β₁ i): map_range f hf (r • g) = r • map_range f hf g := begin ext, simp only [map_range_apply f, coe_smul, pi.smul_apply, hf'] end /-- `dfinsupp.map_range` as an `linear_map`. -/ @[simps apply] def map_range.linear_map (f : Π i, β₁ i →ₗ[R] β₂ i) : (Π₀ i, β₁ i) →ₗ[R] (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, f i x) (λ i, (f i).map_zero), map_smul' := λ r, map_range_smul _ _ _ (λ i, (f i).map_smul r), .. map_range.add_monoid_hom (λ i, (f i).to_add_monoid_hom) } @[simp] lemma map_range.linear_map_id : map_range.linear_map (λ i, (linear_map.id : (β₂ i) →ₗ[R] _)) = linear_map.id := linear_map.ext map_range_id lemma map_range.linear_map_comp (f : Π i, β₁ i →ₗ[R] β₂ i) (f₂ : Π i, β i →ₗ[R] β₁ i): map_range.linear_map (λ i, (f i).comp (f₂ i)) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp (λ i x, f i x) (λ i x, f₂ i x) _ _ _ include dec_ι lemma sum_map_range_index.linear_map [Π (i : ι) (x : β₁ i), decidable (x ≠ 0)] [Π (i : ι) (x : β₂ i), decidable (x ≠ 0)] {f : Π i, β₁ i →ₗ[R] β₂ i} {h : Π i, β₂ i →ₗ[R] N} {l : Π₀ i, β₁ i} : dfinsupp.lsum ℕ h (map_range.linear_map f l) = dfinsupp.lsum ℕ (λ i, (h i).comp (f i)) l := by simpa [dfinsupp.sum_add_hom_apply] using @sum_map_range_index ι N _ _ _ _ _ _ _ _ (λ i, f i) (λ i, by simp) l (λ i, h i) (λ i, by simp) omit dec_ι /-- `dfinsupp.map_range.linear_map` as an `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (Π₀ i, β₁ i) ≃ₗ[R] (Π₀ i, β₂ i) := { to_fun := map_range (λ i x, e i x) (λ i, (e i).map_zero), inv_fun := map_range (λ i x, (e i).symm x) (λ i, (e i).symm.map_zero), .. map_range.add_equiv (λ i, (e i).to_add_equiv), .. map_range.linear_map (λ i, (e i).to_linear_map) } @[simp] lemma map_range.linear_equiv_refl : (map_range.linear_equiv $ λ i, linear_equiv.refl R (β₁ i)) = linear_equiv.refl _ _ := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : Π i, β i ≃ₗ[R] β₁ i) (f₂ : Π i, β₁ i ≃ₗ[R] β₂ i): map_range.linear_equiv (λ i, (f i).trans (f₂ i)) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp (λ i x, f₂ i x) (λ i x, f i x) _ _ _ @[simp] lemma map_range.linear_equiv_symm (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (map_range.linear_equiv e).symm = map_range.linear_equiv (λ i, (e i).symm) := rfl end map_range section basis /-- The direct sum of free modules is free. Note that while this is stated for `dfinsupp` not `direct_sum`, the types are defeq. -/ noncomputable def basis {η : ι → Type*} (b : Π i, basis (η i) R (M i)) : basis (Σ i, η i) R (Π₀ i, M i) := basis.of_repr ((map_range.linear_equiv (λ i, (b i).repr)).trans (sigma_finsupp_lequiv_dfinsupp R).symm) end basis end dfinsupp include dec_ι namespace submodule variables [semiring R] [add_comm_monoid N] [module R N] open dfinsupp lemma dfinsupp_sum_mem {β : ι → Type*} [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] (S : submodule R N) (f : Π₀ i, β i) (g : Π i, β i → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S := dfinsupp_sum_mem S f g h lemma dfinsupp_sum_add_hom_mem {β : ι → Type*} [Π i, add_zero_class (β i)] (S : submodule R N) (f : Π₀ i, β i) (g : Π i, β i →+ N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : dfinsupp.sum_add_hom g f ∈ S := dfinsupp_sum_add_hom_mem S f g h /-- The supremum of a family of submodules is equal to the range of `dfinsupp.lsum`; that is every element in the `supr` can be produced from taking a finite number of non-zero elements of `p i`, coercing them to `N`, and summing them. -/ lemma supr_eq_range_dfinsupp_lsum (p : ι → submodule R N) : supr p = (dfinsupp.lsum ℕ (λ i, (p i).subtype)).range := begin apply le_antisymm, { apply supr_le _, intros i y hy, exact ⟨dfinsupp.single i ⟨y, hy⟩, dfinsupp.sum_add_hom_single _ _ _⟩, }, { rintros x ⟨v, rfl⟩, exact dfinsupp_sum_add_hom_mem _ v _ (λ i _, (le_supr p i : p i ≤ _) (v i).prop) } end /-- The bounded supremum of a family of commutative additive submonoids is equal to the range of `dfinsupp.sum_add_hom` composed with `dfinsupp.filter_add_monoid_hom`; that is, every element in the bounded `supr` can be produced from taking a finite number of non-zero elements from the `S i` that satisfy `p i`, coercing them to `γ`, and summing them. -/ lemma bsupr_eq_range_dfinsupp_lsum (p : ι → Prop) [decidable_pred p] (S : ι → submodule R N) : (⨆ i (h : p i), S i) = ((dfinsupp.lsum ℕ (λ i, (S i).subtype)).comp (dfinsupp.filter_linear_map R _ p)).range := begin apply le_antisymm, { refine supr₂_le (λ i hi y hy, ⟨dfinsupp.single i ⟨y, hy⟩, _⟩), rw [linear_map.comp_apply, filter_linear_map_apply, filter_single_pos _ _ hi], exact dfinsupp.sum_add_hom_single _ _ _, }, { rintros x ⟨v, rfl⟩, refine dfinsupp_sum_add_hom_mem _ _ _ (λ i hi, _), refine mem_supr_of_mem i _, by_cases hp : p i, { simp [hp], }, { simp [hp] }, } end lemma mem_supr_iff_exists_dfinsupp (p : ι → submodule R N) (x : N) : x ∈ supr p ↔ ∃ f : Π₀ i, p i, dfinsupp.lsum ℕ (λ i, (p i).subtype) f = x := set_like.ext_iff.mp (supr_eq_range_dfinsupp_lsum p) x /-- A variant of `submodule.mem_supr_iff_exists_dfinsupp` with the RHS fully unfolded. -/ lemma mem_supr_iff_exists_dfinsupp' (p : ι → submodule R N) [Π i (x : p i), decidable (x ≠ 0)] (x : N) : x ∈ supr p ↔ ∃ f : Π₀ i, p i, f.sum (λ i xi, ↑xi) = x := begin rw mem_supr_iff_exists_dfinsupp, simp_rw [dfinsupp.lsum_apply_apply, dfinsupp.sum_add_hom_apply], congr', end lemma mem_bsupr_iff_exists_dfinsupp (p : ι → Prop) [decidable_pred p] (S : ι → submodule R N) (x : N) : x ∈ (⨆ i (h : p i), S i) ↔ ∃ f : Π₀ i, S i, dfinsupp.lsum ℕ (λ i, (S i).subtype) (f.filter p) = x := set_like.ext_iff.mp (bsupr_eq_range_dfinsupp_lsum p S) x open_locale big_operators omit dec_ι lemma mem_supr_finset_iff_exists_sum {s : finset ι} (p : ι → submodule R N) (a : N) : a ∈ (⨆ i ∈ s, p i) ↔ ∃ μ : Π i, p i, ∑ i in s, (μ i : N) = a := begin classical, rw submodule.mem_supr_iff_exists_dfinsupp', split; rintro ⟨μ, hμ⟩, { use λ i, ⟨μ i, (supr_const_le : _ ≤ p i) (coe_mem $ μ i)⟩, rw ← hμ, symmetry, apply finset.sum_subset, { intro x, contrapose, intro hx, rw [mem_support_iff, not_ne_iff], ext, rw [coe_zero, ← mem_bot R], convert coe_mem (μ x), symmetry, exact supr_neg hx }, { intros x _ hx, rw [mem_support_iff, not_ne_iff] at hx, rw hx, refl } }, { refine ⟨dfinsupp.mk s _, _⟩, { rintro ⟨i, hi⟩, refine ⟨μ i, _⟩, rw supr_pos, { exact coe_mem _ }, { exact hi } }, simp only [dfinsupp.sum], rw [finset.sum_subset support_mk_subset, ← hμ], exact finset.sum_congr rfl (λ x hx, congr_arg coe $ mk_of_mem hx), { intros x _ hx, rw [mem_support_iff, not_ne_iff] at hx, rw hx, refl } } end end submodule namespace complete_lattice open dfinsupp section semiring variables [semiring R] [add_comm_monoid N] [module R N] /-- Independence of a family of submodules can be expressed as a quantifier over `dfinsupp`s. This is an intermediate result used to prove `complete_lattice.independent_of_dfinsupp_lsum_injective` and `complete_lattice.independent.dfinsupp_lsum_injective`. -/ lemma independent_iff_forall_dfinsupp (p : ι → submodule R N) : independent p ↔ ∀ i (x : p i) (v : Π₀ (i : ι), ↥(p i)), lsum ℕ (λ i, (p i).subtype) (erase i v) = x → x = 0 := begin simp_rw [complete_lattice.independent_def, submodule.disjoint_def, submodule.mem_bsupr_iff_exists_dfinsupp, exists_imp_distrib, filter_ne_eq_erase], apply forall_congr (λ i, _), refine subtype.forall'.trans _, simp_rw submodule.coe_eq_zero, refl, end /- If `dfinsupp.lsum` applied with `submodule.subtype` is injective then the submodules are independent. -/ lemma independent_of_dfinsupp_lsum_injective (p : ι → submodule R N) (h : function.injective (lsum ℕ (λ i, (p i).subtype))) : independent p := begin rw independent_iff_forall_dfinsupp, intros i x v hv, replace hv : lsum ℕ (λ i, (p i).subtype) (erase i v) = lsum ℕ (λ i, (p i).subtype) (single i x), { simpa only [lsum_single] using hv, }, have := dfinsupp.ext_iff.mp (h hv) i, simpa [eq_comm] using this, end /- If `dfinsupp.sum_add_hom` applied with `add_submonoid.subtype` is injective then the additive submonoids are independent. -/ lemma independent_of_dfinsupp_sum_add_hom_injective (p : ι → add_submonoid N) (h : function.injective (sum_add_hom (λ i, (p i).subtype))) : independent p := begin rw ←independent_map_order_iso_iff (add_submonoid.to_nat_submodule : add_submonoid N ≃o _), exact independent_of_dfinsupp_lsum_injective _ h, end /-- Combining `dfinsupp.lsum` with `linear_map.to_span_singleton` is the same as `finsupp.total` -/ lemma lsum_comp_map_range_to_span_singleton [Π (m : R), decidable (m ≠ 0)] (p : ι → submodule R N) {v : ι → N} (hv : ∀ (i : ι), v i ∈ p i) : ((lsum ℕ) (λ i, (p i).subtype) : _ →ₗ[R] _).comp ((map_range.linear_map (λ i, linear_map.to_span_singleton R ↥(p i) ⟨v i, hv i⟩) : _ →ₗ[R] _).comp (finsupp_lequiv_dfinsupp R : (ι →₀ R) ≃ₗ[R] _).to_linear_map) = finsupp.total ι N R v := by { ext, simp } end semiring section ring variables [ring R] [add_comm_group N] [module R N] /- If `dfinsupp.sum_add_hom` applied with `add_submonoid.subtype` is injective then the additive subgroups are independent. -/ lemma independent_of_dfinsupp_sum_add_hom_injective' (p : ι → add_subgroup N) (h : function.injective (sum_add_hom (λ i, (p i).subtype))) : independent p := begin rw ←independent_map_order_iso_iff (add_subgroup.to_int_submodule : add_subgroup N ≃o _), exact independent_of_dfinsupp_lsum_injective _ h, end /-- The canonical map out of a direct sum of a family of submodules is injective when the submodules are `complete_lattice.independent`. Note that this is not generally true for `[semiring R]`, for instance when `A` is the `ℕ`-submodules of the positive and negative integers. See `counterexamples/direct_sum_is_internal.lean` for a proof of this fact. -/ lemma independent.dfinsupp_lsum_injective {p : ι → submodule R N} (h : independent p) : function.injective (lsum ℕ (λ i, (p i).subtype)) := begin -- simplify everything down to binders over equalities in `N` rw independent_iff_forall_dfinsupp at h, suffices : (lsum ℕ (λ i, (p i).subtype)).ker = ⊥, { -- Lean can't find this without our help letI : add_comm_group (Π₀ i, p i) := @dfinsupp.add_comm_group _ (λ i, p i) _, rw linear_map.ker_eq_bot at this, exact this }, rw linear_map.ker_eq_bot', intros m hm, ext i : 1, -- split `m` into the piece at `i` and the pieces elsewhere, to match `h` rw [dfinsupp.zero_apply, ←neg_eq_zero], refine h i (-m i) m _, rwa [←erase_add_single i m, linear_map.map_add, lsum_single, submodule.subtype_apply, add_eq_zero_iff_eq_neg, ←submodule.coe_neg] at hm, end /-- The canonical map out of a direct sum of a family of additive subgroups is injective when the additive subgroups are `complete_lattice.independent`. -/ lemma independent.dfinsupp_sum_add_hom_injective {p : ι → add_subgroup N} (h : independent p) : function.injective (sum_add_hom (λ i, (p i).subtype)) := begin rw ←independent_map_order_iso_iff (add_subgroup.to_int_submodule : add_subgroup N ≃o _) at h, exact h.dfinsupp_lsum_injective, end /-- A family of submodules over an additive group are independent if and only iff `dfinsupp.lsum` applied with `submodule.subtype` is injective. Note that this is not generally true for `[semiring R]`; see `complete_lattice.independent.dfinsupp_lsum_injective` for details. -/ lemma independent_iff_dfinsupp_lsum_injective (p : ι → submodule R N) : independent p ↔ function.injective (lsum ℕ (λ i, (p i).subtype)) := ⟨independent.dfinsupp_lsum_injective, independent_of_dfinsupp_lsum_injective p⟩ /-- A family of additive subgroups over an additive group are independent if and only if `dfinsupp.sum_add_hom` applied with `add_subgroup.subtype` is injective. -/ lemma independent_iff_dfinsupp_sum_add_hom_injective (p : ι → add_subgroup N) : independent p ↔ function.injective (sum_add_hom (λ i, (p i).subtype)) := ⟨independent.dfinsupp_sum_add_hom_injective, independent_of_dfinsupp_sum_add_hom_injective' p⟩ omit dec_ι /-- If a family of submodules is `independent`, then a choice of nonzero vector from each submodule forms a linearly independent family. See also `complete_lattice.independent.linear_independent'`. -/ lemma independent.linear_independent [no_zero_smul_divisors R N] (p : ι → submodule R N) (hp : independent p) {v : ι → N} (hv : ∀ i, v i ∈ p i) (hv' : ∀ i, v i ≠ 0) : linear_independent R v := begin classical, rw linear_independent_iff, intros l hl, let a := dfinsupp.map_range.linear_map (λ i, linear_map.to_span_singleton R (p i) (⟨v i, hv i⟩)) l.to_dfinsupp, have ha : a = 0, { apply hp.dfinsupp_lsum_injective, rwa ←lsum_comp_map_range_to_span_singleton _ hv at hl }, ext i, apply smul_left_injective R (hv' i), have : l i • v i = a i := rfl, simp [this, ha], end lemma independent_iff_linear_independent_of_ne_zero [no_zero_smul_divisors R N] {v : ι → N} (h_ne_zero : ∀ i, v i ≠ 0) : independent (λ i, R ∙ v i) ↔ linear_independent R v := ⟨λ hv, hv.linear_independent _ (λ i, submodule.mem_span_singleton_self $ v i) h_ne_zero, λ hv, hv.independent_span_singleton⟩ end ring end complete_lattice
0c7beb88d48ba96f4b498f3aea8f153cf14ec5ac
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/class1.lean
16b5a3ebec6e27aaeac5badaf3f26e1491580573
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
156
lean
import logic data.prod data.num open prod inhabited definition H : inhabited (Prop × num × (num → num)) := _ (* print(get_env():find("H"):value()) *)
21c905b7811dcec8d9a75ac1d9e46fa883011cf0
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/real/division.lean
87f9af41febd56b20e6c9a082c83c4008dac2eea
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
23,994
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability and excluded middle. -/ import data.real.basic data.real.order data.rat data.nat open rat open nat open eq.ops pnat classical namespace rat_seq local postfix ⁻¹ := pnat.inv ----------------------------- -- Facts about absolute values of sequences, to define inverse definition s_abs (s : seq) : seq := λ n, abs (s n) theorem abs_reg_of_reg {s : seq} (Hs : regular s) : regular (s_abs s) := begin intros, apply le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Hs end theorem abs_pos_of_nonzero {s : seq} (Hs : regular s) (Hnz : sep s zero) : ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m) ≥ N⁻¹ := begin rewrite [↑sep at Hnz, ↑s_lt at Hnz], apply or.elim Hnz, intro Hnz1, have H' : pos (sneg s), begin apply pos_of_pos_equiv, rotate 2, apply Hnz1, rotate 1, apply s_zero_add, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end, cases bdd_away_of_pos (reg_neg_reg Hs) H' with [N, HN], existsi N, intro m Hm, apply le.trans, apply HN m Hm, rewrite ↑sneg, apply neg_le_abs_self, intro Hnz2, let H' := pos_of_pos_equiv (reg_add_reg Hs (reg_neg_reg zero_is_reg)) (s_add_zero s Hs) Hnz2, let H'' := bdd_away_of_pos Hs H', cases H'' with [N, HN], existsi N, intro m Hm, apply le.trans, apply HN m Hm, apply le_abs_self end theorem abs_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_abs s ≡ s_abs t := begin rewrite [↑equiv at *], intro n, rewrite ↑s_abs, apply le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Heq end theorem sep_zero_of_pos {s : seq} (Hs : regular s) (Hpos : pos s) : sep s zero := begin apply or.inr, apply pos_of_pos_equiv, rotate 2, apply Hpos, apply Hs, apply equiv.symm, apply s_sub_zero Hs end ------------------------ -- This section could be cleaned up. private noncomputable definition pb {s : seq} (Hs : regular s) (Hpos : pos s) := some (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private noncomputable definition ps {s : seq} (Hs : regular s) (Hsep : sep s zero) := some (abs_pos_of_nonzero Hs Hsep) private theorem pb_spec {s : seq} (Hs : regular s) (Hpos : pos s) : ∀ m : ℕ+, m ≥ (pb Hs Hpos) → abs (s m) ≥ (pb Hs Hpos)⁻¹ := some_spec (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private theorem ps_spec {s : seq} (Hs : regular s) (Hsep : sep s zero) : ∀ m : ℕ+, m ≥ (ps Hs Hsep) → abs (s m) ≥ (ps Hs Hsep)⁻¹ := some_spec (abs_pos_of_nonzero Hs Hsep) noncomputable definition s_inv {s : seq} (Hs : regular s) (n : ℕ+) : ℚ := if H : sep s zero then (if n < (ps Hs H) then 1 / (s ((ps Hs H) * (ps Hs H) * (ps Hs H))) else 1 / (s ((ps Hs H) * (ps Hs H) * n))) else 0 private theorem peq {s : seq} (Hsep : sep s zero) (Hpos : pos s) (Hs : regular s) : pb Hs Hpos = ps Hs Hsep := rfl private theorem s_inv_of_sep_lt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n < (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) := begin apply eq.trans, apply dif_pos Hsep, apply dif_pos Hn end private theorem s_inv_of_sep_gt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n ≥ (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * n) := begin apply eq.trans, apply dif_pos Hsep, apply dif_neg (pnat.not_lt_of_ge Hn) end private theorem s_inv_of_pos_lt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : ℕ+} (Hn : n < (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * (pb Hs Hpos)) := s_inv_of_sep_lt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem s_inv_of_pos_gt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : ℕ+} (Hn : n ≥ (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * n) := s_inv_of_sep_gt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem le_ps {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : ℕ+) : abs (s_inv Hs n) ≤ (rat_of_pnat (ps Hs Hsep)) := if Hn : n < ps Hs Hsep then (begin rewrite [(s_inv_of_sep_lt_p Hs Hsep Hn), abs_one_div], apply div_le_pnat, apply ps_spec, apply pnat.mul_le_mul_left end) else (begin rewrite [(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hn)), abs_one_div], apply div_le_pnat, apply ps_spec, rewrite pnat.mul_assoc, apply pnat.mul_le_mul_right end) theorem s_inv_zero : s_inv zero_is_reg = zero := funext (λ n, dif_neg (!not_sep_self)) private theorem s_inv_of_zero' {s : seq} (Hs : regular s) (Hz : ¬ sep s zero) (n : ℕ+) : s_inv Hs n = 0 := dif_neg Hz theorem s_inv_of_zero {s : seq} (Hs : regular s) (Hz : ¬ sep s zero) : s_inv Hs = zero := begin apply funext, intro n, apply s_inv_of_zero' Hs Hz n end private theorem s_ne_zero_of_ge_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n ≥ (ps Hs Hsep)) : s n ≠ 0 := begin let Hps := ps_spec Hs Hsep, apply ne_zero_of_abs_ne_zero, apply ne_of_gt, apply gt_of_ge_of_gt, apply Hps, apply Hn, apply pnat.inv_pos end theorem reg_inv_reg {s : seq} (Hs : regular s) (Hsep : sep s zero) : regular (s_inv Hs) := begin rewrite ↑regular, intros, have Hsp : s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep !pnat.mul_le_mul_left, have Hspn : s ((ps Hs Hsep) * (ps Hs Hsep) * n) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * n ≥ ps Hs Hsep, by rewrite pnat.mul_assoc; apply pnat.mul_le_mul_right), have Hspm : s ((ps Hs Hsep) * (ps Hs Hsep) * m) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * m ≥ ps Hs Hsep, by rewrite pnat.mul_assoc; apply pnat.mul_le_mul_right), cases em (m < ps Hs Hsep) with [Hmlt, Hmlt], cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_lt_p Hs Hsep Hnlt)], rewrite [sub_self, abs_zero], apply add_invs_nonneg, rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt))], rewrite [(!div_sub_div Hsp Hspn), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hsp Hspn), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hmlt), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply add_le_add_right, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hmlt, cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hnlt), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hsp), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hsp), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hnlt), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply rat.add_le_add_left, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hnlt, rewrite [(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hspn), div_eq_mul_one_div, abs_mul, *one_mul, *mul_one], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hspn), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply le.refl end theorem s_inv_ne_zero {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : ℕ+) : s_inv Hs n ≠ 0 := if H : n ≥ ps Hs Hsep then (begin rewrite (s_inv_of_sep_gt_p Hs Hsep H), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.le_trans, apply H, apply pnat.mul_le_mul_left end) else (begin rewrite (s_inv_of_sep_lt_p Hs Hsep (pnat.lt_of_not_le H)), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.mul_le_mul_left end) protected theorem mul_inv {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul s (s_inv Hs) ≡ one := begin let Rsi := reg_inv_reg Hs Hsep, let Rssi := reg_mul_reg Hs Rsi, apply eq_of_bdd Rssi one_is_reg, intros, existsi max (ps Hs Hsep) j, intro n Hn, have Hnz : s_inv Hs ((K₂ s (s_inv Hs)) * 2 * n) ≠ 0, from s_inv_ne_zero Hs Hsep _, rewrite [↑smul, ↑one, mul.comm, -(mul_one_div_cancel Hnz), -mul_sub_left_distrib, abs_mul], apply le.trans, apply mul_le_mul_of_nonneg_right, apply canon_2_bound_right s, apply Rsi, apply abs_nonneg, have Hp : (K₂ s (s_inv Hs)) * 2 * n ≥ ps Hs Hsep, begin apply pnat.le_trans, apply pnat.max_left, rotate 1, apply pnat.le_trans, apply Hn, apply pnat.mul_le_mul_left end, have Hnz' : s (((ps Hs Hsep) * (ps Hs Hsep)) * ((K₂ s (s_inv Hs)) * 2 * n)) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show ps Hs Hsep ≤ ((ps Hs Hsep) * (ps Hs Hsep)) * ((K₂ s (s_inv Hs)) * 2 * n), by rewrite *pnat.mul_assoc; apply pnat.mul_le_mul_right), rewrite [(s_inv_of_sep_gt_p Hs Hsep Hp), (division_ring.one_div_one_div Hnz')], apply rat.le_trans, apply mul_le_mul_of_nonneg_left, apply Hs, apply le_of_lt, apply rat_of_pnat_is_pos, rewrite [left_distrib, pnat.mul_comm ((ps Hs Hsep) * (ps Hs Hsep)), *pnat.mul_assoc, *(@pnat.inv_mul_eq_mul_inv (K₂ s (s_inv Hs))), -*mul.assoc, *pnat.inv_cancel_left, *one_mul, -(pnat.add_halves j)], apply add_le_add, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, apply pnat.max_right, rotate 1, apply pnat.le_trans, apply Hn, apply pnat.mul_le_mul_right end protected theorem inv_mul {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul (s_inv Hs) s ≡ one := begin apply equiv.trans, rotate 3, apply s_mul_comm, apply rat_seq.mul_inv, repeat (assumption | apply reg_mul_reg | apply reg_inv_reg | apply zero_is_reg) end theorem sep_of_equiv_sep {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) (Hsep : sep s zero) : sep t zero := begin apply or.elim Hsep, intro Hslt, apply or.inl, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, intro Hslt, apply or.inr, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 5, apply equiv.refl, repeat (assumption | apply reg_neg_reg | apply reg_add_reg | apply zero_is_reg) end theorem inv_unique {s t : seq} (Hs : regular s) (Ht : regular t) (Hsep : sep s zero) (Heq : smul s t ≡ one) : s_inv Hs ≡ t := begin apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_one, rotate 1, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply equiv.refl, apply equiv.symm, apply Heq, apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_assoc, rotate 3, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply rat_seq.inv_mul, rotate 1, apply equiv.refl, apply s_one_mul, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg | apply one_is_reg) end theorem inv_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_inv Hs ≡ s_inv Ht := if Hsep : sep s zero then (begin note Hsept := sep_of_equiv_sep Hs Ht Heq Hsep, have Hm : smul t (s_inv Hs) ≡ smul s (s_inv Hs), begin apply mul_well_defined, repeat (assumption | apply reg_inv_reg), apply equiv.symm s t Heq, apply equiv.refl end, apply equiv.symm, apply inv_unique, rotate 2, apply equiv.trans, rotate 3, apply Hm, apply rat_seq.mul_inv, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg), apply one_is_reg end) else (assert H : s_inv Hs = zero, from funext (λ n, dif_neg Hsep), have Hsept : ¬ sep t zero, from assume H', Hsep (sep_of_equiv_sep Ht Hs (equiv.symm _ _ Heq) H'), assert H' : s_inv Ht = zero, from funext (λ n, dif_neg Hsept), by rewrite [H', H]; apply equiv.refl) theorem s_neg_neg {s : seq} : sneg (sneg s) ≡ s := begin rewrite [↑equiv, ↑sneg], intro n, rewrite [neg_neg, sub_self, abs_zero], apply add_invs_nonneg end theorem s_neg_sub {s t : seq} (Hs : regular s) (Ht : regular t) : sneg (sadd s (sneg t)) ≡ sadd t (sneg s) := begin apply equiv.trans, rotate 3, apply s_neg_add_eq_s_add_neg, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_neg, apply s_add_comm, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_total {s t : seq} (Hs : regular s) (Ht : regular t) : s_le s t ∨ s_le t s := if H : s_le s t then or.inl H else or.inr begin rewrite [↑s_le at *], have H' : ∃ n : ℕ+, -n⁻¹ > sadd t (sneg s) n, begin apply by_contradiction, intro Hex, have Hex' : ∀ n : ℕ+, -n⁻¹ ≤ sadd t (sneg s) n, begin intro m, apply by_contradiction, intro Hm, note Hm' := lt_of_not_ge Hm, note Hex'' := exists.intro m Hm', apply Hex Hex'' end, apply H Hex' end, eapply exists.elim H', intro m Hm, note Hm' := neg_lt_neg Hm, rewrite neg_neg at Hm', apply s_nonneg_of_pos, rotate 1, apply pos_of_pos_equiv, rotate 1, apply s_neg_sub, rotate 2, rewrite [↑pos, ↑sneg], existsi m, apply Hm', repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_not_lt {s t : seq} (Hle : ¬ s_lt s t) : s_le t s := begin rewrite [↑s_le, ↑nonneg, ↑s_lt at Hle, ↑pos at Hle], let Hle' := iff.mp forall_iff_not_exists Hle, intro n, let Hn := neg_le_neg (le_of_not_gt (Hle' n)), rewrite [↑sadd, ↑sneg, add_neg_eq_neg_add_rev], apply Hn end theorem sep_of_nequiv {s t : seq} (Hs : regular s) (Ht : regular t) (Hneq : ¬ equiv s t) : sep s t := begin rewrite ↑sep, apply by_contradiction, intro Hnor, let Hand := iff.mp !not_or_iff_not_and_not Hnor, let Hle1 := s_le_of_not_lt (and.left Hand), let Hle2 := s_le_of_not_lt (and.right Hand), apply Hneq (equiv_of_le_of_ge Hs Ht Hle2 Hle1) end theorem s_zero_inv_equiv_zero : s_inv zero_is_reg ≡ zero := by rewrite s_inv_zero; apply equiv.refl theorem lt_or_equiv_of_le {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : s_le s t) : s_lt s t ∨ s ≡ t := if H : s ≡ t then or.inr H else or.inl (lt_of_le_and_sep Hs Ht (and.intro Hle (sep_of_nequiv Hs Ht H))) theorem s_le_of_equiv_le_left {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : s ≡ t) (Hle : s_le s u) : s_le t u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_equiv_le_right {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : t ≡ u) (Hle : s_le s t) : s_le s u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply Heq, apply equiv.refl, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end ----------------------------- noncomputable definition r_inv (s : reg_seq) : reg_seq := reg_seq.mk (s_inv (reg_seq.is_reg s)) (if H : sep (reg_seq.sq s) zero then reg_inv_reg (reg_seq.is_reg s) H else assert Hz : s_inv (reg_seq.is_reg s) = zero, from funext (λ n, dif_neg H), by rewrite Hz; apply zero_is_reg) theorem r_inv_zero : requiv (r_inv r_zero) r_zero := s_zero_inv_equiv_zero theorem r_inv_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_inv s) (r_inv t) := inv_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_le_total (s t : reg_seq) : r_le s t ∨ r_le t s := s_le_total (reg_seq.is_reg s) (reg_seq.is_reg t) theorem r_mul_inv (s : reg_seq) (Hsep : r_sep s r_zero) : requiv (s * (r_inv s)) r_one := rat_seq.mul_inv (reg_seq.is_reg s) Hsep theorem r_sep_of_nequiv (s t : reg_seq) (Hneq : ¬ requiv s t) : r_sep s t := sep_of_nequiv (reg_seq.is_reg s) (reg_seq.is_reg t) Hneq theorem r_lt_or_equiv_of_le (s t : reg_seq) (Hle : r_le s t) : r_lt s t ∨ requiv s t := lt_or_equiv_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle theorem r_le_of_equiv_le_left {s t u : reg_seq} (Heq : requiv s t) (Hle : r_le s u) : r_le t u := s_le_of_equiv_le_left (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle theorem r_le_of_equiv_le_right {s t u : reg_seq} (Heq : requiv t u) (Hle : r_le s t) : r_le s u := s_le_of_equiv_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle definition r_abs (s : reg_seq) : reg_seq := reg_seq.mk (s_abs (reg_seq.sq s)) (abs_reg_of_reg (reg_seq.is_reg s)) theorem r_abs_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_abs s) (r_abs t) := abs_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H end rat_seq namespace real open [class] rat_seq noncomputable protected definition inv (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (rat_seq.r_inv a)) (λ a b H, quot.sound (rat_seq.r_inv_well_defined H)) noncomputable definition real_has_inv [instance] [reducible] [priority real.prio] : has_inv real := has_inv.mk real.inv noncomputable protected definition div (x y : ℝ) : ℝ := x * y⁻¹ noncomputable definition real_has_div [instance] [reducible] [priority real.prio] : has_div real := has_div.mk real.div protected theorem le_total (x y : ℝ) : x ≤ y ∨ y ≤ x := quot.induction_on₂ x y (λ s t, rat_seq.r_le_total s t) protected theorem mul_inv_cancel' (x : ℝ) : x ≢ 0 → x * x⁻¹ = 1 := quot.induction_on x (λ s H, quot.sound (rat_seq.r_mul_inv s H)) protected theorem inv_mul_cancel' (x : ℝ) : x ≢ 0 → x⁻¹ * x = 1 := by rewrite real.mul_comm; apply real.mul_inv_cancel' theorem neq_of_sep {x y : ℝ} (H : x ≢ y) : ¬ x = y := assume Heq, !not_sep_self (Heq ▸ H) theorem sep_of_neq {x y : ℝ} : ¬ x = y → x ≢ y := quot.induction_on₂ x y (λ s t H, rat_seq.r_sep_of_nequiv s t (assume Heq, H (quot.sound Heq))) theorem sep_is_neq (x y : ℝ) : (x ≢ y) = (¬ x = y) := propext (iff.intro neq_of_sep sep_of_neq) protected theorem mul_inv_cancel (x : ℝ) : x ≠ 0 → x * x⁻¹ = 1 := !sep_is_neq ▸ !real.mul_inv_cancel' protected theorem inv_mul_cancel (x : ℝ) : x ≠ 0 → x⁻¹ * x = 1 := !sep_is_neq ▸ !real.inv_mul_cancel' protected theorem inv_zero : (0 : ℝ)⁻¹ = 0 := quot.sound (rat_seq.r_inv_zero) protected theorem lt_or_eq_of_le (x y : ℝ) : x ≤ y → x < y ∨ x = y := quot.induction_on₂ x y (λ s t H, or.elim (rat_seq.r_lt_or_equiv_of_le s t H) (assume H1, or.inl H1) (assume H2, or.inr (quot.sound H2))) protected theorem le_iff_lt_or_eq (x y : ℝ) : x ≤ y ↔ x < y ∨ x = y := iff.intro (real.lt_or_eq_of_le x y) (real.le_of_lt_or_eq x y) noncomputable definition dec_lt : decidable_rel real.lt := begin rewrite ↑decidable_rel, intros, apply prop_decidable end protected noncomputable definition discrete_linear_ordered_field [reducible] [trans_instance]: discrete_linear_ordered_field ℝ := ⦃ discrete_linear_ordered_field, real.comm_ring, real.ordered_ring, le_total := real.le_total, mul_inv_cancel := real.mul_inv_cancel, inv_mul_cancel := real.inv_mul_cancel, zero_lt_one := real.zero_lt_one, inv_zero := real.inv_zero, le_iff_lt_or_eq := real.le_iff_lt_or_eq, decidable_lt := dec_lt ⦄ theorem of_rat_divide (x y : ℚ) : of_rat (x / y) = of_rat x / of_rat y := by_cases (assume yz : y = 0, by krewrite [yz, div_zero, +of_rat_zero, div_zero]) (assume ynz : y ≠ 0, have ynz' : of_rat y ≠ 0, from assume yz', ynz (of_rat.inj yz'), !eq_div_of_mul_eq ynz' (by krewrite [-of_rat_mul, !div_mul_cancel ynz])) open int theorem of_int_div (x y : ℤ) (H : y ∣ x) : of_int (x / y) = of_int x / of_int y := by rewrite [of_int_eq, rat.of_int_div H, of_rat_divide] theorem of_nat_div (x y : ℕ) (H : y ∣ x) : of_nat (x / y) = of_nat x / of_nat y := by rewrite [of_nat_eq, rat.of_nat_div H, of_rat_divide] /- useful for proving equalities -/ theorem eq_zero_of_nonneg_of_forall_lt {x : ℝ} (xnonneg : x ≥ 0) (H : ∀ ε : ℝ, ε > 0 → x < ε) : x = 0 := decidable.by_contradiction (suppose x ≠ 0, have x > 0, from lt_of_le_of_ne xnonneg (ne.symm this), have x < x, from H x this, show false, from !lt.irrefl this) theorem eq_zero_of_nonneg_of_forall_le {x : ℝ} (xnonneg : x ≥ 0) (H : ∀ ε : ℝ, ε > 0 → x ≤ ε) : x = 0 := have ∀ ε : ℝ, ε > 0 → x < ε, from take ε, suppose ε > 0, assert e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, assert ε / 2 < ε, from div_two_lt_of_pos `ε > 0`, begin apply lt_of_le_of_lt, apply H _ e2pos, apply this end, eq_zero_of_nonneg_of_forall_lt xnonneg this theorem eq_zero_of_forall_abs_le {x : ℝ} (H : ∀ ε : ℝ, ε > 0 → abs x ≤ ε) : x = 0 := by_contradiction (suppose x ≠ 0, have abs x = 0, from eq_zero_of_nonneg_of_forall_le !abs_nonneg H, show false, from `x ≠ 0` (eq_zero_of_abs_eq_zero this)) theorem eq_of_forall_abs_sub_le {x y : ℝ} (H : ∀ ε : ℝ, ε > 0 → abs (x - y) ≤ ε) : x = y := have x - y = 0, from eq_zero_of_forall_abs_le H, eq_of_sub_eq_zero this end real
acd24afdeff0a2745a7ef46767ec95422d476d75
827a8a5c2041b1d7f55e128581f583dfbd65ecf6
/spectral/scratch.hlean
faff2a27fcd5a7df6fc5cbf1e388e67898a08297
[ "Apache-2.0" ]
permissive
fpvandoorn/leansnippets
6af0499f6f3fd2c07e4b580734d77b67574e7c27
601bafbe07e9534af76f60994d6bdf741996ef93
refs/heads/master
1,590,063,910,882
1,545,093,878,000
1,545,093,878,000
36,044,957
2
2
null
1,442,619,708,000
1,432,256,875,000
Lean
UTF-8
Lean
false
false
5,548
hlean
import .seq_colim open eq nat sigma sigma.ops quotient equiv pi is_trunc is_equiv fiber function trunc seq_colim universe variables v w variables {A A' A'' : ℕ → Type} {f : seq_diagram A} {f' : seq_diagram A'} {f'' : seq_diagram A''} {τ τ₂ : Π⦃n⦄, A n → A' n} {p : Π⦃n⦄ (a : A n), τ (f a) = f' (τ a)} {p₂ : Π⦃n⦄ (a : A n), τ₂ (f a) = f' (τ₂ a)} {τ' : Π⦃n⦄, A' n → A'' n} {p' : Π⦃n⦄ (a' : A' n), τ' (f' a') = f'' (τ' a')} {P : Π⦃n⦄, A n → Type.{v}} {P' : Π⦃n⦄, A' n → Type.{w}} {g : seq_diagram_over f P} {g' : seq_diagram_over f' P'} {n : ℕ} {a : A n} (σ : Π⦃n⦄ {a : A n}, P a → P' (τ a)) (q : Π⦃n⦄ {a : A n} (x : P a), σ (g x) =[p a] g' (σ x)) definition sigma_colim_elim_point [unfold 10] {X : Type} (e : Π⦃n⦄ ⦃a : A n⦄, P a → X) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), e (g x) = e x) {n : ℕ} {a : A n} (y : seq_colim_over g (ι f a)) : X := begin induction y with k x k x, { exact e x }, { exact w x } end -- ⊢ square -- (apd0111 e (succ_add n (succ k)) (rep_f f (succ k) a) -- (pathover_tro (rep_f f (succ k) a) (g x))) -- (apd0111 e (succ_add n k) (rep_f f k a) -- (pathover_tro (rep_f f k a) x)) -- (w x) -- (ap e (rep_f_equiv_natural g x) ⬝ w (rep_f f k a ▸o x)) -- print apd0111_precompose -- print ap_apd0111 -- definition apd0111_natural {A₁ A₂ A : Type} {B₁ : A₁ → Type} {B₂ : A₂ → Type} -- {C₁ : Π⦃a⦄, B₁ a → Type} {C₂ : Π⦃a⦄, B₂ a → Type} {a a₂ : A₁} -- {ga : A₁ → A₂} {gb : Π⦃a⦄, B₁ a → B₂ (ga a)} {gc : Π⦃a⦄ {b : B₁ a}, C₁ b → C₂ (gb b)} -- {b : B₁ a} {b₂ : B₁ a₂} {c : C₁ b} {c₂ : C₁ b₂} -- (f₁ : Π⦃a⦄ {b : B₁ a}, C₁ b → A) (f₂ : Π⦃a⦄ {b : B₂ a}, C₂ b → A) (Ha : a = a₂) (Hb : b =[Ha] b₂) -- (Hc : c =[apd011 C₁ Ha Hb] c₂) -- (h : Π⦃a⦄ {b : B₁ a} (c : C₁ b), f₁ c = f₂ (gc c)) : -- square (apd0111 f₁ Ha Hb Hc) (apd0111 f₂ (ap ga Ha) (pathover_ap B₂ ga (apo gb Hb)) _) -- (h c) (h (transporto C₁ _ c₂)) := -- begin end definition sigma_colim_elim_path {X : Type} (e : Π⦃n⦄ ⦃a : A n⦄, P a → X) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), e (g x) = e x) {n : ℕ} (a : A n) : pathover (λx, seq_colim_over g x → X) (sigma_colim_elim_point e w) (glue f a) (sigma_colim_elim_point e w) := begin apply arrow_pathover_constant_right, intro y, refine _ ⬝ ap (sigma_colim_elim_point e w) (seq_colim_over_glue g _)⁻¹ᵖ, induction y with k x k x, { exact apd0111 e _ (rep_f f k a) !pathover_tro }, { apply eq_pathover, refine !elim_glue ⬝ph _ ⬝hp (ap_compose (sigma_colim_elim_point e w ∘ shift_down _) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ !ap_compose⁻¹ ◾ (!ap_compose ⬝ ap02 _ !elim_glue ⬝ !elim_glue))⁻¹, esimp [function.compose], apply move_right_of_top, exact sorry } end definition sigma_colim_elim {X : Type} (e : Π⦃n⦄ ⦃a : A n⦄, P a → X) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), e (g x) = e x) (v : Σ(x : seq_colim f), seq_colim_over g x) : X := begin induction v with x y, induction x with n a n a, { exact sigma_colim_elim_point e w y }, { exact sigma_colim_elim_path e w a } end theorem sigma_colim_elim_glue {X : Type} (e : Π⦃n⦄ ⦃a : A n⦄, P a → X) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), e (g x) = e x) {n : ℕ} {a : A n} (x : P a) : ap (sigma_colim_elim e w) (glue' g x) = w x := begin refine !ap_dpair_eq_dpair ⬝ _, refine !apd011_eq_apo11_apd ⬝ _, refine ap (λx, apo11_constant_right x _) !rec_glue ⬝ _, refine !apo11_arrow_pathover_constant_right ⬝ _, refine whisker_right _ !idp_con ⬝ _, rewrite [▸*, tr_eq_of_pathover_concato_eq, ap_con, ↑glue_over, to_right_inv !pathover_equiv_tr_eq, ap_inv, inv_con_cancel_left], apply elim_glue end example {E : (Σ(x : seq_colim f), seq_colim_over g x) → Type} (e : Π⦃n⦄ ⦃a : A n⦄ (x : P a), E ⟨ι f a, ιo g x⟩) (w : Π⦃n⦄ ⦃a : A n⦄ (x : P a), pathover E (e (g x)) (glue' g x) (e x)) {n : ℕ} {a : A n} (x : P a) : sigma_colim_rec g e w ⟨ι f a, ιo g x⟩ = e x := by reflexivity include q definition seq_colim_over_functor_point (a : A n) : seq_colim_over g (ι f a) → seq_colim_over g' (ι f' (τ a)) := begin refine seq_colim_functor _ _, { intro k x, exact transport (@P' (n+k)) (rep_natural τ p k a) (σ x) }, { intro k x, refine _ ⬝ (fn_tr_eq_tr_fn (rep_natural τ p k a) (@g' _) (σ x))⁻¹, refine _ ⬝ tr_ap (@P' _) (@f' _) _ _, refine _ ⬝ ap (transport _ _) (tr_eq_of_pathover (q x)), exact con_tr (p _) (ap _ (rep_natural τ p k _)) (σ (g x)) } end definition seq_colim_over_functor ⦃a : seq_colim f⦄ : seq_colim_over g a → seq_colim_over g' (seq_colim_functor τ p a) := begin induction a, { exact seq_colim_over_functor_point σ q a }, { apply arrow_pathover_left, esimp, intro x, induction x with k x k x, { exact sorry }, { exact sorry }} end definition sigma_colim_of_colim_sigma_natural (a : seq_colim (seq_diagram_sigma g)) : hsquare (sigma_colim_of_colim_sigma g) (sigma_colim_of_colim_sigma g') (seq_colim_functor (λn, sigma_functor (@τ n) (@σ n)) (λn, sigma_functor_hsquare (@p n) (@q n))) (sigma_functor (seq_colim_functor τ p) (seq_colim_over_functor σ q)) := begin exact sorry end
22b496fe8d4110c4edf77271fb99b3059d6a7a3b
367134ba5a65885e863bdc4507601606690974c1
/src/data/int/basic.lean
e631f8b557fc8ed53e6df22e0e359789caf03fe2
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
53,368
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. -/ import data.nat.basic import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, sub := int.sub, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /-! ### Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_le_one := le_of_lt int.zero_lt_one, .. int.comm_ring, .. int.linear_order, .. int.nontrivial } instance : linear_ordered_add_comm_group int := by apply_instance @[simp] lemma add_neg_one (i : ℤ) : i + -1 = i - 1 := rfl theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] lemma neg_succ_not_nonneg (n : ℕ) : 0 ≤ -[1+ n] ↔ false := by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, } @[simp] lemma neg_succ_not_pos (n : ℕ) : 0 < -[1+ n] ↔ false := by simp only [not_lt, iff_false] @[simp] lemma neg_succ_sub_one (n : ℕ) : -[1+ n] - 1 = -[1+ (n+1)] := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero @[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 @[simp] lemma succ_coe_nat_pos (n : ℕ) : 0 < (n : ℤ) + 1 := lt_add_one_iff.mpr (by simp) @[norm_cast] lemma coe_pred_of_pos (n : ℕ) (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by { cases n, cases h, simp, } lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[simp] lemma eq_zero_iff_abs_lt_one {a : ℤ} : abs a < 1 ↔ a = 0 := ⟨λ a0, let ⟨hn, hp⟩ := abs_lt.mp a0 in (le_of_lt_add_one (by exact hp)).antisymm hn, λ a0, (abs_eq_zero.mpr a0).le.trans_lt zero_lt_one⟩ @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b) with n n, { induction n with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction n with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /-! ### nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) : a.nat_abs * b.nat_abs = c := by rw [← nat_abs_mul, h, nat_abs_of_nat] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end lemma nat_abs_eq_iff_mul_self_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a * a = b * b := begin rw [← abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_inj'.symm end lemma nat_abs_lt_iff_mul_self_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a * a < b * b := begin rw [← abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_lt.symm end lemma nat_abs_le_iff_mul_self_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a * a ≤ b * b := begin rw [← abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_le.symm end lemma nat_abs_eq_iff_sq_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a ^ 2 = b ^ 2 := by { rw [pow_two, pow_two], exact nat_abs_eq_iff_mul_self_eq } lemma nat_abs_lt_iff_sq_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a ^ 2 < b ^ 2 := by { rw [pow_two, pow_two], exact nat_abs_lt_iff_mul_self_lt } lemma nat_abs_le_iff_sq_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a ^ 2 ≤ b ^ 2 := by { rw [pow_two, pow_two], exact nat_abs_le_iff_mul_self_le } /-! ### `/` -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] protected theorem add_div_of_dvd_right {a b c : ℤ} (H : c ∣ b) : (a + b) / c = a / c + b / c := begin by_cases h1 : c = 0, { simp [h1] }, cases H with k hk, rw hk, change c ≠ 0 at h1, rw [mul_comm c k, int.add_mul_div_right _ _ h1, ←zero_add (k * c), int.add_mul_div_right _ _ h1, int.zero_div, zero_add] end protected theorem add_div_of_dvd_left {a b c : ℤ} (H : c ∣ a) : (a + b) / c = a / c + b / c := by rw [add_comm, int.add_div_of_dvd_right H, add_comm] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /-! ### mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem div_add_mod (a b : ℤ) : b * (a / b) + a % b = a := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℤ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℤ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self] } end @[simp] lemma neg_mod_two (i : ℤ) : (-i) % 2 = i % 2 := begin apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr, convert int.mul_mod_right 2 (-i), simp only [two_mul, sub_eq_add_neg] end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /-! ### properties of `/` and `%` -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by { rw [add_mul, one_mul, mul_comm, ← sub_lt_iff_lt_add', ← mod_def], exact mod_lt_of_pos _ H } theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /-! ### dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] protected theorem mul_div_assoc' (b : ℤ) {a c : ℤ} (h : c ∣ a) : a * b / c = a / c * b := by rw [mul_comm, int.mul_div_assoc _ h, mul_comm] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) : b = c / a := eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma sub_div_of_dvd {a b c : ℤ} (hcb : c ∣ b) : (a - b) / c = a / c - b / c := begin rw [sub_eq_add_neg, sub_eq_add_neg, int.add_div_of_dvd_right ((dvd_neg c b).mpr hcb)], congr, exact neg_div_of_dvd hcb, end lemma sub_div_of_dvd_sub {a b c : ℤ} (hcab : c ∣ (a - b)) : (a - b) / c = a / c - b / c := by rw [eq_sub_iff_add_eq, ← int.add_div_of_dvd_left hcab, sub_add_cancel] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) {n : ℤ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_add_one_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def] at h, have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ this, _⟩, rw [add_comm _ (1 : ℤ), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ } end /-! ### `/` and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /-! ### to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 := to_nat_add h (zero_le_one) @[simp] lemma pred_to_nat : ∀ (i : ℤ), (i - 1).to_nat = i.to_nat - 1 | (0:ℕ) := rfl | (n+1:ℕ) := by simp | -[1+ n] := rfl @[simp] lemma to_nat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.to_nat - 1 : ℕ) : ℤ) = i - 1 := by simp [h, le_of_lt h] with push_cast /-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`. -/ def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h lemma to_nat_zero_of_neg : ∀ {z : ℤ}, z < 0 → z.to_nat = 0 | (-[1+n]) _ := rfl | (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim /-! ### units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) @[simp] lemma units_mul_self (u : units ℤ) : u * u = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) -- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further @[simp] lemma units_coe_mul_self (u : units ℤ) : (u * u : ℤ) = 1 := by rw [←units.coe_mul, units_mul_self, units.coe_one] /-! ### bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n := mt (congr_arg bodd) $ by simp lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n := (bit0_ne_bit1 _ _).symm lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 := by simpa only [bit0_zero] using bit1_ne_bit0 m 0 @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /-! ### Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical end int attribute [irreducible] int.nonneg
ca8beb0f3c5b5fe74ba29c330b8851776d1e15c4
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/category_theory/closed/cartesian.lean
699f922aadf5b52b82f2de304b7afb7760539fcb
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,338
lean
/- Copyright (c) 2020 Bhavik Mehta, Edward Ayers, Thomas Read. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Edward Ayers, Thomas Read -/ import category_theory.limits.shapes.finite_products import category_theory.limits.preserves.shapes.binary_products import category_theory.closed.monoidal import category_theory.monoidal.of_has_finite_products import category_theory.adjunction import category_theory.adjunction.mates import category_theory.epi_mono /-! # Cartesian closed categories Given a category with finite products, the cartesian monoidal structure is provided by the local instance `monoidal_of_has_finite_products`. We define exponentiable objects to be closed objects with respect to this monoidal structure, i.e. `(X × -)` is a left adjoint. We say a category is cartesian closed if every object is exponentiable (equivalently, that the category equipped with the cartesian monoidal structure is closed monoidal). Show that exponential forms a difunctor and define the exponential comparison morphisms. ## TODO Some of the results here are true more generally for closed objects and for closed monoidal categories, and these could be generalised. -/ universes v u u₂ noncomputable theory namespace category_theory open category_theory category_theory.category category_theory.limits local attribute [instance] monoidal_of_has_finite_products /-- An object `X` is *exponentiable* if `(X × -)` is a left adjoint. We define this as being `closed` in the cartesian monoidal structure. -/ abbreviation exponentiable {C : Type u} [category.{v} C] [has_finite_products C] (X : C) := closed X /-- If `X` and `Y` are exponentiable then `X ⨯ Y` is. This isn't an instance because it's not usually how we want to construct exponentials, we'll usually prove all objects are exponential uniformly. -/ def binary_product_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] {X Y : C} (hX : exponentiable X) (hY : exponentiable Y) : exponentiable (X ⨯ Y) := { is_adj := begin haveI := hX.is_adj, haveI := hY.is_adj, exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm end } /-- The terminal object is always exponentiable. This isn't an instance because most of the time we'll prove cartesian closed for all objects at once, rather than just for this one. -/ def terminal_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] : exponentiable ⊤_C := unit_closed /-- A category `C` is cartesian closed if it has finite products and every object is exponentiable. We define this as `monoidal_closed` with respect to the cartesian monoidal structure. -/ abbreviation cartesian_closed (C : Type u) [category.{v} C] [has_finite_products C] := monoidal_closed C variables {C : Type u} [category.{v} C] (A B : C) {X X' Y Y' Z : C} section exp variables [has_finite_products C] [exponentiable A] /-- This is (-)^A. -/ def exp : C ⥤ C := (@closed.is_adj _ _ _ A _).right /-- The adjunction between A ⨯ - and (-)^A. -/ def exp.adjunction : prod.functor.obj A ⊣ exp A := closed.is_adj.adj /-- The evaluation natural transformation. -/ def ev : exp A ⋙ prod.functor.obj A ⟶ 𝟭 C := closed.is_adj.adj.counit /-- The coevaluation natural transformation. -/ def coev : 𝟭 C ⟶ prod.functor.obj A ⋙ exp A := closed.is_adj.adj.unit @[simp] lemma exp_adjunction_counit : (exp.adjunction A).counit = ev A := rfl @[simp] lemma exp_adjunction_unit : (exp.adjunction A).unit = coev A := rfl @[simp, reassoc] lemma ev_naturality {X Y : C} (f : X ⟶ Y) : limits.prod.map (𝟙 A) ((exp A).map f) ≫ (ev A).app Y = (ev A).app X ≫ f := (ev A).naturality f @[simp, reassoc] lemma coev_naturality {X Y : C} (f : X ⟶ Y) : f ≫ (coev A).app Y = (coev A).app X ≫ (exp A).map (limits.prod.map (𝟙 A) f) := (coev A).naturality f notation A ` ⟹ `:20 B:20 := (exp A).obj B notation B ` ^^ `:30 A:30 := (exp A).obj B @[simp, reassoc] lemma ev_coev : limits.prod.map (𝟙 A) ((coev A).app B) ≫ (ev A).app (A ⨯ B) = 𝟙 (A ⨯ B) := adjunction.left_triangle_components (exp.adjunction A) @[simp, reassoc] lemma coev_ev : (coev A).app (A⟹B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A⟹B) := adjunction.right_triangle_components (exp.adjunction A) instance : preserves_colimits (prod.functor.obj A) := (exp.adjunction A).left_adjoint_preserves_colimits end exp variables {A} -- Wrap these in a namespace so we don't clash with the core versions. namespace cartesian_closed variables [has_finite_products C] [exponentiable A] /-- Currying in a cartesian closed category. -/ def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) := (closed.is_adj.adj.hom_equiv _ _).to_fun /-- Uncurrying in a cartesian closed category. -/ def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) := (closed.is_adj.adj.hom_equiv _ _).inv_fun end cartesian_closed open cartesian_closed variables [has_finite_products C] [exponentiable A] @[reassoc] lemma curry_natural_left (f : X ⟶ X') (g : A ⨯ X' ⟶ Y) : curry (limits.prod.map (𝟙 _) f ≫ g) = f ≫ curry g := adjunction.hom_equiv_naturality_left _ _ _ @[reassoc] lemma curry_natural_right (f : A ⨯ X ⟶ Y) (g : Y ⟶ Y') : curry (f ≫ g) = curry f ≫ (exp _).map g := adjunction.hom_equiv_naturality_right _ _ _ @[reassoc] lemma uncurry_natural_right (f : X ⟶ A⟹Y) (g : Y ⟶ Y') : uncurry (f ≫ (exp _).map g) = uncurry f ≫ g := adjunction.hom_equiv_naturality_right_symm _ _ _ @[reassoc] lemma uncurry_natural_left (f : X ⟶ X') (g : X' ⟶ A⟹Y) : uncurry (f ≫ g) = limits.prod.map (𝟙 _) f ≫ uncurry g := adjunction.hom_equiv_naturality_left_symm _ _ _ @[simp] lemma uncurry_curry (f : A ⨯ X ⟶ Y) : uncurry (curry f) = f := (closed.is_adj.adj.hom_equiv _ _).left_inv f @[simp] lemma curry_uncurry (f : X ⟶ A⟹Y) : curry (uncurry f) = f := (closed.is_adj.adj.hom_equiv _ _).right_inv f lemma curry_eq_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) : curry f = g ↔ f = uncurry g := adjunction.hom_equiv_apply_eq _ f g lemma eq_curry_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) : g = curry f ↔ uncurry g = f := adjunction.eq_hom_equiv_apply _ f g -- I don't think these two should be simp. lemma uncurry_eq (g : Y ⟶ A ⟹ X) : uncurry g = limits.prod.map (𝟙 A) g ≫ (ev A).app X := adjunction.hom_equiv_counit _ lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (coev A).app Y ≫ (exp A).map g := adjunction.hom_equiv_unit _ lemma uncurry_id_eq_ev (A X : C) [exponentiable A] : uncurry (𝟙 (A ⟹ X)) = (ev A).app X := by rw [uncurry_eq, prod.map_id_id, id_comp] lemma curry_id_eq_coev (A X : C) [exponentiable A] : curry (𝟙 _) = (coev A).app X := by { rw [curry_eq, (exp A).map_id (A ⨯ _)], apply comp_id } lemma curry_injective : function.injective (curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X)) := (closed.is_adj.adj.hom_equiv _ _).injective lemma uncurry_injective : function.injective (uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X)) := (closed.is_adj.adj.hom_equiv _ _).symm.injective /-- Show that the exponential of the terminal object is isomorphic to itself, i.e. `X^1 ≅ X`. The typeclass argument is explicit: any instance can be used. -/ def exp_terminal_iso_self [exponentiable ⊤_C] : (⊤_C ⟹ X) ≅ X := yoneda.ext (⊤_ C ⟹ X) X (λ Y f, (prod.left_unitor Y).inv ≫ uncurry f) (λ Y f, curry ((prod.left_unitor Y).hom ≫ f)) (λ Z g, by rw [curry_eq_iff, iso.hom_inv_id_assoc] ) (λ Z g, by simp) (λ Z W f g, by rw [uncurry_natural_left, prod.left_unitor_inv_naturality_assoc f] ) /-- The internal element which points at the given morphism. -/ def internalize_hom (f : A ⟶ Y) : ⊤_C ⟶ (A ⟹ Y) := curry (limits.prod.fst ≫ f) section pre variables {B} /-- Pre-compose an internal hom with an external hom. -/ def pre (f : B ⟶ A) [exponentiable B] : exp A ⟶ exp B := transfer_nat_trans_self (exp.adjunction _) (exp.adjunction _) (prod.functor.map f) lemma prod_map_pre_app_comp_ev (f : B ⟶ A) [exponentiable B] (X : C) : limits.prod.map (𝟙 B) ((pre f).app X) ≫ (ev B).app X = limits.prod.map f (𝟙 (A ⟹ X)) ≫ (ev A).app X := transfer_nat_trans_self_counit _ _ (prod.functor.map f) X lemma uncurry_pre (f : B ⟶ A) [exponentiable B] (X : C) : uncurry ((pre f).app X) = limits.prod.map f (𝟙 _) ≫ (ev A).app X := begin rw [uncurry_eq, prod_map_pre_app_comp_ev] end lemma coev_app_comp_pre_app (f : B ⟶ A) [exponentiable B] : (coev A).app X ≫ (pre f).app (A ⨯ X) = (coev B).app X ≫ (exp B).map (limits.prod.map f (𝟙 _)) := unit_transfer_nat_trans_self _ _ (prod.functor.map f) X @[simp] lemma pre_id (A : C) [exponentiable A] : pre (𝟙 A) = 𝟙 _ := by simp [pre] @[simp] lemma pre_map {A₁ A₂ A₃ : C} [exponentiable A₁] [exponentiable A₂] [exponentiable A₃] (f : A₁ ⟶ A₂) (g : A₂ ⟶ A₃) : pre (f ≫ g) = pre g ≫ pre f := by rw [pre, pre, pre, transfer_nat_trans_self_comp, prod.functor.map_comp] end pre /-- The internal hom functor given by the cartesian closed structure. -/ def internal_hom [cartesian_closed C] : Cᵒᵖ ⥤ C ⥤ C := { obj := λ X, exp X.unop, map := λ X Y f, pre f.unop } /-- If an initial object `I` exists in a CCC, then `A ⨯ I ≅ I`. -/ @[simps] def zero_mul {I : C} (t : is_initial I) : A ⨯ I ≅ I := { hom := limits.prod.snd, inv := t.to _, hom_inv_id' := begin have: (limits.prod.snd : A ⨯ I ⟶ I) = uncurry (t.to _), rw ← curry_eq_iff, apply t.hom_ext, rw [this, ← uncurry_natural_right, ← eq_curry_iff], apply t.hom_ext, end, inv_hom_id' := t.hom_ext _ _ } /-- If an initial object `0` exists in a CCC, then `0 ⨯ A ≅ 0`. -/ def mul_zero {I : C} (t : is_initial I) : I ⨯ A ≅ I := limits.prod.braiding _ _ ≪≫ zero_mul t /-- If an initial object `0` exists in a CCC then `0^B ≅ 1` for any `B`. -/ def pow_zero {I : C} (t : is_initial I) [cartesian_closed C] : I ⟹ B ≅ ⊤_ C := { hom := default _, inv := curry ((mul_zero t).hom ≫ t.to _), hom_inv_id' := begin rw [← curry_natural_left, curry_eq_iff, ← cancel_epi (mul_zero t).inv], { apply t.hom_ext }, { apply_instance }, { apply_instance } end } -- TODO: Generalise the below to its commutated variants. -- TODO: Define a distributive category, so that zero_mul and friends can be derived from this. /-- In a CCC with binary coproducts, the distribution morphism is an isomorphism. -/ def prod_coprod_distrib [has_binary_coproducts C] [cartesian_closed C] (X Y Z : C) : (Z ⨯ X) ⨿ (Z ⨯ Y) ≅ Z ⨯ (X ⨿ Y) := { hom := coprod.desc (limits.prod.map (𝟙 _) coprod.inl) (limits.prod.map (𝟙 _) coprod.inr), inv := uncurry (coprod.desc (curry coprod.inl) (curry coprod.inr)), hom_inv_id' := begin apply coprod.hom_ext, rw [coprod.inl_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inl_desc, uncurry_curry], rw [coprod.inr_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inr_desc, uncurry_curry], end, inv_hom_id' := begin rw [← uncurry_natural_right, ←eq_curry_iff], apply coprod.hom_ext, rw [coprod.inl_desc_assoc, ←curry_natural_right, coprod.inl_desc, ←curry_natural_left, comp_id], rw [coprod.inr_desc_assoc, ←curry_natural_right, coprod.inr_desc, ←curry_natural_left, comp_id], end } /-- If an initial object `I` exists in a CCC then it is a strict initial object, i.e. any morphism to `I` is an iso. This actually shows a slightly stronger version: any morphism to an initial object from an exponentiable object is an isomorphism. -/ def strict_initial {I : C} (t : is_initial I) (f : A ⟶ I) : is_iso f := begin haveI : mono (limits.prod.lift (𝟙 A) f ≫ (zero_mul t).hom) := mono_comp _ _, rw [zero_mul_hom, prod.lift_snd] at _inst, haveI: split_epi f := ⟨t.to _, t.hom_ext _ _⟩, apply is_iso_of_mono_of_split_epi end instance to_initial_is_iso [has_initial C] (f : A ⟶ ⊥_ C) : is_iso f := strict_initial initial_is_initial _ /-- If an initial object `0` exists in a CCC then every morphism from it is monic. -/ lemma initial_mono {I : C} (B : C) (t : is_initial I) [cartesian_closed C] : mono (t.to B) := ⟨λ B g h _, by { haveI := strict_initial t g, haveI := strict_initial t h, exact eq_of_inv_eq_inv (t.hom_ext _ _) }⟩ instance initial.mono_to [has_initial C] (B : C) [cartesian_closed C] : mono (initial.to B) := initial_mono B initial_is_initial variables {D : Type u₂} [category.{v} D] section functor variables [has_finite_products D] /-- Transport the property of being cartesian closed across an equivalence of categories. Note we didn't require any coherence between the choice of finite products here, since we transport along the `prod_comparison` isomorphism. -/ def cartesian_closed_of_equiv (e : C ≌ D) [h : cartesian_closed C] : cartesian_closed D := { closed := λ X, { is_adj := begin haveI q : exponentiable (e.inverse.obj X) := infer_instance, have : is_left_adjoint (prod.functor.obj (e.inverse.obj X)) := q.is_adj, have : e.functor ⋙ prod.functor.obj X ⋙ e.inverse ≅ prod.functor.obj (e.inverse.obj X), apply nat_iso.of_components _ _, intro Y, { apply as_iso (prod_comparison e.inverse X (e.functor.obj Y)) ≪≫ _, apply prod.map_iso (iso.refl _) (e.unit_iso.app Y).symm }, { intros Y Z g, dsimp [prod_comparison], simp [prod.comp_lift, ← e.inverse.map_comp, ← e.inverse.map_comp_assoc], -- I wonder if it would be a good idea to make `map_comp` a simp lemma the other way round dsimp, simp -- See note [dsimp, simp] }, { have : is_left_adjoint (e.functor ⋙ prod.functor.obj X ⋙ e.inverse) := by exactI adjunction.left_adjoint_of_nat_iso this.symm, have : is_left_adjoint (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) := by exactI adjunction.left_adjoint_of_comp e.inverse _, have : (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) ⋙ e.functor ≅ prod.functor.obj X, { apply iso_whisker_right e.counit_iso (prod.functor.obj X ⋙ e.inverse ⋙ e.functor) ≪≫ _, change prod.functor.obj X ⋙ e.inverse ⋙ e.functor ≅ prod.functor.obj X, apply iso_whisker_left (prod.functor.obj X) e.counit_iso, }, resetI, apply adjunction.left_adjoint_of_nat_iso this }, end } } variables [cartesian_closed C] [cartesian_closed D] variables (F : C ⥤ D) [preserves_limits_of_shape (discrete walking_pair) F] /-- The exponential comparison map. `F` is a cartesian closed functor if this is an iso for all `A,B`. -/ def exp_comparison (A B : C) : F.obj (A ⟹ B) ⟶ F.obj A ⟹ F.obj B := curry (inv (prod_comparison F A _) ≫ F.map ((ev _).app _)) /-- The exponential comparison map is natural in its left argument. -/ lemma exp_comparison_natural_left (A A' B : C) (f : A' ⟶ A) : exp_comparison F A B ≫ (pre (F.map f)).app (F.obj B) = F.map ((pre f).app B) ≫ exp_comparison F A' B := begin rw [exp_comparison, exp_comparison, ←curry_natural_left, eq_curry_iff, uncurry_natural_left, uncurry_pre, prod.map_swap_assoc, curry_eq, prod.map_id_comp, assoc, ev_naturality], dsimp only [prod.functor_obj_obj], rw [ev_coev_assoc, ← F.map_id, ← F.map_id, ← prod_comparison_inv_natural_assoc, ← prod_comparison_inv_natural_assoc, ← F.map_comp, ← F.map_comp, prod_map_pre_app_comp_ev], end /-- The exponential comparison map is natural in its right argument. -/ lemma exp_comparison_natural_right (A B B' : C) (f : B ⟶ B') : exp_comparison F A B ≫ (exp (F.obj A)).map (F.map f) = F.map ((exp A).map f) ≫ exp_comparison F A B' := by erw [exp_comparison, ← curry_natural_right, curry_eq_iff, exp_comparison, uncurry_natural_left, uncurry_curry, assoc, ← F.map_comp, ← (ev _).naturality, F.map_comp, prod_comparison_inv_natural_assoc, F.map_id] -- TODO: If F has a left adjoint L, then F is cartesian closed if and only if -- L (B ⨯ F A) ⟶ L B ⨯ L F A ⟶ L B ⨯ A -- is an iso for all A ∈ D, B ∈ C. -- Corollary: If F has a left adjoint L which preserves finite products, F is cartesian closed iff -- F is full and faithful. end functor end category_theory
4208a60f526300e09450f27d7476942f819899b0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/witt_vector/compare.lean
ed9d52b5883c9a9192a177da32f27e31f5d8a835
[ "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
8,297
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import ring_theory.witt_vector.truncated import ring_theory.witt_vector.identities import number_theory.padics.ring_homs /-! # Comparison isomorphism between `witt_vector p (zmod p)` and `ℤ_[p]` We construct a ring isomorphism between `witt_vector p (zmod p)` and `ℤ_[p]`. This isomorphism follows from the fact that both satisfy the universal property of the inverse limit of `zmod (p^n)`. ## Main declarations * `witt_vector.to_zmod_pow`: a family of compatible ring homs `𝕎 (zmod p) → zmod (p^k)` * `witt_vector.equiv`: the isomorphism ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ noncomputable theory variables {p : ℕ} [hp : fact p.prime] local notation `𝕎` := witt_vector p include hp namespace truncated_witt_vector variables (p) (n : ℕ) (R : Type*) [comm_ring R] lemma eq_of_le_of_cast_pow_eq_zero [char_p R p] (i : ℕ) (hin : i ≤ n) (hpi : (p ^ i : truncated_witt_vector p n R) = 0) : i = n := begin contrapose! hpi, replace hin := lt_of_le_of_ne hin hpi, clear hpi, have : (↑p ^ i : truncated_witt_vector p n R) = witt_vector.truncate n (↑p ^ i), { rw [ring_hom.map_pow, ring_hom.map_nat_cast] }, rw [this, ext_iff, not_forall], clear this, use ⟨i, hin⟩, rw [witt_vector.coeff_truncate, coeff_zero, fin.coe_mk, witt_vector.coeff_p_pow], haveI : nontrivial R := char_p.nontrivial_of_char_ne_one hp.1.ne_one, exact one_ne_zero end section iso variables (p n) {R} lemma card_zmod : fintype.card (truncated_witt_vector p n (zmod p)) = p ^ n := by rw [card, zmod.card] lemma char_p_zmod : char_p (truncated_witt_vector p n (zmod p)) (p ^ n) := char_p_of_prime_pow_injective _ _ _ (card_zmod _ _) (eq_of_le_of_cast_pow_eq_zero p n (zmod p)) local attribute [instance] char_p_zmod /-- The unique isomorphism between `zmod p^n` and `truncated_witt_vector p n (zmod p)`. This isomorphism exists, because `truncated_witt_vector p n (zmod p)` is a finite ring with characteristic and cardinality `p^n`. -/ def zmod_equiv_trunc : zmod (p^n) ≃+* truncated_witt_vector p n (zmod p) := zmod.ring_equiv (truncated_witt_vector p n (zmod p)) (card_zmod _ _) lemma zmod_equiv_trunc_apply {x : zmod (p^n)} : zmod_equiv_trunc p n x = zmod.cast_hom (by refl) (truncated_witt_vector p n (zmod p)) x := rfl /-- The following diagram commutes: ```text zmod (p^n) ----------------------------> zmod (p^m) | | | | v v truncated_witt_vector p n (zmod p) ----> truncated_witt_vector p m (zmod p) ``` Here the vertical arrows are `truncated_witt_vector.zmod_equiv_trunc`, the horizontal arrow at the top is `zmod.cast_hom`, and the horizontal arrow at the bottom is `truncated_witt_vector.truncate`. -/ lemma commutes {m : ℕ} (hm : n ≤ m) : (truncate hm).comp (zmod_equiv_trunc p m).to_ring_hom = (zmod_equiv_trunc p n).to_ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hm) _) := ring_hom.ext_zmod _ _ lemma commutes' {m : ℕ} (hm : n ≤ m) (x : zmod (p^m)) : truncate hm (zmod_equiv_trunc p m x) = zmod_equiv_trunc p n (zmod.cast_hom (pow_dvd_pow p hm) _ x) := show (truncate hm).comp (zmod_equiv_trunc p m).to_ring_hom x = _, by rw commutes _ _ hm; refl lemma commutes_symm' {m : ℕ} (hm : n ≤ m) (x : truncated_witt_vector p m (zmod p)) : (zmod_equiv_trunc p n).symm (truncate hm x) = zmod.cast_hom (pow_dvd_pow p hm) _ ((zmod_equiv_trunc p m).symm x) := begin apply (zmod_equiv_trunc p n).injective, rw ← commutes', simp end /-- The following diagram commutes: ```text truncated_witt_vector p n (zmod p) ----> truncated_witt_vector p m (zmod p) | | | | v v zmod (p^n) ----------------------------> zmod (p^m) ``` Here the vertical arrows are `(truncated_witt_vector.zmod_equiv_trunc p _).symm`, the horizontal arrow at the top is `zmod.cast_hom`, and the horizontal arrow at the bottom is `truncated_witt_vector.truncate`. -/ lemma commutes_symm {m : ℕ} (hm : n ≤ m) : (zmod_equiv_trunc p n).symm.to_ring_hom.comp (truncate hm) = (zmod.cast_hom (pow_dvd_pow p hm) _).comp (zmod_equiv_trunc p m).symm.to_ring_hom := by ext; apply commutes_symm' end iso end truncated_witt_vector namespace witt_vector open truncated_witt_vector variables (p) /-- `to_zmod_pow` is a family of compatible ring homs. We get this family by composing `truncated_witt_vector.zmod_equiv_trunc` (in right-to-left direction) with `witt_vector.truncate`. -/ def to_zmod_pow (k : ℕ) : 𝕎 (zmod p) →+* zmod (p ^ k) := (zmod_equiv_trunc p k).symm.to_ring_hom.comp (truncate k) lemma to_zmod_pow_compat (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow p n) = to_zmod_pow p m := calc (zmod.cast_hom _ (zmod (p ^ m))).comp ((zmod_equiv_trunc p n).symm.to_ring_hom.comp (truncate n)) = ((zmod_equiv_trunc p m).symm.to_ring_hom.comp (truncated_witt_vector.truncate h)).comp (truncate n) : by rw [commutes_symm, ring_hom.comp_assoc] ... = (zmod_equiv_trunc p m).symm.to_ring_hom.comp (truncate m) : by rw [ring_hom.comp_assoc, truncate_comp_witt_vector_truncate] /-- `to_padic_int` lifts `to_zmod_pow : 𝕎 (zmod p) →+* zmod (p ^ k)` to a ring hom to `ℤ_[p]` using `padic_int.lift`, the universal property of `ℤ_[p]`. -/ def to_padic_int : 𝕎 (zmod p) →+* ℤ_[p] := padic_int.lift $ to_zmod_pow_compat p lemma zmod_equiv_trunc_compat (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂) : (truncated_witt_vector.truncate hk).comp ((zmod_equiv_trunc p k₂).to_ring_hom.comp (padic_int.to_zmod_pow k₂)) = (zmod_equiv_trunc p k₁).to_ring_hom.comp (padic_int.to_zmod_pow k₁) := by rw [← ring_hom.comp_assoc, commutes, ring_hom.comp_assoc, padic_int.zmod_cast_comp_to_zmod_pow] /-- `from_padic_int` uses `witt_vector.lift` to lift `truncated_witt_vector.zmod_equiv_trunc` composed with `padic_int.to_zmod_pow` to a ring hom `ℤ_[p] →+* 𝕎 (zmod p)`. -/ def from_padic_int : ℤ_[p] →+* 𝕎 (zmod p) := witt_vector.lift (λ k, (zmod_equiv_trunc p k).to_ring_hom.comp (padic_int.to_zmod_pow k)) $ zmod_equiv_trunc_compat _ lemma to_padic_int_comp_from_padic_int : (to_padic_int p).comp (from_padic_int p) = ring_hom.id ℤ_[p] := begin rw ← padic_int.to_zmod_pow_eq_iff_ext, intro n, rw [← ring_hom.comp_assoc, to_padic_int, padic_int.lift_spec], simp only [from_padic_int, to_zmod_pow, ring_hom.comp_id], rw [ring_hom.comp_assoc, truncate_comp_lift, ← ring_hom.comp_assoc], simp only [ring_equiv.symm_to_ring_hom_comp_to_ring_hom, ring_hom.id_comp] end lemma to_padic_int_comp_from_padic_int_ext (x) : (to_padic_int p).comp (from_padic_int p) x = ring_hom.id ℤ_[p] x := by rw to_padic_int_comp_from_padic_int lemma from_padic_int_comp_to_padic_int : (from_padic_int p).comp (to_padic_int p) = ring_hom.id (𝕎 (zmod p)) := begin apply witt_vector.hom_ext, intro n, rw [from_padic_int, ← ring_hom.comp_assoc, truncate_comp_lift, ring_hom.comp_assoc], simp only [to_padic_int, to_zmod_pow, ring_hom.comp_id, padic_int.lift_spec, ring_hom.id_comp, ← ring_hom.comp_assoc, ring_equiv.to_ring_hom_comp_symm_to_ring_hom] end lemma from_padic_int_comp_to_padic_int_ext (x) : (from_padic_int p).comp (to_padic_int p) x = ring_hom.id (𝕎 (zmod p)) x := by rw from_padic_int_comp_to_padic_int /-- The ring of Witt vectors over `zmod p` is isomorphic to the ring of `p`-adic integers. This equivalence is witnessed by `witt_vector.to_padic_int` with inverse `witt_vector.from_padic_int`. -/ def equiv : 𝕎 (zmod p) ≃+* ℤ_[p] := { to_fun := to_padic_int p, inv_fun := from_padic_int p, left_inv := from_padic_int_comp_to_padic_int_ext _, right_inv := to_padic_int_comp_from_padic_int_ext _, map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _ } end witt_vector
953f62bee467e0ce6a1bf5c13b805e2a76ee4e97
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/solutions/wednesday/structures.lean
4977c81d3de1bb1a2f09f37a426216c469721666
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,490
lean
import data.rat.basic import data.nat.parity import tactic.basic open nat noncomputable theory -- definitions are allowed to not compute in this file open_locale classical -- use classical logic in this file /-! ## Structures and Classes In this session we will discuss structures together, and then you can solve the exercises yourself. Before we start, run the following in a terminal: ``` cd /path/to/lftcm2020/ git pull leanproject get-mathlib-cache ``` If `git pull` didn't work because you edited one of the files in the repository, first copy the files to a backup version and then run `git checkout -- .` (this will remove all changes to files you edited, so be careful!) ### Declaring a Structure Structures are a way to bundle information together. For example, the first example below makes a new structure `even_natural_number`, which consists of pairs, where the first component is a natural number, and the second component is a proof that the natural number is even. These are called the *fields* of the structure. -/ structure even_natural_number : Type := (n : ℕ) (even_n : even n) /-! We can also group propositions together, for example this is a proposition stating that `n` is an even cube greater than 100. Note that this is a property of a natural number, while the previous structure was a natural number with a property "bundled" together. -/ structure is_even_cube_above_100 (n : ℕ) : Prop := (even : even n) (is_cube : ∃ k, n = k^3) (gt_100 : n > 100) /-! Here we give the upper bounds for a function `f`. We can omit the type of the structure. -/ structure bounds (f : ℕ → ℕ) := (bound : ℕ) (le_bound : ∀ (n : ℕ), f n ≤ bound) /-! You can use `#print` to print the type and all fields of a structure. -/ #print even_natural_number #print is_even_cube_above_100 #print bounds /-! ### Exercise 1 * Define a structure of eventually constant sequences `ℕ → ℕ`. The first field will be `seq : ℕ → ℕ`, and the second field will be the statement that `seq` is eventually constant. * Define a structure of a type with 2 points that are unequal. (hint: omit the type of the structure, Lean might complain if you give it explicitly) Lean will not tell you if you got the right definition, but it will complain if you make a syntax error. If you are unsure, ask a mentor to check whether your solution is correct. -/ -- omit /- There are different ways to do these, here is one way. -/ structure eventually_constant_sequence : Type := (seq : ℕ → ℕ) (eventually_constant : ∃ k v, ∀ n ≥ k, seq n = v) structure bipointed_type := (A : Type) (x y : A) (x_ne_y : x ≠ y) -- omit /-! ### Projections of a structure -/ /-! The field names are declared in the namespace of the structure. This means that their names have the form `<structure_name>.<field_name>`. -/ example (n : ℕ) (hn : is_even_cube_above_100 n) : n > 100 := is_even_cube_above_100.gt_100 hn /-! You can also `open` the namespace, to use the abbreviated form. We put this `open` command inside a section, so that the namespace is closed at the end of the `section`. -/ section open is_even_cube_above_100 example (n : ℕ) (hn : is_even_cube_above_100 n) : n > 100 := gt_100 hn end /-! Another useful technique is to use *projection notation*. Instead of writing `is_even_cube_above_100.even hn` we can write `hn.even`. Lean will look at the type of `hn` and see that it is `is_even_cube_above_100 n`. Then it looks for the lemma with the name `is_even_cube_above_100.even` and apply it to `hn`. -/ example (n : ℕ) (hn : is_even_cube_above_100 n) : even n := hn.even example (n : ℕ) (hn : is_even_cube_above_100 n) : even n ∧ ∃ k, n = k^3 := ⟨ hn.even, hn.is_cube ⟩ /-! You can also use `.1`, `.2`, `.3`, ... for the fields of a structure. -/ example (n : ℕ) (hn : is_even_cube_above_100 n) : even n ∧ n > 100 ∧ (∃ k, n = k^3) := ⟨ hn.1, hn.3, hn.2 ⟩ /-! We could have alternatively stated `is_even_cube_above_100` as a conjunction of three statements, as below. That gives the same proposition, but doesn't give a name to the three components. -/ def is_even_cube_above_100' (n : ℕ) : Prop := even n ∧ (∃ k, n = k^3) ∧ n > 100 /-! If we have a structure that mixes data (elements of types, like `ℕ`, `ℝ`, and so on) and properties of the data, we can alternatively declare them using *subtypes*. This consists of pairs of a natural number and a proof that the natural number is even. -/ def even_natural_number' : Type := { n : ℕ // even n } /-! The notation for subtypes is almost the same as the notation for set comprehension. Note that `//` is used for subtypes, and `|` is used for sets. -/ def set_of_even_natural_numbers : set ℕ := { n : ℕ | even n } /-! We can construct objects of a structure using the *anonymous constructor* `⟨...⟩`. This can construct an object of any structure, including conjunctions, existential statements and subtypes. -/ example : even_natural_number → even_natural_number' := λ n, ⟨n.1, n.2⟩ example (n : ℕ) : is_even_cube_above_100 n → is_even_cube_above_100' n := λ hn, ⟨hn.even, hn.is_cube, hn.gt_100⟩ /-! An alternative way is to use the *structure notation*. The syntax for this is ``` { structure_name . field1_name := value, field2_name := value, ... } ``` You can prove the fields in any order you want. -/ example : even_natural_number' → even_natural_number := λ n, { even_natural_number . n := n.1, even_n := n.2 } /-! The structure name is optional if the structure in question is clear from context. -/ example (n : ℕ) : is_even_cube_above_100' n → is_even_cube_above_100 n := λ ⟨h1n, h2n, h3n⟩, { even := h1n, is_cube := h2n, gt_100 := h3n } /-! ### Exercise 2 * Define `bounds` (given above) again, but now using a the subtype notation `{ _ : _ // _ }`. * Define functions back and forth from the structure `bounds` given above and `bounds` given here. Try different variations using the anonymous constructor and the projection notation. -/ #print bounds def bounds' (f : ℕ → ℕ) : Type := /- inline sorry -/ { n : ℕ // ∀ (m : ℕ), f m ≤ n } /- inline sorry -/ example (f : ℕ → ℕ) : bounds f → bounds' f := /- inline sorry -/ λ ⟨n, hn⟩, ⟨n, hn⟩ /- inline sorry -/ /- In the example below, replace the `sorry` by an underscore `_`. A small yellow lightbulb will appear. Click it, and then select `Generate skeleton for the structure under construction`. This will automatically give an outline of the structure for you. -/ example (f : ℕ → ℕ) : bounds' f → bounds f := λ n, /- inline sorry -/ { bound := n.1, le_bound := n.2 } /- inline sorry -/ /-! Before you continue, watch the second pre-recorded video. -/ /-! ### Classes Classes are special kind of types or propositions that Lean will automatically find inhabitants for. You can declare a class by giving it the `@[class]` attribute. As an example, in this section, we will implement square root on natural numbers, that can only be applied to natural numbers that are squares. -/ @[class] def is_square (n : ℕ) : Prop := ∃k : ℕ, k^2 = n namespace is_square /-! Hypotheses with a class as type should be written in square brackets `[...]`. This tells Lean that they are implicit, and Lean will try to fill them in automatically. We define the square root as the (unique) number `k` such that `k^2 = n`. Such `k` exists by the `is_square n` hypothesis. -/ def sqrt (n : ℕ) [hn : is_square n] : ℕ := classical.some hn prefix `√`:(max+1) := sqrt -- notation for `sqrt` /-! The following is the defining property of `√n`. Note that when we write `√n`, Lean will automatically insert the implicit argument `hn` it found it the context. This is called *type-class inference*. We mark this lemma with the `@[simp]` attribute to tell `simp` to simplify using this lemma. -/ @[simp] lemma square_sqrt (n : ℕ) [hn : is_square n] : (√n) ^ 2 = n := classical.some_spec hn /-! ### Exercise: Fill in all `sorry`s in the remainder of this section. -/ /-! Prove this lemma. Again we mark it `@[simp]` so that `simp` can simplify equalities involving `√`. Also, hypotheses in square brackets do not need a name. Hint: use `pow_left_inj` -/ @[simp] lemma sqrt_eq_iff (n k : ℕ) [is_square n] : √n = k ↔ n = k^2 := begin -- sorry split; intro h, { simp [← h] }, { exact pow_left_inj (nat.zero_le _) (nat.zero_le k) zero_lt_two (by simp [h]) } -- sorry end /-! To help type-class inference, we have to tell it that some numbers are always squares. Here we show that `n^2` is always a square. We mark it as `instance`, which is like `lemma` or `def`, except that it is automatically used by type-class inference. -/ instance square_square (n : ℕ) : is_square (n^2) := ⟨n, rfl⟩ lemma sqrt_square (n : ℕ) : √(n ^ 2) = n := by simp /-! Instances can depend on other instances: here we show that if `n` and `m` are squares, then `n * m` is one, too. When writing `√n`, Lean will use a simple search algorithm to find a proof that `n` is a square, by repeatedly applying previously declared instances, and arguments in the local context. -/ instance square_mul (n m : ℕ) [is_square n] [is_square m] : is_square (n*m) := ⟨√n * √m, by simp [mul_pow]⟩ /-! Hint: use `mul_pow` -/ #check mul_pow lemma sqrt_mul (n m : ℕ) [is_square n] [is_square m] : √(n * m) = √n * √m := begin -- sorry simp [mul_pow] -- sorry end /-! Note that Lean automatically inserts the proof that `n * m ^ 2` is a square, using the previously declared instances. -/ example (n m : ℕ) [is_square n] : √(n * m ^ 2) = √n * m := begin -- sorry simp [sqrt_mul, sqrt_square], -- sorry end /-! Hint: use `nat.le_mul_self` and `pow_two` -/ #check nat.le_mul_self #check pow_two lemma sqrt_le (n : ℕ) [is_square n] : √n ≤ n := begin -- sorry conv_rhs { rw [← square_sqrt n, pow_two] }, apply nat.le_mul_self -- sorry end end is_square /- At this point, feel free do the remaining exercises in any order. -/ /-! ### Exercise: Bijections and equivalences -/ section bijections open function variables {α β : Type*} /- An important structure is the type of equivalences, which gives an equivalence (bijection) between two types: ``` structure equiv (α β : Type*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) ``` In this section we show that this is the same as the bijections from `α` to `β`. -/ #print equiv structure bijection (α β : Type*) := (to_fun : α → β) (injective : injective to_fun) (surjective : surjective to_fun) /- We declare a *coercion*. This allows us to treat `f` as a function if `f : bijection α β`. -/ instance : has_coe_to_fun (bijection α β) := ⟨_, λ f, f.to_fun⟩ /-! To show that two bijections are equal, it is sufficient that the underlying functions are equal on all inputs. We mark it as `@[ext]` so that we can later use the tactic `ext` to show that two bijections are equal. -/ @[ext] def bijection.ext {f g : bijection α β} (hfg : ∀ x, f x = g x) : f = g := by { cases f, cases g, congr, ext, exact hfg x } /-! This lemma allows `simp` to reduce the application of a bijection to an argument. -/ @[simp] lemma coe_mk {f : α → β} {h1f : injective f} {h2f : surjective f} {x : α} : { bijection . to_fun := f, injective := h1f, surjective := h2f } x = f x := rfl /- There is a lemma in the library that almost states this. You can use the tactic `suggest` to get suggested lemmas from Lean (the one you want has `bijective` in the name). -/ def equiv_of_bijection (f : bijection α β) : α ≃ β := begin -- sorry exact equiv.of_bijective f ⟨f.injective, f.surjective⟩ -- sorry end def bijection_of_equiv (f : α ≃ β) : bijection α β := -- sorry { to_fun := f, injective := f.injective, surjective := f.surjective } -- sorry /-! Show that bijections are the same (i.e. equivalent) to equivalences. -/ def bijection_equiv_equiv : bijection α β ≃ (α ≃ β) := -- sorry { to_fun := equiv_of_bijection, inv_fun := bijection_of_equiv, left_inv := by { intro f, ext, simp [bijection_of_equiv, equiv_of_bijection] }, right_inv := by { intro f, ext, simp [bijection_of_equiv, equiv_of_bijection] } } -- sorry end bijections /-! ### Exercise: Bundled groups -/ /-! Below is a possible definition of a group in Lean. It's not the definition we use use in mathlib. The actual definition uses classes, and will be explained in detail in the next session. -/ structure Group := (G : Type*) (op : G → G → G) (infix * := op) -- temporary notation `*` for `op`, just inside this structure declaration (op_assoc' : ∀ (x y z : G), (x * y) * z = x * (y * z)) (id : G) (notation 1 := id) -- temporary notation `1` for `id`, just inside this structure declaration (id_op' : ∀ (x : G), 1 * x = x) (inv : G → G) (postfix ⁻¹ := inv) -- temporary notation `⁻¹` for `inv`, just inside this structure declaration (op_left_inv' : ∀ (x : G), x⁻¹ * x = 1) /-! You can use the `extend` command to define a structure that adds fields to one or more existing structures. -/ structure CommGroup extends Group := (infix * := op) (op_comm : ∀ (x y : G), x * y = y * x) /- Here is an example: the rationals form a group under addition. -/ def rat_Group : Group := { G := ℚ, op := (+), -- you can put parentheses around an infix operation to talk about the operation itself. op_assoc' := add_assoc, id := 0, id_op' := zero_add, inv := λ x, -x, op_left_inv' := neg_add_self } /-- You can extend an object of a structure by using the structure notation and using `..<existing object>`. -/ def rat_CommGroup : CommGroup := { G := ℚ, op_comm := add_comm, ..rat_Group } namespace Group variables {G : Group} /- Let `G` be a group -/ /- The following line declares that if `G : Group`, then we can also view `G` as a type. -/ instance : has_coe_to_sort Group := ⟨_, Group.G⟩ /- The following lines declare the notation `*`, `⁻¹` and `1` for the fields of `Group`. -/ instance : has_mul G := ⟨G.op⟩ instance : has_inv G := ⟨G.inv⟩ instance : has_one G := ⟨G.id⟩ /- the axioms for groups are satisfied -/ lemma op_assoc (x y z : G) : (x * y) * z = x * (y * z) := G.op_assoc' x y z lemma id_op (x : G) : 1 * x = x := G.id_op' x lemma op_left_inv (x : G) : x⁻¹ * x = 1 := G.op_left_inv' x /- Use the axioms `op_assoc`, `id_op` and `op_left_inv` to prove the following lemma. The fields `op_assoc'`, `id_op'` and `op_left_inv'` should not be used directly, nor can you use any lemmas from the library about `mul`. -/ lemma eq_id_of_op_eq_self {G : Group} {x : G} : x * x = x → x = 1 := begin -- sorry intro hx, rw [←id_op x, ← op_left_inv x, op_assoc, hx] -- sorry end /- Apply the previous lemma to show that `⁻¹` is also a right-sided inverse. -/ lemma op_right_inv {G : Group} (x : G) : x * x⁻¹ = 1 := begin -- sorry apply eq_id_of_op_eq_self, rw [op_assoc x x⁻¹ (x * x⁻¹), ← op_assoc x⁻¹ x x⁻¹, op_left_inv, id_op] -- sorry end /- we can prove that `1` is also a right identity. -/ lemma op_id {G : Group} (x : G) : x * 1 = x := begin -- sorry rw [← op_left_inv x, ← op_assoc, op_right_inv, id_op] -- sorry end /-! However, it is inconvenient to use this group instance directly. One reason is that to use these group operations we now have to write `(x y : rat_Group)` instead of `(x y : ℚ)`. That's why in Lean we use classes for algebraic structures, explained in the next lecture. -/ /- show that the cartesian product of two groups is a group. The underlying type will be `G × H`. -/ def prod_Group (G H : Group) : Group := -- sorry { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc' := by { intros, ext; simp; rw [op_assoc] }, id := (1, 1), id_op' := by { intros, ext; simp; rw [id_op] }, inv := λ x, (x.1⁻¹, x.2⁻¹), op_left_inv' := by { intros, ext; simp; rw [op_left_inv] } } -- sorry end Group /-! ### Exercise: Pointed types -/ structure pointed_type := (type : Type*) (point : type) namespace pointed_type variables {A B : pointed_type} /- The following line declares that if `A : pointed_type`, then we can also view `A` as a type. -/ instance : has_coe_to_sort pointed_type := ⟨_, pointed_type.type⟩ /- The product of two pointed types is a pointed type. The `@[simps point]` is a hint to `simp` that it can unfold the point of this definition. -/ @[simps point] def prod (A B : pointed_type) : pointed_type := { type := A × B, point := (A.point, B.point) } end pointed_type structure pointed_map (A B : pointed_type) := (to_fun : A → B) (to_fun_point : to_fun A.point = B.point) namespace pointed_map infix ` →. `:25 := pointed_map variables {A B C D : pointed_type} variables {h : C →. D} {g : B →. C} {f f₁ f₂ : A →. B} instance : has_coe_to_fun (A →. B) := ⟨λ _, A → B, pointed_map.to_fun⟩ @[simp] lemma coe_mk {f : A → B} {hf : f A.point = B.point} {x : A} : { pointed_map . to_fun := f, to_fun_point := hf } x = f x := rfl @[simp] lemma coe_point : f A.point = B.point := f.to_fun_point @[ext] protected lemma ext (hf₁₂ : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := begin -- sorry cases f₁ with f₁ hf₁, cases f₂ with f₂ hf₂, congr, ext x, exact hf₁₂ x -- sorry end /-! Below we show that pointed types form a category. -/ def comp (g : B →. C) (f : A →. B) : A →. C := -- sorry { to_fun := g ∘ f, to_fun_point := by simp } -- sorry def id : A →. A := -- sorry { to_fun := id, to_fun_point := by simp } -- sorry /-! You can use projection notation for any declaration declared in the same namespace as the structure. For example, `g.comp f` means `pointed_map.comp g f` -/ lemma comp_assoc : h.comp (g.comp f) = (h.comp g).comp f := -- sorry by { ext x, refl } -- sorry lemma id_comp : f.comp id = f := -- sorry by { ext x, refl } -- sorry lemma comp_id : id.comp f = f := -- sorry by { ext x, refl } -- sorry /-! Below we show that `A.prod B` (that is, `pointed_type.prod A B`) is a product in the category of pointed types. -/ def fst : A.prod B →. A := -- sorry { to_fun := prod.fst, to_fun_point := rfl } -- sorry def snd : A.prod B →. B := -- sorry { to_fun := prod.snd, to_fun_point := rfl } -- sorry def pair (f : C →. A) (g : C →. B) : C →. A.prod B := -- sorry { to_fun := λ c, (f c, g c), to_fun_point := by simp } -- sorry lemma fst_pair (f : C →. A) (g : C →. B) : fst.comp (f.pair g) = f := -- sorry by { ext, simp [pair, fst, comp] } -- sorry lemma snd_pair (f : C →. A) (g : C →. B) : snd.comp (f.pair g) = g := -- sorry by { ext, simp [pair, snd, comp] } -- sorry lemma pair_unique (f : C →. A) (g : C →. B) (u : C →. A.prod B) (h1u : fst.comp u = f) (h2u : snd.comp u = g) : u = f.pair g := begin -- sorry ext, { have : fst (u x) = f x, { rw [←h1u], simp [comp] }, simpa using this }, { have : snd (u x) = g x, { rw [←h2u], simp [comp] }, simpa using this } -- sorry end end pointed_map /-! As an advanced exercise, you can show that the category of pointed type has coproducts. For this we need quotients, the basic interface is given with the declarations `quot r`: the quotient of the equivalence relation generated by relation `r` on `A` `quot.mk r : A → quot r`, `quot.sound` `quot.lift` (see below) -/ #print quot #print quot.mk #print quot.sound #print quot.lift open sum /-! We want to define the coproduct of pointed types `A` and `B` as the coproduct `A ⊕ B` of the underlying type, identifying the two basepoints. First define a relation that *only* relates `inl A.point ~ inr B.point`. -/ def coprod_rel (A B : pointed_type) : (A ⊕ B) → (A ⊕ B) → Prop := -- sorry λ x y, x = inl A.point ∧ y = inr B.point -- sorry namespace pointed_type -- @[simps point] -- omit @[simps point] -- omit def coprod (A B : pointed_type) : pointed_type := -- sorry { type := quot (coprod_rel A B), point := quot.mk _ (inl A.point) } -- sorry end pointed_type namespace pointed_map variables {A B C D : pointed_type} def inl : A →. A.coprod B := -- sorry { to_fun := quot.mk _ ∘ sum.inl, to_fun_point := rfl } -- sorry def inr : B →. A.coprod B := -- sorry { to_fun := quot.mk _ ∘ sum.inr, to_fun_point := by { refine (quot.sound _).symm, exact ⟨rfl, rfl⟩ } } -- sorry def elim (f : A →. C) (g : B →. C) : A.coprod B →. C := -- sorry { to_fun := quot.lift (sum.elim f g) (by { rintro _ _ ⟨rfl, rfl⟩, simp }), to_fun_point := by simp } -- sorry lemma elim_comp_inl (f : A →. C) (g : B →. C) : (f.elim g).comp inl = f := -- sorry by { ext, simp [elim, inl, comp] } -- sorry lemma elim_comp_inr (f : A →. C) (g : B →. C) : (f.elim g).comp inr = g := -- sorry by { ext, simp [elim, inr, comp] } -- sorry lemma elim_unique (f : A →. C) (g : B →. C) (u : A.coprod B →. C) (h1u : u.comp inl = f) (h2u : u.comp inr = g) : u = f.elim g := begin -- sorry ext (x|y), { have : u (inl x) = f x, { rw [←h1u], simp [comp] }, simpa [elim, inl] using this }, { have : u (inr y) = g y, { rw [←h2u], simp [comp] }, simpa [elim, inl] using this } -- sorry end end pointed_map
231569ca8816deaa72aa9cc784cbd1a66d686e7f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/dedekind_domain/integral_closure.lean
46cabb9b4bb3e2bb4fade4b809fc9c0de8926904
[ "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
10,254
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.dedekind_domain.basic import ring_theory.trace /-! # Integral closure of Dedekind domains This file shows the integral closure of a Dedekind domain (in particular, the ring of integers of a number field) is a Dedekind domain. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors polynomial variables [is_domain A] section is_integral_closure /-! ### `is_integral_closure` section We show that an integral closure of a Dedekind domain in a finite separable field extension is again a Dedekind domain. This implies the ring of integers of a number field is a Dedekind domain. -/ open algebra open_locale big_operators variables {A K} [algebra A K] [is_fraction_ring A K] variables {L : Type*} [field L] (C : Type*) [comm_ring C] variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L] variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L] lemma is_integral_closure.range_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : ((algebra.linear_map C L).restrict_scalars A).range ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, rintros _ ⟨x, rfl⟩, simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply], have hx : is_integral A (algebra_map C L x) := (is_integral_closure.is_integral A L x).algebra_map, rsuffices ⟨c, x_eq⟩ : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i, { rw x_eq, refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)), rw set.mem_range, exact ⟨i, rfl⟩ }, suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i), { obtain ⟨c, hc, hx⟩ := this, have hc' : ∀ i, is_localization.is_integer A (c i) := λ i, is_integrally_closed.is_integral_iff.mp (hc i), use λ i, classical.some (hc' i), refine hx.trans (finset.sum_congr rfl (λ i _, _)), conv_lhs { rw [← classical.some_spec (hc' i)] }, rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] }, refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩, rw bilin_form.dual_basis_repr_apply, exact is_integral_trace (is_integral_mul hx (hb_int i)) end lemma integral_closure_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : (integral_closure A L).to_submodule ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int), intros x hx, exact ⟨⟨x, hx⟩, rfl⟩ end variables (A) (K) include K /-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R` to `(y : R) • x ∈ integral_closure R L`. -/ lemma exists_integral_multiples (s : finset L) : ∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) := begin haveI := classical.dec_eq L, refine s.induction _ _, { use [1, one_ne_zero], rintros x ⟨⟩ }, { rintros x s hx ⟨y, hy, hs⟩, obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple ((is_fraction_ring.is_algebraic_iff A K L).mpr (is_algebraic_of_finite _ _ x)) ((injective_iff_map_eq_zero (algebra_map A L)).mp _), refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩, rcases finset.mem_insert.mp hx'' with (rfl | hx''), { rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'], exact is_integral_mul is_integral_algebra_map x'.2 }, { rw [mul_comm, mul_smul, algebra.smul_def], exact is_integral_mul is_integral_algebra_map (hs _ hx'') }, { rw is_scalar_tower.algebra_map_eq A K L, apply (algebra_map K L).injective.comp, exact is_fraction_ring.injective _ _ } } end variables (L) /-- If `L` is a finite extension of `K = Frac(A)`, then `L` has a basis over `A` consisting of integral elements. -/ lemma finite_dimensional.exists_is_basis_integral : ∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) := begin letI := classical.dec_eq L, letI : is_noetherian K L := is_noetherian.iff_fg.2 infer_instance, let s' := is_noetherian.finset_basis_index K L, let bs' := is_noetherian.finset_basis K L, obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'), have hy' : algebra_map A L y ≠ 0, { refine mt ((injective_iff_map_eq_zero (algebra_map A L)).mp _ _) hy, rw is_scalar_tower.algebra_map_eq A K L, exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) }, refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x, inv_fun := λ x, (algebra_map A L y)⁻¹ * x, left_inv := _, right_inv := _, .. algebra.lmul _ _ (algebra_map A L y) }, _⟩, { intros x, simp only [inv_mul_cancel_left₀ hy'] }, { intros x, simp only [mul_inv_cancel_left₀ hy'] }, { rintros ⟨x', hx'⟩, simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his', simp only [basis.map_apply, linear_equiv.coe_mk], exact his' _ ⟨_, rfl⟩ } end variables (A K L) [is_separable K L] include L /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian over `A`. -/ lemma is_integral_closure.is_noetherian [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian A C := begin haveI := classical.dec_eq L, obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L, let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, letI := is_noetherian_span_of_finite A (set.finite_range b'), let f : C →ₗ[A] submodule.span A (set.range b') := (submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp ((algebra.linear_map C L).restrict_scalars A).range_restrict, refine is_noetherian_of_ker_bot f _, rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict], exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L) end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian. -/ lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring C := is_noetherian_ring_iff.mpr $ is_noetherian_of_tower A (is_integral_closure.is_noetherian A K L C) variables {A K} /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure of `A` in `L` is Noetherian. -/ lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring (integral_closure A L) := is_integral_closure.is_noetherian_ring A K L (integral_closure A L) variables (A K) [is_domain C] /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure `C` of `A` in `L` is a Dedekind domain. Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A` and `C := integral_closure A L`. -/ lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain C := begin haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C, exact ⟨is_integral_closure.is_noetherian_ring A K L C, h.dimension_le_one.is_integral_closure _ L _, (is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x (is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx), is_integral_closure.algebra_map_mk' _ _ _⟩)⟩ end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. Can't be an instance since `K` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`. -/ lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := is_integral_closure.is_dedekind_domain A K L (integral_closure A L) omit K variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L] variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L] /- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. See also the lemma `integral_closure.is_dedekind_domain` where you can choose the field of fractions yourself. -/ instance integral_closure.is_dedekind_domain_fraction_ring [is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := integral_closure.is_dedekind_domain A (fraction_ring A) L end is_integral_closure
bb7990e83d6133817368520ecb559242599ef014
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/tools/debugger/cli.lean
2db09e4ad16c6e16db098e03605d812ba900044c
[]
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
728
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 Simple command line interface for debugging Lean programs and tactics. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.tools.debugger.util universes l namespace Mathlib namespace debugger inductive mode where | init : mode | step : mode | run : mode | done : mode structure state where md : mode csz : ℕ fn_bps : List name active_bps : List (ℕ × name) def init_state : state := state.mk mode.init 0 [] [] def prune_active_bps_core (csz : ℕ) : List (ℕ × name) → List (ℕ × name) := sorry
235643f38a9237edeb00c9628fbf5435e5c345ec
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/pp_struct.lean
c6ddd0d5c7e44e830b71e7bba18d823cd0bd1e6c
[ "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
1,241
lean
structure foo := (x : nat) (y : nat) (z : bool) check let s := {foo . x := let v1 := 10 + 10 + 20 + 30 + 40 + 10 + 20 + 30 + 40 + 50 + 10 + 10, v2 := 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 20, v3 := 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 20, v4 := 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 20 in v1 + v2 + v3 + v4, y := 20, z := tt} in s^.x + s^.y set_option pp.structure_instances_qualifier true check let s := {foo . x := let v1 := 10 + 10 + 20 + 30 + 40 + 10 + 20 + 30 + 40 + 50 + 10 + 10, v2 := 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 20, v3 := 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 20, v4 := 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 10 + 20 in v1 + v2 + v3 + v4, y := 20, z := tt} in s^.x + s^.y set_option pp.structure_instances false check {foo . x := 10, y := 20, z := ff} set_option pp.structure_instances true check {foo . x := 10, y := 20, z := ff} set_option pp.structure_instances_qualifier false check {foo . x := 10, y := 20, z := ff} check {foo . x := 10, y := 20, z := ff}^.x check (1, 2).1 constant boo : nat → nat → nat × nat check (boo 1 1)^.fst structure F := (fn : nat → nat → nat) (v : nat) constant h : nat → F check (h 0)^.fn 10 20
f4aed24d69b4b81549b86a632d3bb12bcfccd2ff
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/theories/measure_theory/extended_real.lean
62c353b2c2fd085e50b0a89c1f424e74a49f7814
[ "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
15,806
lean
/- Copyright (c) 2015 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad Extended reals. -/ import data.real open real eq.ops classical -- This is a hack, to get around the fact that the top level names are inaccessible when -- defining these theorems in the ereal namespace. Is there a better way? private definition zero_mul' := @zero_mul private definition mul_zero' := @mul_zero private definition neg_neg' := @neg_neg noncomputable theory inductive ereal : Type := | of_real : ℝ → ereal | infty : ereal | neginfty : ereal attribute ereal.of_real [coercion] notation `∞` := ereal.infty notation `-∞` := ereal.neginfty namespace ereal protected definition prio := num.pred real.prio /- arithmetic operations on the ereals -/ definition ereal_has_zero [instance] [priority ereal.prio] : has_zero ereal := has_zero.mk (of_real 0) definition ereal_has_one [instance] [priority ereal.prio] : has_one ereal := has_one.mk (of_real 1) protected definition add : ereal → ereal → ereal | (of_real x) (of_real y) := of_real (x + y) | ∞ _ := ∞ | _ ∞ := ∞ | -∞ _ := -∞ | _ -∞ := -∞ protected definition neg : ereal → ereal | (of_real x) := of_real (-x) | ∞ := -∞ | -∞ := ∞ private definition blow_up [reducible] : ereal → ereal | (of_real x) := if x = 0 then of_real 0 else if x > 0 then ∞ else -∞ | ∞ := ∞ | -∞ := -∞ protected definition mul : ereal → ereal → ereal | (of_real x) (of_real y) := of_real (x * y) | ∞ a := blow_up a | a ∞ := blow_up a | -∞ a := ereal.neg (blow_up a) | a -∞ := ereal.neg (blow_up a) definition ereal_has_add [instance] [priority ereal.prio] : has_add ereal := has_add.mk ereal.add definition ereal_has_neg [instance] [priority ereal.prio] : has_neg ereal := has_neg.mk ereal.neg protected definition sub (u v : ereal) : ereal := u + -v definition ereal_has_sub [instance] [priority ereal.prio] : has_sub ereal := has_sub.mk ereal.sub definition ereal_has_mul [instance] [priority ereal.prio] : has_mul ereal := has_mul.mk ereal.mul protected theorem zero_def : (0 : ereal) = of_real 0 := rfl protected theorem one_def : (1 : ereal) = of_real 1 := rfl protected theorem add_def (x y : ereal) : x + y = ereal.add x y := rfl protected theorem neg_def (x : ereal) : -x = ereal.neg x := rfl protected theorem sub_eq_add_neg (u v : ereal) : u - v = u + -v := rfl protected theorem mul_def (x y : ereal) : x * y = ereal.mul x y := rfl theorem of_real.inj {x y : real} (H : of_real x = of_real y) : x = y := ereal.no_confusion H (assume H1, H1) abbreviation eq_of_of_real_eq_of_real := @of_real.inj theorem of_real_add (x y : real) : of_real (x + y) = of_real x + of_real y := rfl theorem of_real_mul (x y : real) : of_real (x * y) = of_real x * of_real y := rfl theorem infty_ne_neg_infty : ∞ ≠ -∞ := ereal.no_confusion theorem infty_ne_of_real (x : real) : ∞ ≠ of_real x := ereal.no_confusion theorem neg_infty_ne_of_real (x : real) : -∞ ≠ of_real x := ereal.no_confusion /- properties of the arithmetic operations -/ protected theorem add_comm : ∀ u v : ereal, u + v = v + u | (of_real x) (of_real y) := congr_arg of_real !add.comm | ∞ v := by rewrite[*ereal.add_def, ↑ereal.add] | u ∞ := by rewrite[*ereal.add_def, ↑ereal.add] | -∞ v := by rewrite[*ereal.add_def, ↑ereal.add] | u -∞ := by rewrite[*ereal.add_def, ↑ereal.add] theorem infty_add : ∀ u, ∞ + u = ∞ | (of_real x) := rfl | ∞ := rfl | -∞ := rfl theorem add_infty : ∀ u, u + ∞ = ∞ | (of_real x) := rfl | ∞ := rfl | -∞ := rfl protected theorem add_assoc : ∀ u v w : ereal, (u + v) + w = u + (v + w) | (of_real x) (of_real y) (of_real z) := congr_arg of_real !add.assoc | ∞ v w := by rewrite [*infty_add, *add_infty] | u ∞ w := by rewrite [*infty_add, *add_infty, infty_add] | u v ∞ := by rewrite [*infty_add, *add_infty] | (of_real x) (of_real y) -∞ := by rewrite[*ereal.add_def, ↑ereal.add] | (of_real x) -∞ (of_real z) := by rewrite[*ereal.add_def, ↑ereal.add] | -∞ (of_real y) (of_real z) := by rewrite[*ereal.add_def, ↑ereal.add] | (of_real x) -∞ -∞ := by rewrite[*ereal.add_def, ↑ereal.add] | -∞ (of_real y) -∞ := rfl | -∞ -∞ (of_real z) := by rewrite[*ereal.add_def, ↑ereal.add] | -∞ -∞ -∞ := rfl protected theorem zero_add : ∀ u : ereal, 0 + u = u | (of_real x) := congr_arg of_real !real.zero_add | ∞ := rfl | -∞ := rfl protected theorem add_zero : ∀ u : ereal, u + 0 = u := by intro u; rewrite [ereal.add_comm, ereal.zero_add] protected theorem mul_comm : ∀ u v : ereal, u * v = v * u | (of_real x) (of_real y) := congr_arg of_real !mul.comm | ∞ a := by rewrite [*ereal.mul_def, ↑ereal.mul] | a ∞ := by rewrite [*ereal.mul_def, ↑ereal.mul] | -∞ a := by rewrite [*ereal.mul_def, ↑ereal.mul] | a -∞ := by rewrite [*ereal.mul_def, ↑ereal.mul] protected theorem neg_neg : ∀ u : ereal, -(-u) = u | ∞ := rfl | (of_real x) := by rewrite [*ereal.neg_def, ↑ereal.neg, ▸*, (neg_neg' x)] | -∞ := rfl theorem neg_infty : -∞ = - ∞ := rfl protected theorem neg_zero : -(0 : ereal) = 0 := rfl theorem infty_mul_pos {x : real} (H : x > 0) : ∞ * x = ∞ := have H1 : x ≠ 0, from ne_of_gt H, by rewrite [*ereal.mul_def, ↑ereal.mul, if_neg H1, if_pos H] theorem pos_mul_infty {x : real} (H : x > 0) : x * ∞ = ∞ := by rewrite [ereal.mul_comm, infty_mul_pos H] theorem infty_mul_neg {x : real} (H : x < 0) : ∞ * x = -∞ := have H1 : x ≠ 0, from ne_of_lt H, have H2 : ¬ x > 0, from not_lt_of_gt H, by rewrite [*ereal.mul_def, ↑ereal.mul, if_neg H1, if_neg H2] theorem neg_mul_infty {x : real} (H : x < 0) : x * ∞ = -∞ := by rewrite [ereal.mul_comm, infty_mul_neg H] private theorem infty_mul_zero : ∞ * 0 = 0 := by rewrite [*ereal.mul_def, ↑ereal.mul, ereal.zero_def, ↑blow_up, if_pos rfl] private theorem zero_mul_infty : 0 * ∞ = 0 := by rewrite [ereal.mul_comm, infty_mul_zero] theorem infty_mul_infty : ∞ * ∞ = ∞ := rfl protected theorem neg_of_real (x : real) : -(of_real x) = of_real (-x) := rfl private theorem aux1 : ∀ v : ereal, -∞ * v = -(∞ * v) | ∞ := rfl | (of_real x) := rfl | -∞ := rfl private theorem aux2 : ∀ u : ereal, -u * ∞ = -(u * ∞) | ∞ := rfl | (of_real x) := lt.by_cases (assume H : x < 0, by rewrite [ereal.neg_of_real, pos_mul_infty (neg_pos_of_neg H), neg_mul_infty H]) (assume H : x = 0, by krewrite [H, ereal.neg_zero, *zero_mul_infty, ereal.neg_zero]) (assume H : x > 0, by rewrite [ereal.neg_of_real, neg_mul_infty (neg_neg_of_pos H), pos_mul_infty H]) | -∞ := rfl theorem ereal_neg_mul : ∀ u v : ereal, -u * v = -(u * v) | ∞ v := aux1 v | -∞ v := by rewrite [aux1, *ereal.neg_neg] | u ∞ := by rewrite [-aux2] | u -∞ := by rewrite [ereal.mul_comm, ereal.mul_comm u, *aux1, ereal.mul_comm, aux2, *ereal.neg_neg] | (of_real x) (of_real y) := congr_arg of_real (eq.symm (neg_mul_eq_neg_mul x y)) theorem ereal_mul_neg (u v : ereal) : u * -v = -(u * v) := by rewrite [*ereal.mul_comm u, ereal_neg_mul] protected theorem mul_zero : ∀ u : ereal, u * 0 = 0 | ∞ := infty_mul_zero | -∞ := by rewrite [neg_infty, ereal_neg_mul, infty_mul_zero] | (of_real x) := congr_arg of_real (mul_zero' x) protected theorem zero_mul (u : ereal) : 0 * u = 0 := by rewrite [ereal.mul_comm, ereal.mul_zero] private theorem aux3 : ∀ u, ∞ * (∞ * u) = ∞ * u | ∞ := rfl | (of_real x) := if H : x = 0 then by rewrite [*ereal.mul_def, ↑ereal.mul, ↑blow_up, *H, *if_pos rfl] else if H1 : x > 0 then by rewrite [*ereal.mul_def, ↑ereal.mul, ↑blow_up, if_neg H, if_pos H1] else by rewrite [*ereal.mul_def, ↑ereal.mul, ↑blow_up, if_neg H, if_neg H1] | -∞ := rfl private theorem aux4 (x y : real) : ∞ * x * y = ∞ * (x * y) := lt.by_cases (assume H : x < 0, lt.by_cases (assume H1 : y < 0, by rewrite [infty_mul_neg H, neg_infty, ereal_neg_mul, -of_real_mul, infty_mul_neg H1, infty_mul_pos (mul_pos_of_neg_of_neg H H1)]) (assume H1 : y = 0, by krewrite [H1, *ereal.mul_zero]) (assume H1 : y > 0, by rewrite [infty_mul_neg H, neg_infty, *ereal_neg_mul, -of_real_mul, infty_mul_pos H1, infty_mul_neg (mul_neg_of_neg_of_pos H H1)])) (assume H : x = 0, by krewrite [H, ereal.mul_zero, *ereal.zero_mul, ereal.mul_zero]) (assume H : x > 0, lt.by_cases (assume H1 : y < 0, by rewrite [infty_mul_pos H, infty_mul_neg H1, -of_real_mul, infty_mul_neg (mul_neg_of_pos_of_neg H H1)]) (assume H1 : y = 0, by krewrite [H1, *ereal.mul_zero]) (assume H1 : y > 0, by rewrite [infty_mul_pos H, infty_mul_pos H1, -of_real_mul, infty_mul_pos (mul_pos H H1)])) private theorem aux5 : ∀ u v, ∞ * u * v = ∞ * (u * v) | ∞ v := by rewrite [infty_mul_infty, aux3] | u ∞ := by rewrite [-*ereal.mul_comm ∞] | -∞ v := by rewrite [neg_infty, *ereal_neg_mul, *ereal_mul_neg, ereal_neg_mul, infty_mul_infty, aux3] | u -∞ := by rewrite [neg_infty, *ereal_mul_neg] | (of_real x) (of_real y) := aux4 x y protected theorem mul_assoc : ∀ u v w : ereal, u * v * w = u * (v * w) | ∞ v w := !aux5 | u ∞ w := by rewrite [-*ereal.mul_comm ∞, *ereal.mul_comm u, *aux5, *ereal.mul_comm u] | u v ∞ := by rewrite [-*ereal.mul_comm ∞, *ereal.mul_comm u, aux5] | -∞ v w := by rewrite [neg_infty, *ereal_neg_mul, aux5] | u -∞ w := by rewrite [neg_infty, *ereal_mul_neg, *ereal_neg_mul, ereal_mul_neg, *ereal.mul_comm u, *aux5, ereal.mul_comm u] | u v -∞ := by rewrite [neg_infty, *ereal_mul_neg, *ereal.mul_comm u, -*ereal.mul_comm ∞, aux5] | (of_real x) (of_real y) (of_real z) := congr_arg of_real (mul.assoc x y z) protected theorem one_mul : ∀ u : ereal, of_real 1 * u = u | (of_real x) := !real.one_mul ▸ rfl | ∞ := pos_mul_infty zero_lt_one | -∞ := by rewrite [neg_infty, ereal_mul_neg, pos_mul_infty zero_lt_one] protected theorem mul_one (u : ereal) : u * 1 = u := by krewrite [ereal.mul_comm, ereal.one_mul] /- instantiating arithmetic structures -/ -- Note that distributivity fails, e.g. ∞ ⬝ (-1 + 1) ≠ ∞ * -1 + ∞ * 1 protected definition comm_monoid [trans_instance] : comm_monoid ereal := ⦃comm_monoid, mul := ereal.mul, mul_assoc := ereal.mul_assoc, one := 1, one_mul := ereal.one_mul, mul_one := ereal.mul_one, mul_comm := ereal.mul_comm ⦄ protected definition add_comm_monoid [trans_instance] : add_comm_monoid ereal := ⦃add_comm_monoid, add := ereal.add, add_assoc := ereal.add_assoc, zero := 0, zero_add := ereal.zero_add, add_zero := ereal.add_zero, add_comm := ereal.add_comm ⦄ /- ordering on the ereals -/ protected definition le : ereal → ereal → Prop | u ∞ := true | -∞ v := true | (of_real x) (of_real y) := x ≤ y | (of_real x) -∞ := false | ∞ (of_real y) := false | ∞ -∞ := false definition ereal_has_le [instance] [priority ereal.prio] : has_le ereal := has_le.mk ereal.le theorem of_real_le_of_real (x y : real) : of_real x ≤ of_real y ↔ x ≤ y := !iff.refl theorem le_infty : ∀ u, u ≤ ∞ | ∞ := trivial | (of_real x) := trivial | -∞ := trivial theorem neg_infty_le : ∀ v, -∞ ≤ v | ∞ := trivial | (of_real x) := trivial | -∞ := trivial protected theorem le_refl : ∀ u : ereal, u ≤ u | ∞ := trivial | -∞ := trivial | (of_real x) := by rewrite [of_real_le_of_real] protected theorem le_trans : ∀ u v w : ereal, u ≤ v → v ≤ w → u ≤ w | u v ∞ H1 H2 := !le_infty | -∞ v w H1 H2 := !neg_infty_le | u ∞ (of_real x) H1 H2 := false.elim H2 | ∞ (of_real x) v H1 H2 := false.elim H1 | ∞ -∞ v H1 H2 := false.elim H1 | u (of_real x) -∞ H1 H2 := false.elim H2 | u ∞ -∞ H1 H2 := false.elim H2 | (of_real x) -∞ v H1 H2 := false.elim H1 | (of_real x) (of_real y) (of_real z) H1 H2 := iff.mpr !of_real_le_of_real (le.trans (iff.mp !of_real_le_of_real H1) (iff.mp !of_real_le_of_real H2)) protected theorem le_antisymm : ∀ u v : ereal, u ≤ v → v ≤ u → u = v | ∞ ∞ H1 H2 := rfl | ∞ (of_real x) H1 H2 := false.elim H1 | ∞ -∞ H1 H2 := false.elim H1 | -∞ -∞ H1 H2 := rfl | -∞ (of_real x) H1 H2 := false.elim H2 | -∞ ∞ H1 H2 := false.elim H2 | (of_real x) ∞ H1 H2 := false.elim H2 | (of_real x) -∞ H1 H2 := false.elim H1 | (of_real x) (of_real y) H1 H2 := congr_arg of_real (le.antisymm (iff.mp !of_real_le_of_real H1) (iff.mp !of_real_le_of_real H2)) protected definition lt (x y : ereal) : Prop := x ≤ y ∧ x ≠ y definition ereal_has_lt [instance] [priority ereal.prio] : has_lt ereal := has_lt.mk ereal.lt protected theorem le_iff_lt_or_eq (u v : ereal) : u ≤ v ↔ u < v ∨ u = v := iff.intro (assume H : u ≤ v, by_cases (assume H1 : u = v, or.inr H1) (assume H1 : u ≠ v, or.inl (and.intro H H1))) (assume H : u < v ∨ u = v, or.elim H (assume H1 : u < v, and.left H1) (assume H1 : u = v, by rewrite H1; apply ereal.le_refl)) protected theorem le_total : ∀ u v : ereal, u ≤ v ∨ v ≤ u | u ∞ := or.inl (le_infty u) | u -∞ := or.inr (neg_infty_le u) | ∞ v := or.inr (le_infty v) | -∞ v := or.inl (neg_infty_le v) | (of_real x) (of_real y) := or.elim (le.total x y) (assume H : x ≤[real] y, or.inl (iff.mpr !of_real_le_of_real H)) (assume H : x ≥[real] y, or.inr (iff.mpr !of_real_le_of_real H)) theorem neg_infty_lt_infty : -∞ < ∞ := and.intro trivial (ne.symm infty_ne_neg_infty) theorem neg_infty_lt_of_real (x : real) : -∞ < of_real x := and.intro trivial !neg_infty_ne_of_real theorem of_real_lt_infty (x : real) : of_real x < ∞ := and.intro trivial (ne.symm !infty_ne_of_real) protected definition decidable_linear_order [trans_instance] : decidable_linear_order ereal := ⦃decidable_linear_order, le := ereal.le, le_refl := ereal.le_refl, le_trans := ereal.le_trans, le_antisymm := ereal.le_antisymm, lt := ereal.lt, le_iff_lt_or_eq := ereal.le_iff_lt_or_eq, lt_irrefl := abstract λ u H, and.right H rfl end, decidable_lt := abstract λ u v : ereal, prop_decidable (u < v) end, le_total := ereal.le_total ⦄ -- TODO : we still need some properties relating the arithmetic operations and the order. end ereal
977068d1301243ddde7adeb2d8d6c3dd924936e5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/char_p/basic.lean
46a92ff99b75634dc553d4df84f3b6f69adb577a
[ "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
21,339
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Joey van Langen, Casper Putz -/ import algebra.hom.iterate import data.int.modeq import data.nat.choose.dvd import data.nat.choose.sum import data.zmod.defs import group_theory.order_of_element import ring_theory.nilpotent /-! # Characteristic of semirings -/ universes u v variables (R : Type u) /-- The generator of the kernel of the unique homomorphism ℕ → R for a semiring R. *Warning*: for a semiring `R`, `char_p R 0` and `char_zero R` need not coincide. * `char_p R 0` asks that only `0 : ℕ` maps to `0 : R` under the map `ℕ → R`; * `char_zero R` requires an injection `ℕ ↪ R`. For instance, endowing `{0, 1}` with addition given by `max` (i.e. `1` is absorbing), shows that `char_zero {0, 1}` does not hold and yet `char_p {0, 1} 0` does. This example is formalized in `counterexamples/char_p_zero_ne_char_zero`. -/ @[mk_iff] class char_p [add_monoid_with_one R] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:R) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero [add_monoid_with_one R] (p : ℕ) [char_p R p] : (p:R) = 0 := (char_p.cast_eq_zero_iff R p p).2 (dvd_refl p) @[simp] lemma char_p.cast_card_eq_zero [add_group_with_one R] [fintype R] : (fintype.card R : R) = 0 := by rw [← nsmul_one, card_nsmul_eq_zero] lemma char_p.int_cast_eq_zero_iff [add_group_with_one R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end lemma char_p.int_coe_eq_int_coe_iff [add_group_with_one R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = (b : R) ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq_iff_dvd] theorem char_p.eq [add_monoid_with_one R] {p q : ℕ} (c1 : char_p R p) (c2 : char_p R q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff R p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff R q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero [add_monoid_with_one R] [char_zero R] : char_p R 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists [non_assoc_semiring R] : ∃ p, char_p R p := by letI := classical.dec_eq R; exact classical.by_cases (assume H : ∀ p:ℕ, (p:R) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; simp⟩⟩⟩) (λ H, ⟨nat.find (not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique [non_assoc_semiring R] : ∃! p, char_p R p := let ⟨c, H⟩ := char_p.exists R in ⟨c, H, λ y H2, char_p.eq R H2 H⟩ theorem char_p.congr {R : Type u} [add_monoid_with_one R] {p : ℕ} (q : ℕ) [hq : char_p R q] (h : q = p) : char_p R p := h ▸ hq /-- Noncomputable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char [non_assoc_semiring R] : ℕ := classical.some (char_p.exists_unique R) namespace ring_char variables [non_assoc_semiring R] theorem spec : ∀ x:ℕ, (x:R) = 0 ↔ ring_char R ∣ x := by letI := (classical.some_spec (char_p.exists_unique R)).1; unfold ring_char; exact char_p.cast_eq_zero_iff R (ring_char R) theorem eq (p : ℕ) [C : char_p R p] : ring_char R = p := ((classical.some_spec (char_p.exists_unique R)).2 p C).symm instance char_p : char_p R (ring_char R) := ⟨spec R⟩ variables {R} theorem of_eq {p : ℕ} (h : ring_char R = p) : char_p R p := char_p.congr (ring_char R) h theorem eq_iff {p : ℕ} : ring_char R = p ↔ char_p R p := ⟨of_eq, @eq R _ p⟩ theorem dvd {x : ℕ} (hx : (x : R) = 0) : ring_char R ∣ x := (spec R x).1 hx @[simp] lemma eq_zero [char_zero R] : ring_char R = 0 := eq R 0 @[simp] lemma nat.cast_ring_char : (ring_char R : R) = 0 := by rw ring_char.spec end ring_char theorem add_pow_char_of_commute [semiring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x + y)^p = x^p + y^p := begin rw [commute.add_pow h, finset.sum_range_succ_comm, tsub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one], congr' 1, convert finset.sum_eq_single 0 _ _, { simp only [mul_one, one_mul, nat.choose_zero_right, tsub_zero, nat.cast_one, pow_zero] }, { intros b h1 h2, suffices : (p.choose b : R) = 0, { rw this, simp }, rw char_p.cast_eq_zero_iff R p, refine nat.prime.dvd_choose_self (pos_iff_ne_zero.mpr h2) _ (fact.out _), rwa ← finset.mem_range }, { intro h1, contrapose! h1, rw finset.mem_range, exact nat.prime.pos (fact.out _) } end theorem add_pow_char_pow_of_commute [semiring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply add_pow_char_of_commute, apply commute.pow_pow h, end theorem sub_pow_char_of_commute [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x - y)^p = x^p - y^p := begin rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)], simp, repeat {apply_instance}, end theorem sub_pow_char_pow_of_commute [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply sub_pow_char_of_commute, apply commute.pow_pow h, end theorem add_pow_char [comm_semiring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) : (x + y)^p = x^p + y^p := add_pow_char_of_commute _ _ _ (commute.all _ _) theorem add_pow_char_pow [comm_semiring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := add_pow_char_pow_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) : (x - y)^p = x^p - y^p := sub_pow_char_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char_pow [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := sub_pow_char_pow_of_commute _ _ _ (commute.all _ _) lemma eq_iff_modeq_int [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq_iff_dvd] lemma char_p.neg_one_ne_one [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] : (-1 : R) ≠ (1 : R) := begin suffices : (2 : R) ≠ 0, { symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this }, assume h, rw [show (2 : R) = (2 : ℕ), by norm_cast] at h, have := (char_p.cast_eq_zero_iff R p 2).mp h, have := nat.le_of_dvd dec_trivial this, rw fact_iff at *, linarith, end lemma char_p.neg_one_pow_char [comm_ring R] (p : ℕ) [char_p R p] [fact p.prime] : (-1 : R) ^ p = -1 := begin rw eq_neg_iff_add_eq_zero, nth_rewrite 1 ← one_pow p, rw [← add_pow_char, add_left_neg, zero_pow (fact.out (nat.prime p)).pos], end lemma char_p.neg_one_pow_char_pow [comm_ring R] (p n : ℕ) [char_p R p] [fact p.prime] : (-1 : R) ^ p ^ n = -1 := begin rw eq_neg_iff_add_eq_zero, nth_rewrite 1 ← one_pow (p ^ n), rw [← add_pow_char_pow, add_left_neg, zero_pow (pow_pos (fact.out (nat.prime p)).pos _)], end lemma ring_hom.char_p_iff_char_p {K L : Type*} [division_ring K] [semiring L] [nontrivial L] (f : K →+* L) (p : ℕ) : char_p K p ↔ char_p L p := by simp only [char_p_iff, ← f.injective.eq_iff, map_nat_cast f, f.map_zero] section frobenius section comm_semiring variables [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (fact.out (nat.prime p)).pos, map_add' := add_pow_char R } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n := begin induction n, {simp}, rw [function.iterate_succ', pow_succ', pow_mul, function.comp_apply, frobenius_def, n_ih] end theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := function.semiconj.iterate_right (f.map_frobenius p) n x theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := map_nat_cast (frobenius R p) n open_locale big_operators variables {R} lemma list_sum_pow_char (l : list R) : l.sum ^ p = (l.map (^ p)).sum := (frobenius R p).map_list_sum _ lemma multiset_sum_pow_char (s : multiset R) : s.sum ^ p = (s.map (^ p)).sum := (frobenius R p).map_multiset_sum _ lemma sum_pow_char {ι : Type*} (s : finset ι) (f : ι → R) : (∑ i in s, f i) ^ p = ∑ i in s, f i ^ p := (frobenius R p).map_sum _ _ end comm_semiring section comm_ring variables [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y end comm_ring end frobenius theorem frobenius_inj [comm_ring R] [is_reduced R] (p : ℕ) [fact p.prime] [char_p R p] : function.injective (frobenius R p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact is_reduced.eq_zero _ ⟨_,H⟩ } /-- If `ring_char R = 2`, where `R` is a finite reduced commutative ring, then every `a : R` is a square. -/ lemma is_square_of_char_two' {R : Type*} [fintype R] [comm_ring R] [is_reduced R] [char_p R 2] (a : R) : is_square a := exists_imp_exists (λ b h, pow_two b ▸ eq.symm h) $ ((fintype.bijective_iff_injective_and_card _).mpr ⟨frobenius_inj R 2, rfl⟩).surjective a namespace char_p section variables [non_assoc_ring R] lemma char_p_to_char_zero (R : Type*) [add_group_with_one R] [char_p R 0] : char_zero R := char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff R 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p R p] (k : ℕ) : (k : R) = (k % p : ℕ) := calc (k : R) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp [cast_eq_zero] /-- The characteristic of a finite ring cannot be zero. -/ theorem char_ne_zero_of_finite (p : ℕ) [char_p R p] [finite R] : p ≠ 0 := begin unfreezingI { rintro rfl }, haveI : char_zero R := char_p_to_char_zero R, casesI nonempty_fintype R, exact absurd nat.cast_injective (not_injective_infinite_finite (coe : ℕ → R)) end lemma ring_char_ne_zero_of_finite [finite R] : ring_char R ≠ 0 := char_ne_zero_of_finite R (ring_char R) end section comm_ring variables [comm_ring R] [is_reduced R] {R} @[simp] lemma pow_prime_pow_mul_eq_one_iff (p k m : ℕ) [fact p.prime] [char_p R p] (x : R) : x ^ (p ^ k * m) = 1 ↔ x ^ m = 1 := begin induction k with k hk, { rw [pow_zero, one_mul] }, { refine ⟨λ h, _, λ h, _⟩, { rw [pow_succ, mul_assoc, pow_mul', ← frobenius_def, ← frobenius_one p] at h, exact hk.1 (frobenius_inj R p h) }, { rw [pow_mul', h, one_pow] } } end end comm_ring section semiring open nat variables [non_assoc_semiring R] theorem char_ne_one [nontrivial R] (p : ℕ) [hc : char_p R p] : p ≠ 1 := assume hp : p = 1, have ( 1 : R) = 0, by simpa using (cast_eq_zero_iff R p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero section no_zero_divisors variable [no_zero_divisors R] theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p R p] (hp : 2 ≤ p) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from nat.prime_def_lt''.mpr ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : R) = 0, from (cast_eq_zero_iff R p p).mpr (dvd_refl p), have (d : R) * e = 0, from (@cast_mul R _ d e) ▸ (hmul ▸ this), or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume hd : (d : R) = 0, have p ∣ d, from (cast_eq_zero_iff R p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : R) = 0, have p ∣ e, from (cast_eq_zero_iff R p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) section nontrivial variables [nontrivial R] theorem char_is_prime_or_zero (p : ℕ) [hc : char_p R p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one R _ _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_two_le R _ _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p R p] : fact p.prime := ⟨(char_p.char_is_prime_or_zero R _).resolve_right (pos_iff_ne_zero.1 h.1)⟩ end nontrivial end no_zero_divisors end semiring section ring variables (R) [ring R] [no_zero_divisors R] [nontrivial R] [finite R] theorem char_is_prime (p : ℕ) [char_p R p] : p.prime := or.resolve_right (char_is_prime_or_zero R p) (char_ne_zero_of_finite R p) end ring section char_one variables {R} [non_assoc_semiring R] @[priority 100] -- see Note [lower instance priority] instance [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul lemma false_of_nontrivial_of_char_one [nontrivial R] [char_p R 1] : false := false_of_nontrivial_of_subsingleton R lemma ring_char_ne_one [nontrivial R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } lemma nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) [hr : char_p R v] : nontrivial R := ⟨⟨(1 : ℕ), 0, λ h, hv $ by rwa [char_p.cast_eq_zero_iff _ v, nat.dvd_one] at h; assumption ⟩⟩ lemma ring_char_of_prime_eq_zero [nontrivial R] {p : ℕ} (hprime : nat.prime p) (hp0 : (p : R) = 0) : ring_char R = p := or.resolve_left ((nat.dvd_prime hprime).1 (ring_char.dvd hp0)) ring_char_ne_one end char_one end char_p section /-- We have `2 ≠ 0` in a nontrivial ring whose characteristic is not `2`. -/ -- Note: there is `two_ne_zero` (assuming `[ordered_semiring]`) -- and `two_ne_zero'`(assuming `[char_zero]`), which both don't fit the needs here. @[protected] lemma ring.two_ne_zero {R : Type*} [non_assoc_semiring R] [nontrivial R] (hR : ring_char R ≠ 2) : (2 : R) ≠ 0 := begin rw [ne.def, (by norm_cast : (2 : R) = (2 : ℕ)), ring_char.spec, nat.dvd_prime nat.prime_two], exact mt (or_iff_left hR).mp char_p.ring_char_ne_one, end /-- Characteristic `≠ 2` and nontrivial implies that `-1 ≠ 1`. -/ -- We have `char_p.neg_one_ne_one`, which assumes `[ring R] (p : ℕ) [char_p R p] [fact (2 < p)]`. -- This is a version using `ring_char` instead. lemma ring.neg_one_ne_one_of_char_ne_two {R : Type*} [non_assoc_ring R] [nontrivial R] (hR : ring_char R ≠ 2) : (-1 : R) ≠ 1 := λ h, ring.two_ne_zero hR (neg_eq_iff_add_eq_zero.mp h) /-- Characteristic `≠ 2` in a domain implies that `-a = a` iff `a = 0`. -/ lemma ring.eq_self_iff_eq_zero_of_char_ne_two {R : Type*} [non_assoc_ring R] [nontrivial R] [no_zero_divisors R] (hR : ring_char R ≠ 2) {a : R} : -a = a ↔ a = 0 := ⟨λ h, (mul_eq_zero.mp $ (two_mul a).trans $ neg_eq_iff_add_eq_zero.mp h).resolve_left (ring.two_ne_zero hR), λ h, ((congr_arg (λ x, - x) h).trans neg_zero).trans h.symm⟩ end section variables (R) [non_assoc_ring R] [fintype R] (n : ℕ) lemma char_p_of_ne_zero (hn : fintype.card R = n) (hR : ∀ i < n, (i : R) = 0 → i = 0) : char_p R n := { cast_eq_zero_iff := begin have H : (n : R) = 0, by { rw [← hn, char_p.cast_card_eq_zero] }, intro k, split, { intro h, rw [← nat.mod_add_div k n, nat.cast_add, nat.cast_mul, H, zero_mul, add_zero] at h, rw nat.dvd_iff_mod_eq_zero, apply hR _ (nat.mod_lt _ _) h, rw [← hn, fintype.card_pos_iff], exact ⟨0⟩, }, { rintro ⟨k, rfl⟩, rw [nat.cast_mul, H, zero_mul] } end } lemma char_p_of_prime_pow_injective (R) [ring R] [fintype R] (p : ℕ) [hp : fact p.prime] (n : ℕ) (hn : fintype.card R = p ^ n) (hR : ∀ i ≤ n, (p ^ i : R) = 0 → i = n) : char_p R (p ^ n) := begin obtain ⟨c, hc⟩ := char_p.exists R, resetI, have hcpn : c ∣ p ^ n, { rw [← char_p.cast_eq_zero_iff R c, ← hn, char_p.cast_card_eq_zero], }, obtain ⟨i, hi, hc⟩ : ∃ i ≤ n, c = p ^ i, by rwa nat.dvd_prime_pow hp.1 at hcpn, obtain rfl : i = n, { apply hR i hi, rw [← nat.cast_pow, ← hc, char_p.cast_eq_zero] }, rwa ← hc end end section prod variables (S : Type v) [semiring R] [semiring S] (p q : ℕ) [char_p R p] /-- The characteristic of the product of rings is the least common multiple of the characteristics of the two rings. -/ instance [char_p S q] : char_p (R × S) (nat.lcm p q) := { cast_eq_zero_iff := by simp [prod.ext_iff, char_p.cast_eq_zero_iff R p, char_p.cast_eq_zero_iff S q, nat.lcm_dvd_iff] } /-- The characteristic of the product of two rings of the same characteristic is the same as the characteristic of the rings -/ instance prod.char_p [char_p S p] : char_p (R × S) p := by convert nat.lcm.char_p R S p p; simp end prod section /-- If two integers from `{0, 1, -1}` result in equal elements in a ring `R` that is nontrivial and of characteristic not `2`, then they are equal. -/ lemma int.cast_inj_on_of_ring_char_ne_two {R : Type*} [non_assoc_ring R] [nontrivial R] (hR : ring_char R ≠ 2) : ({0, 1, -1} : set ℤ).inj_on (coe : ℤ → R) := begin intros a ha b hb h, apply eq_of_sub_eq_zero, by_contra hf, change a = 0 ∨ a = 1 ∨ a = -1 at ha, change b = 0 ∨ b = 1 ∨ b = -1 at hb, have hh : a - b = 1 ∨ b - a = 1 ∨ a - b = 2 ∨ b - a = 2 := by { rcases ha with ha | ha | ha; rcases hb with hb | hb | hb, swap 5, swap 9, -- move goals with `a = b` to the front iterate 3 { rw [ha, hb, sub_self] at hf, tauto, }, -- 6 goals remain all_goals { rw [ha, hb], norm_num, }, }, have h' : ((a - b : ℤ) : R) = 0 := by exact_mod_cast sub_eq_zero_of_eq h, have h'' : ((b - a : ℤ) : R) = 0 := by exact_mod_cast sub_eq_zero_of_eq h.symm, rcases hh with hh | hh | hh | hh, { rw [hh, (by norm_cast : ((1 : ℤ) : R) = 1)] at h', exact one_ne_zero h', }, { rw [hh, (by norm_cast : ((1 : ℤ) : R) = 1)] at h'', exact one_ne_zero h'', }, { rw [hh, (by norm_cast : ((2 : ℤ) : R) = 2)] at h', exact ring.two_ne_zero hR h', }, { rw [hh, (by norm_cast : ((2 : ℤ) : R) = 2)] at h'', exact ring.two_ne_zero hR h'', }, end end
75ed2658c36e8ee0c70a6aa2f2e3b6bbe4e1dfff
7565ffb53cc64430691ce89265da0f944ee43051
/hott/homotopy/wedge.hlean
aecdfd7db5f9f7291af2c65d5f062b075c5f2bdd
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,217
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Ulrik Buchholtz The Wedge Sum of Two Pointed Types -/ import hit.pushout .connectedness types.unit open eq pushout pointed unit trunc_index definition wedge (A B : Type*) : Type := ppushout (pconst punit A) (pconst punit B) local attribute wedge [reducible] definition pwedge [constructor] (A B : Type*) : Type* := pointed.mk' (wedge A B) infixr ` ∨ ` := pwedge namespace wedge protected definition glue {A B : Type*} : inl pt = inr pt :> wedge A B := pushout.glue ⋆ protected definition rec {A B : Type*} {P : wedge A B → Type} (Pinl : Π(x : A), P (inl x)) (Pinr : Π(x : B), P (inr x)) (Pglue : pathover P (Pinl pt) wedge.glue (Pinr pt)) (y : wedge A B) : P y := by induction y; apply Pinl; apply Pinr; induction x; exact Pglue protected definition elim {A B : Type*} {P : Type} (Pinl : A → P) (Pinr : B → P) (Pglue : Pinl pt = Pinr pt) (y : wedge A B) : P := by induction y with a b x; exact Pinl a; exact Pinr b; induction x; exact Pglue protected definition rec_glue {A B : Type*} {P : wedge A B → Type} (Pinl : Π(x : A), P (inl x)) (Pinr : Π(x : B), P (inr x)) (Pglue : pathover P (Pinl pt) wedge.glue (Pinr pt)) : apd (wedge.rec Pinl Pinr Pglue) wedge.glue = Pglue := !pushout.rec_glue protected definition elim_glue {A B : Type*} {P : Type} (Pinl : A → P) (Pinr : B → P) (Pglue : Pinl pt = Pinr pt) : ap (wedge.elim Pinl Pinr Pglue) wedge.glue = Pglue := !pushout.elim_glue end wedge attribute wedge.rec wedge.elim [recursor 7] [unfold 7] namespace wedge -- TODO maybe find a cleaner proof protected definition unit (A : Type*) : A ≃* pwedge punit A := begin fapply pequiv_of_pmap, { fapply pmap.mk, intro a, apply pinr a, apply respect_pt }, { fapply is_equiv.adjointify, intro x, fapply pushout.elim_on x, exact λ x, Point A, exact id, intro u, reflexivity, intro x, fapply pushout.rec_on x, intro u, cases u, esimp, apply wedge.glue⁻¹, intro a, reflexivity, intro u, cases u, esimp, apply eq_pathover, refine _ ⬝hp !ap_id⁻¹, fapply eq_hconcat, apply ap_compose inr, krewrite elim_glue, fapply eq_hconcat, apply ap_idp, apply square_of_eq, apply con.left_inv, intro a, reflexivity}, end end wedge open trunc is_trunc is_conn function namespace wedge_extension section -- The wedge connectivity lemma (Lemma 8.6.2) parameters {A B : Type*} (n m : ℕ) [cA : is_conn n A] [cB : is_conn m B] (P : A → B → Type) [HP : Πa b, is_trunc (m + n) (P a b)] (f : Πa : A, P a pt) (g : Πb : B, P pt b) (p : f pt = g pt) include cA cB HP private definition Q (a : A) : Type := fiber (λs : (Πb : B, P a b), s (Point B)) (f a) private definition is_trunc_Q (a : A) : is_trunc (n.-1) (Q a) := begin refine @is_conn.elim_general (m.-1) _ _ _ (P a) _ (f a), rewrite [-succ_add_succ, of_nat_add_of_nat], intro b, apply HP end local attribute is_trunc_Q [instance] private definition Q_sec : Πa : A, Q a := is_conn.elim (n.-1) Q (fiber.mk g p⁻¹) protected definition ext : Π(a : A)(b : B), P a b := λa, fiber.point (Q_sec a) protected definition β_left (a : A) : ext a (Point B) = f a := fiber.point_eq (Q_sec a) private definition coh_aux : Σq : ext (Point A) = g, β_left (Point A) = ap (λs : (Πb : B, P (Point A) b), s (Point B)) q ⬝ p⁻¹ := equiv.to_fun (fiber.fiber_eq_equiv (Q_sec (Point A)) (fiber.mk g p⁻¹)) (is_conn.elim_β (n.-1) Q (fiber.mk g p⁻¹)) protected definition β_right (b : B) : ext (Point A) b = g b := apd10 (sigma.pr1 coh_aux) b private definition lem : β_left (Point A) = β_right (Point B) ⬝ p⁻¹ := begin unfold β_right, unfold β_left, krewrite (apd10_eq_ap_eval (sigma.pr1 coh_aux) (Point B)), exact sigma.pr2 coh_aux, end protected definition coh : (β_left (Point A))⁻¹ ⬝ β_right (Point B) = p := by rewrite [lem,con_inv,inv_inv,con.assoc,con.left_inv] end end wedge_extension
efe9f461bd240975dfa0a874c87f2e977261bf6f
4fa161becb8ce7378a709f5992a594764699e268
/src/analysis/normed_space/basic.lean
e490fb6e38737934ece5dc1a57c1dab95559841f
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
46,881
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.instances.nnreal import topology.instances.complex import topology.algebra.module import topology.metric_space.antilipschitz /-! # Normed spaces -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e section prio set_option default_priority 100 -- see Note [default priority] /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) end prio /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } @[nolint ge_or_gt] -- see Note [nolint_ge] theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add' (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], apply le_div_of_mul_le (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl } lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto.comp continuous_norm.continuous_at h lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm, sub_eq_add_neg]; abel ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _ ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) end prio @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_add_le }, { rw ←zero_add (0 : ℝ), apply tendsto.add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto.mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto.mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) end prio @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt (norm_pos_iff.2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b @[simp] lemma nnnorm_one [normed_field α] : nnnorm (1:α) = 1 := nnreal.eq $ by simp instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ := eq.symm (s.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := begin classical, by_cases hb : b = 0, {simp [hb]}, apply eq_div_of_mul_eq, { apply ne_of_gt, apply norm_pos_iff.mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma nnnorm_inv {α : Type*} [normed_field α] (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α] (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) : nhds_within x (-{x}) ≠ ⊥ := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := begin refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _), let δ := min (ε/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0, have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos (half_pos εpos) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨δ, δpos, λ x hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp [sub_sub_cancel], have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2, by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div, div_eq_inv_mul, mul_comm] }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } end lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} := begin assume x hx, apply continuous_at.continuous_within_at, exact (tendsto_inv hx) end end normed_field instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } /-- 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' [normed_field α] {l : filter β} {f : β → α} {y : α} (hy : y ≠ 0) (h : tendsto f l (𝓝 y)) : tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) := (normed_field.tendsto_inv hy).comp h lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) : tendsto (λa, f a / g a) l (𝓝 (x / y)) := hf.mul (hg.inv' hy) lemma filter.tendsto.div_const [normed_field α] {l : filter β} {f : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) := by { simp only [div_eq_inv_mul], exact tendsto_const_nhds.mul hf } /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) : continuous_at (λ x, f x / g x) x := hf.div hg hnz namespace real lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _) @[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp end real @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option default_priority 920 -- see Note [default priority]. Here, we set a rather high priority, -- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better -- unification properties. -- see Note[vector space definition] for why we extend `semimodule`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends semimodule α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin classical, by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _ ... = ∥s • x∥ : _, exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _), rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul], rwa [ne.def, norm_eq_zero] } end lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end /-- In a normed space over a nondiscrete normed field, only `⊤` submodule has a nonempty interior. See also `submodule.eq_top_of_nonempty_interior'` for a `topological_module` version. -/ lemma submodule.eq_top_of_nonempty_interior {α E : Type*} [nondiscrete_normed_field α] [normed_group E] [normed_space α E] (s : submodule α E) (hs : (interior (s:set E)).nonempty) : s = ⊤ := begin refine s.eq_top_of_nonempty_interior' _ hs, simp only [is_unit_iff_ne_zero, @ne.def α, set.mem_singleton_iff.symm], exact normed_field.punctured_nhds_ne_bot _ end theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, interior_eq_of_open is_open_ball], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem interior_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases hE with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure (-{x} : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_eq_of_is_closed is_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] theorem frontier_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_eq_of_is_closed is_closed_ball, interior_closed_ball' x r hE, closed_ball_diff_ball] open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos (norm_pos_iff.2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], -- TODO: without the next two lines Lean unfolds `≤` to `real.le` add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.semimodule } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } end normed_space section normed_algebra section prio set_option default_priority 100 -- see Note [default priority] /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) end prio @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ @[priority 100] instance normed_algebra.to_normed_space (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } instance normed_algebra.id (𝕜 : Type*) [normed_field 𝕜] : normed_algebra 𝕜 𝕜 := { norm_algebra_map_eq := by simp, .. algebra.id 𝕜} end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] /-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/ -- We could add a type synonym equipped with this as an instance, -- as we've done for `module.restrict_scalars`. def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..module.restrict_scalars' 𝕜 𝕜' E } end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥∑ i in t, g i∥ < ε := hs t ht, have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : β → finset ι} {p : filter β} (hp : p ≠ ⊥) (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hp hs ha /-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) := begin by_cases h : summable f, { have h₁ : tendsto (λs:finset ι, ∥∑ i in s, f i∥) at_top (𝓝 ∥(∑' i, f i)∥) := (continuous_norm.tendsto _).comp h.has_sum, have h₂ : tendsto (λs:finset ι, ∑ i in s, ∥f i∥) at_top (𝓝 (∑' i, ∥f i∥)) := hf.has_sum, exact le_of_tendsto_of_tendsto' at_top_ne_bot h₁ h₂ (assume s, norm_sum_le _ _) }, { rw tsum_eq_zero_of_not_summable h, simp [tsum_nonneg] } end lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf at_top_ne_bot tendsto_finset_range h⟩ variable [complete_space α] lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
2733b78f56fc7dbf9db07c4efbe7f19e68ef2b07
a7dd8b83f933e72c40845fd168dde330f050b1c9
/src/category_theory/instances/Mon/default.lean
cbb096a000e83b2a41c26fa9740ecac5a9b47691
[ "Apache-2.0" ]
permissive
NeilStrickland/mathlib
10420e92ee5cb7aba1163c9a01dea2f04652ed67
3efbd6f6dff0fb9b0946849b43b39948560a1ffe
refs/heads/master
1,589,043,046,346
1,558,938,706,000
1,558,938,706,000
181,285,984
0
0
Apache-2.0
1,568,941,848,000
1,555,233,833,000
Lean
UTF-8
Lean
false
false
244
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.instances.Mon.basic import category_theory.instances.Mon.colimits
903df424970741bd70a79bace7f73da40d6314c9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eq4.lean
1298764aaa81a654be6358e0527c049a20521cbb
[ "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
285
lean
open nat definition half : nat → nat | 0 := 0 | 1 := 0 | (x+2) := half x + 1 theorem half0 : half 0 = 0 := rfl theorem half1 : half 1 = 0 := rfl theorem half_succ_succ (a : nat) : half (a + 2) = half a + 1 := rfl example : half 5 = 2 := rfl example : half 8 = 4 := rfl
38eb5b64a6815fa6adadeb46b65cf1572ed0fe95
649957717d58c43b5d8d200da34bf374293fe739
/src/category_theory/limits/preserves.lean
4df7d1e9cb46dd38ed95d9ab88a537d0ed274dfb
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
10,687
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton -- Preservation and reflection of (co)limits. import category_theory.limits.limits open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v+1} C] variables {D : Type u₂} [𝒟 : category.{v+1} D] include 𝒞 𝒟 variables {J : Type v} [small_category J] {K : J ⥤ C} /- Note on "preservation of (co)limits" There are various distinct notions of "preserving limits". The one we aim to capture here is: A functor F : C → D "preserves limits" if it sends every limit cone in C to a limit cone in D. Informally, F preserves all the limits which exist in C. Note that: * Of course, we do not want to require F to *strictly* take chosen limit cones of C to chosen limit cones of D. Indeed, the above definition makes no reference to a choice of limit cones so it makes sense without any conditions on C or D. * Some diagrams in C may have no limit. In this case, there is no condition on the behavior of F on such diagrams. There are other notions (such as "flat functor") which impose conditions also on diagrams in C with no limits, but these are not considered here. In order to be able to express the property of preserving limits of a certain form, we say that a functor F preserves the limit of a diagram K if F sends every limit cone on K to a limit cone. This is vacuously satisfied when K does not admit a limit, which is consistent with the above definition of "preserves limits". -/ class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cone K} [is_limit c], is_limit (F.map_cone c)) class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cocone K} [is_colimit c], is_colimit (F.map_cocone c)) class preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_limit : Π {K : J ⥤ C}, preserves_limit K F) class preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_colimit : Π {K : J ⥤ C}, preserves_colimit K F) class preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_limits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_limits_of_shape J F) class preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_colimits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_colimits_of_shape J F) attribute [instance] preserves_limit.preserves preserves_limits_of_shape.preserves_limit preserves_limits.preserves_limits_of_shape preserves_colimit.preserves preserves_colimits_of_shape.preserves_colimit preserves_colimits.preserves_colimits_of_shape instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } instance id_preserves_limits : preserves_limits (functor.id C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_preserves_colimits : preserves_colimits (functor.id C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } section variables {E : Type u₃} [ℰ : category.{v+1} E] variables (F : C ⥤ D) (G : D ⥤ E) local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] : preserves_limit K (F ⋙ G) := ⟨λ c h, by exactI @preserves_limit.preserves _ _ _ _ _ _ (K ⋙ F) G _ _ (preserves_limit.preserves K F)⟩ instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] : preserves_colimit K (F ⋙ G) := ⟨λ c h, by exactI @preserves_colimit.preserves _ _ _ _ _ _ (K ⋙ F) G _ _ (preserves_colimit.preserves K F)⟩ end /-- If F preserves one limit cone for the diagram K, then it preserves any limit cone for K. -/ def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K} (h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F := ⟨λ t' h', is_limit.of_iso_limit hF (functor.map_iso _ (is_limit.unique h h'))⟩ /-- If F preserves one colimit cocone for the diagram K, then it preserves any colimit cocone for K. -/ def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K} (h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F := ⟨λ t' h', is_colimit.of_iso_colimit hF (functor.map_iso _ (is_colimit.unique h h'))⟩ /- A functor F : C → D reflects limits if whenever the image of a cone under F is a limit cone in D, the cone was already a limit cone in C. Note that again we do not assume a priori that D actually has any limits. -/ class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c) class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c) class reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_limit : Π {K : J ⥤ C}, reflects_limit K F) class reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_colimit : Π {K : J ⥤ C}, reflects_colimit K F) class reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F) class reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F) instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_limits_of_shape J F] : reflects_limit K F := reflects_limits_of_shape.reflects_limit J F instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_colimits_of_shape J F] : reflects_colimit K F := reflects_colimits_of_shape.reflects_colimit J F instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D) [H : reflects_limits F] : reflects_limits_of_shape J F := reflects_limits.reflects_limits_of_shape F instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D) [H : reflects_colimits F] : reflects_colimits_of_shape J F := reflects_colimits.reflects_colimits_of_shape F instance id_reflects_limits : reflects_limits (functor.id C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_reflects_colimits : reflects_colimits (functor.id C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } section variables {E : Type u₃} [ℰ : category.{v+1} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] : reflects_limit K (F ⋙ G) := ⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩ instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] : reflects_colimit K (F ⋙ G) := ⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩ end end category_theory.limits
84dcba6557c31ecc39ed86efacb79f03be7ce1a0
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/basic_monitor.lean
9d5f90c960e83be93ba5425852b6685952fa5443
[ "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
303
lean
meta def basic_monitor : vm_monitor nat := { init := 0, step := λ s, return (trace ("step " ++ s^.to_string) (s+1)) } run_command vm_monitor.register `basic_monitor set_option debugger true example (a b : Prop) : a → b → a ∧ b := begin intros, constructor, assumption, assumption end
e9b93e8f3da93e69ec8fd19fb83e739d61c2145e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/termparsertest1.lean
e430fd966a0419890c0543fc0ca7b0ddc218e167
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,706
lean
import init.lean.parser.term open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; termPTables ← builtinTermParsingTable.get; stx ← IO.ofExcept $ runParser env termPTables input "<input>" "expr"; IO.println stx def test (is : List String) : IO Unit := is.mfor $ fun input => do IO.println input; testParser input def testParserFailure (input : String) : IO Unit := do env ← mkEmptyEnvironment; termPTables ← builtinTermParsingTable.get; match runParser env termPTables input "<input>" "expr" with | Except.ok stx => throw (IO.userError ("unexpected success\n" ++ toString stx)) | Except.error msg => IO.println ("failed as expected, error: " ++ msg) def testFailures (is : List String) : IO Unit := is.mfor $ fun input => do IO.println input; testParserFailure input def main (xs : List String) : IO Unit := do test [ "Prod.mk", "x.{u, v+1}", "x.{u}", "x", "x.{max u v}", "x.{max u v, 0}", "f 0 1", "f.{u+1} \"foo\" x", "(f x, 0, 1)", "()", "(f x)", "(f x : Type)", "h (f x) (g y)", "if x then f x else g x", "if h : x then f x h else g x h", "have p x y from f x; g this", "suffices h : p x y from f x; g this", "show p x y from f x", "fun x y => f y x", "fun (x y : Nat) => f y x", "fun (x, y) => f y x", "fun z (x, y) => f y x", "fun ⟨x, y⟩ ⟨z, w⟩ => f y x w z", "fun (Prod.mk x y) => f y x", "{ x := 10, y := 20 }", "{ x := 10, y := 20, }", "{ x // p x 10 }", "{ x : Nat // p x 10 }", "{ .. }", "{ Prod . fst := 10, .. }", "a[i]", "f [10, 20]", "g a[x+2]", "g f.a.1.2.bla x.1.a", "x+y*z < 10/3", "id (α := Nat) 10", "(x : a)", "a -> b", "{x : a} -> b", "{a : Type} -> [ToString a] -> (x : a) -> b", "f ({x : a} -> b)", "f (x : a) -> b", "f ((x : a) -> b)", "(f : (n : Nat) → Vector Nat n) -> Nat", "∀ x y (z : Nat), x > y -> x > y - z", " match x with | some x => true | none => false", " match x with | some y => match y with | some (a, b) => a + b | none => 1 | none => 0 ", "Type u", "Sort v", "Type 1", "f Type 1", "let x := 0; x + 1", "let x : Nat := 0; x + 1", "let f (x : Nat) := x + 1; f 0", "let f {α : Type} (a : α) : α := a; f 10", "let f (x) := x + 1; f 10 + f 20", "let (x, y) := f 10; x + y", "let { fst := x, .. } := f 10; x + x", "let x.y := f 10; x", "let x.1 := f 10; x", "let x[i].y := f 10; x", "let x[i] := f 20; x", "-x + y", "!x", "¬ a ∧ b", " do x ← f a; x : Nat ← f a; g x; let y := g x; (a, b) <- h x y; let (a, b) := (b, a); pure (a + b)", "do { x ← f a; pure $ a + a }", "let f : Nat → Nat → Nat | 0 a := a + 10 | (n+1) b := n * b; f 20", "'a'", "f 'a' 'b'" ]; testFailures [ "f {x : a} -> b", "(x := 20)", "let x 10; x", "let x := y" ]
1273ae2294dca6f42253a8341eaae50b6a88b51f
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/list/perm.lean
f3278bc685c9a847cd72eecf99615874ee101d04
[ "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
41,064
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro List permutations. -/ import data.list.basic logic.relation namespace list universe variables uu vv variables {α : Type uu} {β : Type vv} /-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list α → list α → Prop | nil : perm [] [] | skip : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ open perm infix ~ := perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := skip x (perm.refl xs) @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) theorem perm.swap' (x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := trans (swap _ _ _) (skip _ $ skip _ p) attribute [trans] perm.trans theorem perm.eqv (α : Type) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance is_setoid (α : Type) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem perm_subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := λ a, perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem mem_of_perm {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (λ m, perm_subset h m) (λ m, perm_subset h.symm m) theorem perm_app_left {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂ | [] p := p | (x::xs) p := skip x (perm_app_right xs p) theorem perm_app {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ := trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) theorem perm_app_cons (a : α) {h₁ h₂ t₁ t₂ : list α} (p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ := perm_app p₁ (skip a p₂) @[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂) | [] l₂ := perm.refl _ | (b::l₁) l₂ := (skip b (@perm_middle l₁ l₂)).trans (swap a b _) @[simp] theorem perm_cons_app (a : α) (l : list α) : l ++ [a] ~ a::l := by simpa using @perm_middle _ a l [] @[simp] theorem perm_app_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := (skip a perm_app_comm).trans perm_middle.symm theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l := by simp theorem perm_length {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem eq_nil_of_perm_nil {l₁ : list α} (p : [] ~ l₁) : l₁ = [] := eq_nil_of_length_eq_zero (perm_length p).symm theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, eq_nil_of_perm_nil p.symm, λ e, e ▸ perm.refl _⟩ theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l | p := by injection eq_nil_of_perm_nil p theorem eq_singleton_of_perm {a b : α} (p : [a] ~ [b]) : a = b := by simpa using perm_subset p (by simp) theorem eq_singleton_of_perm_inv {a : α} {l : list α} (p : [a] ~ l) : l = [a] := match l, show 1 = _, from perm_length p, p with | [a'], rfl, p := by rw [eq_singleton_of_perm p] end @[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l | [] := perm.nil | (a::l) := by rw reverse_cons; exact (perm_cons_app _ _).trans (skip a $ reverse_perm l) theorem perm_cons_app_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := trans (skip a p) perm_middle.symm @[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l := ⟨λ p, (eq_repeat.2 $ by exact ⟨by simpa using (perm_length p).symm, λ b m, eq_of_mem_repeat $ perm_subset p.symm m⟩).symm, λ h, h ▸ perm.refl _⟩ theorem perm_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in e₂.symm ▸ e₁.symm ▸ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ @[congr] theorem perm_filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : filter_map f l₁ ~ filter_map f l₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [filter_map], cases f x with a; simp [filter_map, IH, skip] }, { simp [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IH₂ } end @[congr] theorem perm_map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := by rw ← filter_map_eq_map; apply perm_filter_map _ p theorem perm_pmap {p : α → Prop} (f : Π a, p a → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [IH, skip] }, { simp [swap] }, { refine IH₁.trans IH₂, exact λ a m, H₂ a (perm_subset p₂ m) } end theorem perm_filter (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ := by rw ← filter_map_eq_filter; apply perm_filter_map _ s theorem exists_perm_sublist {l₁ l₂ l₂' : list α} (s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', skip x p', s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in ⟨r₁, pr.trans pm, sr⟩ } end section rel open relator variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ }, case perm.skip : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩, exact ⟨b::l₂, forall₂.cons hab h₁₂, perm.skip _ h₂₃⟩ }, case perm.swap : a₁ a₂ l₁ l₂ h₂₃ { cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃, cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂, exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ { rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩, rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩, exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ } end lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩, have : forall₂ (flip r) l₂ l₁, from h₁₂.flip , rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩, exact ⟨l', h₂.symm, h₁.flip⟩ }, { exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm := assume a b h₁ c d h₂ h, have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩, have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d, by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forall₂ @hr hcb hbc, this ▸ hbd lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp (assume a b c, left_unique_flip hr.1) hab.flip hcd.flip) end rel section subperm /-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂ infix ` <+~ `:50 := subperm theorem nil_subperm {l : list α} : [] <+~ l := ⟨[], perm.nil, by simp⟩ theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂, from ⟨this p, this p.symm⟩, λ l₁ l₂ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem subperm_of_sublist {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, perm.refl _, s⟩ theorem subperm_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, sublist.refl _⟩ theorem subperm.refl (l : list α) : l <+~ l := subperm_of_perm (perm.refl _) theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃ | s ⟨l₂', p₂, s₂⟩ := let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩ theorem length_le_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨l, p, s⟩ := perm_length p ▸ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨l, p, s⟩ h := suffices l = l₂, from this ▸ p.symm, eq_of_sublist_of_length_le s $ perm_length p.symm ▸ h theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le (length_le_of_subperm h₂) theorem subset_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨l, p, s⟩ := subset.trans (perm_subset p.symm) (subset_of_sublist s) end subperm theorem exists_perm_append_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ l₂ a s) := let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨a::l, (skip a p).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ l₂ a s) := let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, skip a p⟩ theorem perm_countp (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact perm_length (perm_filter _ s) theorem countp_le_of_subperm (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂ | ⟨l, p', s⟩ := perm_countp p p' ▸ countp_le_of_sublist s theorem perm_count [decidable_eq α] {l₁ l₂ : list α} (p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ := perm_countp _ p theorem count_le_of_subperm [decidable_eq α] {l₁ l₂ : list α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := countp_le_of_subperm _ s theorem foldl_eq_of_perm {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, r (f b x)) (λ x y t₁ t₂ p r b, by simp; rw rcomm; exact r (f (f b x) y)) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) theorem foldr_eq_of_perm {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) lemma rec_heq_of_perm {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α} (hl : perm l l') (f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b') (f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec α β b f l == @list.rec α β b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.skip : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ } end section variables {op : α → α → α} [is_associative α op] [is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma fold_op_eq_of_perm {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a := foldl_eq_of_perm (right_comm _ (is_commutative.comm _) (is_associative.assoc _)) h _ end section comm_monoid open list variable [comm_monoid α] @[to_additive list.sum_eq_of_perm] lemma prod_eq_of_perm {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ := by induction h; simp [*, mul_left_comm] @[to_additive list.sum_reverse] lemma prod_reverse (l : list α) : prod l.reverse = prod l := prod_eq_of_perm $ reverse_perm l end comm_monoid theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂, intro p, revert l₁ l₂ r₁ r₂ e₁ e₂, refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases l₂ with z l₂; dsimp at e₁ e₂; injections; subst x, { substs t₁ t₂, exact p }, { substs z t₁ t₂, exact p.trans perm_middle }, { substs y t₁ t₂, exact perm_middle.symm.trans p }, { substs z t₁ t₂, exact skip y (IH rfl rfl) } }, { rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩; dsimp at e₁ e₂; injections; substs x y, { substs r₁ r₂, exact skip a p }, { substs r₁ r₂, exact skip u p }, { substs r₁ v t₂, exact skip u (p.trans perm_middle) }, { substs r₁ r₂, exact skip y p }, { substs r₁ r₂ y u, exact skip a p }, { substs r₁ u v t₂, exact (skip y $ p.trans perm_middle).trans (swap _ _ _) }, { substs r₂ z t₁, exact skip y (perm_middle.symm.trans p) }, { substs r₂ y z t₁, exact (swap _ _ _).trans (skip u $ perm_middle.symm.trans p) }, { substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } }, { substs t₁ t₃, have : a ∈ t₂ := perm_subset p₁ (by simp), rcases mem_split this with ⟨l₂, r₂, e₂⟩, subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) } end theorem perm_cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := @perm_inv_core _ _ [] [] _ _ theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ := ⟨perm_cons_inv, skip a⟩ theorem perm_app_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_app_left_iff l) theorem perm_app_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ := ⟨λ p, (perm_app_left_iff _).1 $ trans perm_app_comm $ trans p perm_app_comm, perm_app_left _⟩ theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ := begin refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩, cases o₁ with a; cases o₂ with b, {refl}, { cases (perm_length p) }, { cases (perm_length p) }, { exact option.mem_to_list.1 ((mem_of_perm p).2 $ by simp) } end theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ subperm_of_sublist $ sublist_cons _ _).trans (subperm_of_sublist s') }, { exact ⟨u, perm_cons_inv p, s'⟩ } end, λ ⟨l, p, s⟩, ⟨a::l, skip a p, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases h₂ }, case list.sublist.cons : r₁ r₂ b s' ih { simp at h₂, cases h₂ with e m, { subst b, exact ⟨a::r₁, skip a p, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ r₂ b s' ih { have bm : b ∈ l₁ := (perm_subset p $ mem_cons_self _ _), have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm), rcases mem_split bm with ⟨t₁, t₂, rfl⟩, have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (λ x, subset_of_sublist st x) h₁) (perm_cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (skip b p').trans $ (swap _ _ _).trans (skip a perm_middle.symm), s'.cons2 _ _ _⟩ } end theorem subperm_app_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_app_left l) theorem subperm_app_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ := (perm_app_comm.subperm_left.trans perm_app_comm.subperm_right).trans (subperm_app_left l) theorem subperm.exists_of_length_lt {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂ | ⟨l, p, s⟩ h := suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from (this $ perm_length p.symm ▸ h).imp (λ a, (skip a p).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename l₂ u, induction s with l₁ l₂ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h, { exact (IH h).imp (λ a s, s.trans (subperm_of_sublist $ sublist_cons _ _)) }, { exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ H₂, simp at h, exact cons_subperm_of_mem d h H₁ (IH H₂) } end theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ := ⟨λ p a, mem_of_perm p, λ H, subperm.antisymm (subperm_of_subset_nodup d₁ (λ a, (H a).1)) (subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩ theorem perm_ext_sublist_nodup {l₁ l₂ l : list α} (d : nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := ⟨λ h, begin induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁, { exact eq_nil_of_perm_nil h.symm }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subset_of_subperm ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subset_of_subperm ⟨_, h, s₁⟩ (mem_cons_self _ _) }, { rw IH d.2 s₁ (perm_cons_inv h) } } end, λ h, by rw h⟩ section variable [decidable_eq α] -- attribute [congr] theorem erase_perm_erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from perm_subset p h₁, perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase h₂) else have h₂ : a ∉ l₂, from mt (mem_of_perm p).2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l := ⟨l.erase a, perm.refl _, erase_sublist _ _⟩ theorem erase_subperm_erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h in ⟨l.erase a, erase_perm_erase _ hp, erase_sublist_erase _ hs⟩ theorem perm_diff_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, erase_perm_erase] theorem perm_diff_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l; simp [*, erase_perm_erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ | l₁ [] := ⟨a::l₁, by simp⟩ | l₁ (b::l₂) := begin repeat {rw diff_cons}, by_cases heq : a = b, { by_cases b ∈ l₁, { rw perm.subperm_right, apply subperm_cons_diff, simp [perm_diff_left, heq, perm_erase h] }, { simp [subperm_of_sublist, sublist.cons, h, heq] } }, { simp [heq, subperm_cons_diff] } end theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subset_of_subperm subperm_cons_diff theorem perm_bag_inter_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, skip] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, skip] }, { simp [xt, yt, mt mem_of_mem_erase, skip] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm_bag_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ := begin induction l with a l IH generalizing t₁ t₂ p, {simp}, by_cases a ∈ t₁, { simp [h, (mem_of_perm p).1 h, IH (erase_perm_erase _ p)] }, { simp [h, mt (mem_of_perm p).2 h, IH p] } end theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a := ⟨λ h, have a ∈ l₂, from perm_subset h (mem_cons_self a l₁), ⟨this, perm_cons_inv $ h.trans $ perm_erase this⟩, λ ⟨m, h⟩, trans (skip a h) (perm_erase m).symm⟩ theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := ⟨perm_count, λ H, begin induction l₁ with a l₁ IH generalizing l₂, { cases l₂ with b l₂, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine trans (skip a $ IH $ λ b, _) (perm_erase this).symm, specialize H b, rw perm_count (perm_erase this) at H, by_cases b = a; simp [h] at H ⊢; assumption } end⟩ instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) | [] [] := is_true $ perm.refl _ | [] (b::l₂) := is_false $ λ h, by have := eq_nil_of_perm_nil h; contradiction | (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm_erase_dup_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : erase_dup l₁ ~ erase_dup l₂ := perm_iff_count.2 $ λ a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, perm_subset p h] else by simp [h, mt (mem_of_perm p).2 h] -- attribute [congr] theorem perm_insert (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ := if h : a ∈ l₁ then by simpa [h, perm_subset p h] using p else by simpa [h, mt (mem_of_perm p).2 h] using skip a p theorem perm_insert_swap (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm_union_left {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact perm_insert a ih }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm_union_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l; simp [*, perm_insert] -- @[congr] theorem perm_union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) theorem perm_inter_left {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := perm_filter _ theorem perm_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := by dsimp [(∩), list.inter]; congr; funext a; rw [mem_of_perm p] -- @[congr] theorem perm_inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := perm_inter_right l₂ p₂ ▸ perm_inter_left t₁ p₁ end theorem perm_pairwise {R : α → α → Prop} (S : symmetric R) : ∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ := suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩, λ l₁ l₂ p d, begin induction d with a l₁ h d IH generalizing l₂, { rw eq_nil_of_perm_nil p, constructor }, { have : a ∈ l₂ := perm_subset p (mem_cons_self _ _), rcases mem_split this with ⟨s₂, t₂, rfl⟩, have p' := perm_cons_inv (p.trans perm_middle), refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (perm_subset p'.symm m) } end theorem perm_nodup {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) := perm_pairwise $ @ne.symm α theorem perm_bind_left {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) : l₁.bind f ~ l₂.bind f := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app_right _ IH }, { simp, rw [← append_assoc, ← append_assoc], exact perm_app_left _ perm_app_comm }, { exact trans IH₁ IH₂ } end theorem perm_bind_right (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact perm_app (h a) IH theorem perm_product_left {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ := perm_bind_left _ p theorem perm_product_right (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ := perm_bind_right _ $ λ a, perm_map _ p @[congr] theorem perm_product {l₁ l₂ : list α} {t₁ t₂ : list β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ := trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) theorem sublists_cons_perm_append (a : α) (l : list α) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp [sublists, sublists_aux_cons_cons], refine skip _ ((skip _ _).trans perm_middle.symm), induction sublists_aux l cons with b l IH; simp, exact skip b ((skip _ IH).trans perm_middle.symm) end theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (perm_app IH (perm_map _ IH)) theorem revzip_sublists (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := begin rw revzip, apply list.reverse_rec_on l, { intros l₁ l₂ h, simp at h, simp [h] }, { intros l a IH l₁ l₂ h, rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { rw ← append_assoc, exact perm_app_left _ (IH _ _ h) }, { rw append_assoc, apply (perm_app_right _ perm_app_comm).trans, rw ← append_assoc, exact perm_app_left _ (IH _ _ h) } } end theorem revzip_sublists' (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := begin rw revzip, induction l with a l IH; intros l₁ l₂ h, { simp at h, simp [h] }, { rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { exact perm_middle.trans (skip _ (IH _ _ h)) }, { exact skip _ (IH _ _ h) } } end theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α} (H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁) (p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ := begin let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { cases h : f a, { simp [h], exact (IH (pairwise_cons.1 H).2).skip _ }, { simp [lookmap_cons_some _ _ h], exact p.skip _ } }, { cases h₁ : f a with c; cases h₂ : f b with d, { simp [h₁, h₂], apply swap }, { simp [h₁, lookmap_cons_some _ _ h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂], rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩, refl } }, { refine (IH₁ H).trans (IH₂ ((perm_pairwise _ p₁).1 H)), exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm } end theorem perm_erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α} (H : pairwise (λ a b, f a → f b → false) l₁) (p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ := begin let F := λ a b, f a → f b → false, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { by_cases h : f a, { simp [h, p] }, { simp [h], exact (IH (pairwise_cons.1 H).2).skip _ } }, { by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂], { cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ }, { apply swap } }, { refine (IH₁ H).trans (IH₂ ((perm_pairwise _ p₁).1 H)), exact λ a b h h₁ h₂, h h₂ h₁ } end /- enumerating permutations -/ section permutations theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, { rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split; intro h, { rcases h with e | ⟨l₁, l₂, l0, ye, _⟩, { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } }, { rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩, { simp [ye] }, { simp at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } } end theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2 theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} : l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := have (∃ (a : list α), a ∈ L ∧ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts), from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩, λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α)) (n) (H : ∀ l ∈ L, length l = n) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, simp [ih (λ l m, H l (mem_cons_of_mem _ m)), H l (mem_cons_self _ _), mul_add] end theorem perm_of_mem_permutations_aux : ∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, l₂, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ l₂ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil ▸ IH2 m }, exact (perm_app_left _ (perm_middle.trans (skip _ p))).trans (skip _ perm_app_comm) } end theorem perm_of_mem_permutations {l₁ l₂ : list α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ := (eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _) (λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m) theorem length_permutations_aux : ∀ ts is : list α, length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length.fact, { simpa using IH2 }, simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (λ l m, perm_length (perm_of_mem_permutations m)), permutations, length, length, IH2, nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list α) : length (permutations l) = (length l).fact := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list α} (H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : ∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (perm_subset p'.symm (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩, subst is', have p := perm_cons_inv (perm_middle.symm.trans p'), cases l₂ with a l₂', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::l₂', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ end permutations end list
41c7affc5e3c814e81d59896f04228d5eddff6a4
626e312b5c1cb2d88fca108f5933076012633192
/src/tactic/lint/type_classes.lean
bc321777686ee830daea9f730c69a4902733a3d2
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,046
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority. * `has_inhabited_instances` checks that every type has an `inhabited` instance. * `impossible_instance` checks that there are no instances which can never apply. * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments. * `dangerous_instance` checks for instances that generate subproblems with metavariables. * `fails_quickly` checks that type class resolution finishes quickly. * `class_structure` checks that every `class` is a structure, i.e. `@[class] def` is forbidden. * `has_coe_variable` checks that there is no instance of type `has_coe α t`. * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]`. * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. * `linter.has_coe_to_fun` checks whether necessary `has_coe_to_fun` instances are declared. * `linter.check_reducibility` checks whether non-instances with a class as type are reducible. -/ open tactic /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-- checks whether an instance that always applies has priority ≥ 1000. -/ private meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do (_, tp) ← open_pis d.type, tp ← whnf tp transparency.none, let (fn, args) := tp.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_local_constant ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- There are places where typeclass arguments are specified with implicit `{}` brackets instead of the usual `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type of one of the other arguments. When they can be inferred from these other arguments, it is faster to use this method than to use type class inference. For example, when writing lemmas about `(f : α →+* β)`, it is faster to specify the fact that `α` and `β` are `semiring`s as `{rα : semiring α} {rβ : semiring β}` rather than the usual `[semiring α] [semiring β]`. -/ library_note "implicit instance arguments" /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good.", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. See note [lower instance priority] for instructions to change the priority.", auto_decls := tt } /-- Reports declarations of types that do not have an associated `inhabited` instance. -/ private meta def has_inhabited_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← open_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, auto_decls := ff, no_errors_found := "No types have missing inhabited instances.", errors_found := "TYPES ARE MISSING INHABITED INSTANCES:", is_fast := ff } attribute [nolint has_inhabited_instance] pempty /-- Checks whether an instance can never be applied. -/ private meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter] meta def linter.impossible_instance : linter := { test := impossible_instance, auto_decls := tt, no_errors_found := "All instances are applicable.", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and " ++ "therefore can never succeed. Either mark the arguments with square brackets (if it is a " ++ "class), or don't make it an instance." } /-- Checks whether an instance can never be applied. -/ private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← open_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, auto_decls := tt, no_errors_found := "All declarations have correct type-class arguments.", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]:" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ private meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← open_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances.", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new " ++ "type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked " ++ "with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Applies expression `e` to local constants, but lifts all the arguments that are `Sort`-valued to `Type`-valued sorts. -/ meta def apply_to_fresh_variables (e : expr) : tactic expr := do t ← infer_type e, (xs, b) ← open_pis t, xs.mmap' $ λ x, try $ do { u ← mk_meta_univ, tx ← infer_type x, ttx ← infer_type tx, unify ttx (expr.sort u.succ) }, return $ e.app_of_list xs /-- Tests whether type-class inference search for a class will end quickly when applied to variables. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised. We make sure that we apply the tactic to variables living in `Type u` instead of `Sort u`, because many instances only apply in that special case, and we do want to catch those loops. -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := do e ← mk_const d.to_name, tt ← is_class e | return none, e' ← apply_to_fresh_variables e, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ succeeds_or_fails_with_msg (mk_instance e') $ λ s, "tactic.mk_instance failed to generate instance for".is_prefix_of s | return none, return $ some $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. If we want to increase the maximum number of steps type-class inference is allowed to take, we can increase the number `3000` in the definition. As of 5 Mar 2020 the longest trace (for `is_add_hom`) takes 2900-3000 "heartbeats". -/ @[linter] meta def linter.fails_quickly : linter := { test := fails_quickly 3000, auto_decls := tt, no_errors_found := "No type-class searches timed out.", errors_found := "TYPE CLASS SEARCHES TIMED OUT. For the following classes, there is an instance that causes a loop, or an excessively long search. It is common that this instance is for a very different class than the one flagged below. To debug: (1) run `scripts/mk_all.sh` and create a file with `import all` and `set_option trace.class_instances true` (2) Create an example where you are proving the class on a type with no extra information (other than the classes needed to write down this class) and try to prove it using `by apply_instance`. For example, if `topological_group` raises an error, run ``` example (G : Type*) [topological_space G] [group G] : topological_group G := by apply_instance ``` (3) What error do you get? (3a) The expected error is \"tactic.mk_instance failed to generate instance\" If you get this error, there might be nothing wrong. Check the trace to see if type-class inference takes any unnecessary long unexpected turns. If not, feel free to increase the value in the definition of the linter `fails_quickly`. (3b) If the error is \"maximum class-instance resolution depth has been reached\" there is almost certainly a loop in the type-class inference. Find which instance causes the type-class inference to go astray, and fix that instance.", is_fast := tt } /-- Checks that all uses of the `@[class]` attribute apply to structures or inductive types. This is future-proofing for lean 4, which no longer supports `@[class] def`. -/ private meta def class_structure (n : name) : tactic (option string) := do is_class ← has_attribute' `class n, if is_class then do env ← get_env, pure $ if env.is_inductive n then none else "is a non-structure or inductive type marked @[class]" else pure none /-- A linter object for `class_structure`. -/ @[linter] meta def linter.class_structure : linter := { test := λ d, class_structure d.to_name, auto_decls := tt, no_errors_found := "All classes are structures.", errors_found := "USE OF @[class] def IS DISALLOWED:" } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable, or `has_coe t α` where `α` does not occur in `t`. See note [use has_coe_t]. -/ private meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a %%b) ← return d.type.pi_codomain | return none, if a.is_var then return $ some $ "illegal instance, first argument is variable" else if b.is_var ∧ ¬ b.occurs a then return $ some $ "illegal instance, second argument is variable not occurring in first argument" else return none /-- A linter object for `has_coe_variable`. -/ @[linter] meta def linter.has_coe_variable : linter := { test := has_coe_variable, auto_decls := tt, no_errors_found := "No invalid `has_coe` instances.", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ private meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_nondep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, auto_decls := ff, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`.", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _` hypothesis that is unused lsewhere in the type. In this case, that hypothesis can be replaced with `classical` in the proof. Theorems in the `decidable` namespace are exempt from the check. -/ private meta def decidable_classical (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, ff ← pure $ (`decidable).is_prefix_of d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq ∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel ∨ pr.2.type.is_app_of `decidable, if deceq_binders.length = 0 then return none else (λ s, some $ "The following `decidable` hypotheses should be replaced with `classical` in the proof. " ++ s) <$> print_arguments deceq_binders /-- A linter object for `decidable_classical`. -/ @[linter] meta def linter.decidable_classical : linter := { test := decidable_classical, auto_decls := ff, no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`.", errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." } /- The file `logic/basic.lean` emphasizes the differences between what holds under classical and non-classical logic. It makes little sense to make all these lemmas classical, so we add them to the list of lemmas which are not checked by the linter `decidable_classical`. -/ attribute [nolint decidable_classical] dec_em dec_em' not.decidable_imp_symm private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) := retrieve $ do tt ← return d.is_trusted | pure none, mk_meta_var d.type >>= set_goals ∘ pure, args ← unfreezing intros, expr.sort _ ← target | pure none, let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args, some coe_fn_inst ← try_core $ to_expr ``(_root_.has_coe_to_fun %%ty) >>= mk_instance | pure none, some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ← try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _) | pure none, tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none, set_bool_option `pp.all true, trans_inst_1 ← pp trans_inst_1, trans_inst_2 ← pp trans_inst_2, pure $ format.to_string $ "`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++ trans_inst_1.group.indent 2 ++ format.line ++ "and" ++ trans_inst_2.group.indent 2 /-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/ @[linter] meta def linter.has_coe_to_fun : linter := { test := has_coe_to_fun_linter, auto_decls := tt, no_errors_found := "has_coe_to_fun is used correctly", errors_found := "INVALID/MISSING `has_coe_to_fun` instances. You should add a `has_coe_to_fun` instance for the following types. See Note [function coercion]." } /-- Checks whether an instance contains a semireducible non-instance with a class as type in its value. We add some restrictions to get not too many false positives: * We only consider classes with an `add` or `mul` field, since those classes are most likely to occur as a field to another class, and be an extension of another class. * We only consider instances of type-valued classes and non-instances that are definitions. * We currently ignore declarations `foo` that have a `foo._main` declaration. We could look inside, or at the generated equation lemmas, but it's unlikely that there are many problematic instances defined using the equation compiler. -/ meta def check_reducible_non_instances (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, ff ← is_prop d.type | return none, env ← get_env, -- We only check if the class of the instance contains an `add` or a `mul` field. let cls := d.type.pi_codomain.get_app_fn.const_name, some constrs ← return $ env.structure_fields cls | return none, tt ← return $ constrs.mem `add || constrs.mem `mul | return none, l ← d.value.list_constant.mfilter $ λ nm, do { d ← env.get nm, ff ← is_instance nm | return ff, tt ← is_class d.type | return ff, tt ← return d.is_definition | return ff, -- We only check if the class of the non-instance contains an `add` or a `mul` field. let cls := d.type.pi_codomain.get_app_fn.const_name, some constrs ← return $ env.structure_fields cls | return ff, tt ← return $ constrs.mem `add || constrs.mem `mul | return ff, ff ← has_attribute' `reducible nm | return ff, return tt }, if l.empty then return none else -- we currently ignore declarations that have a `foo._main` declaration. if l.to_list = [d.to_name ++ `_main] then return none else return $ some $ "This instance contains the declarations " ++ to_string l.to_list ++ ", which are semireducible non-instances." /-- A linter that checks whether an instance contains a semireducible non-instance. -/ @[linter] meta def linter.check_reducibility : linter := { test := check_reducible_non_instances, auto_decls := ff, no_errors_found := "All non-instances are reducible.", errors_found := "THE FOLLOWING INSTANCES MIGHT NOT REDUCE. These instances contain one or more declarations that are not instances and are also not marked `@[reducible]`. This means that type-class inference cannot unfold these declarations, " ++ "which might mean that type-class inference cannot infer that two instances are definitionally " ++ "equal. This can cause unexpected errors when this class occurs " ++ "as an *argument* to a type-class problem. See note [reducible non-instances].", is_fast := tt }
b17f65fc9607a625a9a220e27b01ae0ef48e8fd2
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/cubical/square.hlean
f1ecce4dee002bc2a16dc650a25dbfd135f5acb9
[ "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
19,162
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Squares in a type -/ import types.eq open eq equiv is_equiv namespace eq variables {A B : Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A} /-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ inductive square {A : Type} {a₀₀ : A} : Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type := ids : square idp idp idp idp /- square top bottom left right -/ variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} definition ids [reducible] [constructor] := @square.ids definition idsquare [reducible] [constructor] (a : A) := @square.ids A a definition hrefl [unfold 4] (p : a = a') : square idp idp p p := by induction p; exact ids definition vrefl [unfold 4] (p : a = a') : square p p idp idp := by induction p; exact ids definition hrfl [reducible] [unfold 4] {p : a = a'} : square idp idp p p := !hrefl definition vrfl [reducible] [unfold 4] {p : a = a'} : square p p idp idp := !vrefl definition hdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square idp idp p q := by induction r;apply hrefl definition vdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square p q idp idp := by induction r;apply vrefl definition hconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁) : square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ := by induction s₃₁; exact s₁₁ definition vconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃) : square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) := by induction s₁₃; exact s₁₁ definition hinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ := by induction s₁₁;exact ids definition vinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ := by induction s₁₁;exact ids definition eq_vconcat [unfold 11] {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ p₂₁ := by induction r; exact s₁₁ definition vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : square p₁₀ p p₀₁ p₂₁ := by induction r; exact s₁₁ definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := by induction r; exact s₁₁ definition hconcat_eq [unfold 11] {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := by induction r; exact s₁₁ infix `⬝h`:75 := hconcat infix `⬝v`:75 := vconcat infix `⬝hp`:75 := hconcat_eq infix `⬝vp`:75 := vconcat_eq infix `⬝ph`:75 := eq_hconcat infix `⬝pv`:75 := eq_vconcat postfix `⁻¹ʰ`:(max+1) := hinverse postfix `⁻¹ᵛ`:(max+1) := vinverse definition transpose [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ := by induction s₁₁;exact ids definition aps {B : Type} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) := by induction s₁₁;exact ids definition natural_square [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') : square (ap f q) (ap g q) (p a) (p a') := eq.rec_on q hrfl definition natural_square_tr [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') : square (p a) (p a') (ap f q) (ap g q) := eq.rec_on q vrfl definition whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ := by induction s₁₁;induction p;exact ids definition whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) := by induction p;exact s₁₁ /- some higher ∞-groupoid operations -/ definition vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝v vrefl p₁₂ = s₁₁ := by induction s₁₁; reflexivity definition hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝h hrefl p₂₁ = s₁₁ := by induction s₁₁; reflexivity /- equivalences -/ definition eq_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ := by induction s₁₁; apply idp definition square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₁₂; esimp [concat] at r; induction r; induction p₂₁; induction p₁₀; exact ids definition eq_top_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ := by induction s₁₁; apply idp definition square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₂; esimp at r;induction r;induction p₁₀;exact ids definition eq_bot_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ := by induction s₁₁; apply idp definition square_equiv_eq [constructor] (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂) (l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b := begin fapply equiv.MK, { exact eq_of_square}, { exact square_of_eq}, { intro s, induction b, esimp [concat] at s, induction s, induction r, induction t, apply idp}, { intro s, induction s, apply idp}, end definition hdeg_square_equiv' [constructor] (p q : a = a') : square idp idp p q ≃ p = q := by transitivity _;apply square_equiv_eq;transitivity _;apply eq_equiv_eq_symm; apply equiv_eq_closed_right;apply idp_con definition vdeg_square_equiv' [constructor] (p q : a = a') : square p q idp idp ≃ p = q := by transitivity _;apply square_equiv_eq;apply equiv_eq_closed_right; apply idp_con definition eq_of_hdeg_square [reducible] {p q : a = a'} (s : square idp idp p q) : p = q := to_fun !hdeg_square_equiv' s definition eq_of_vdeg_square [reducible] {p q : a = a'} (s : square p q idp idp) : p = q := to_fun !vdeg_square_equiv' s definition top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃) : square (l ⬝ b ⬝ r⁻¹) b l r := by induction r;induction b;induction l;constructor definition bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄) : square t (l⁻¹ ⬝ t ⬝ r) l r := by induction r;induction t;induction l;constructor /- the following two equivalences have as underlying inverse function the functions hdeg_square and vdeg_square, respectively. See examples below the definition -/ definition hdeg_square_equiv [constructor] (p q : a = a') : square idp idp p q ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_hdeg_square}, { reflexivity} end definition vdeg_square_equiv [constructor] (p q : a = a') : square p q idp idp ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_vdeg_square}, { reflexivity} end -- example (p q : a = a') : to_inv (hdeg_square_equiv' p q) = hdeg_square := idp -- this fails example (p q : a = a') : to_inv (hdeg_square_equiv p q) = hdeg_square := idp definition eq_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : square q r (ap f p) (ap g p)) : q =[p] r := by induction p;apply pathover_idp_of_eq;exact eq_of_vdeg_square s definition square_of_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : q =[p] r) : square q r (ap f p) (ap g p) := by induction p;apply vdeg_square;exact eq_of_pathover_idp s /- interaction of equivalences with operations on squares -/ definition eq_pathover_equiv_square [constructor] {f g : A → B} (p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p] r ≃ square q r (ap f p) (ap g p) := equiv.MK square_of_pathover eq_pathover begin intro s, induction p, esimp [square_of_pathover,eq_pathover], exact ap vdeg_square (to_right_inv !pathover_idp (eq_of_vdeg_square s)) ⬝ to_left_inv !vdeg_square_equiv s end begin intro s, induction p, esimp [square_of_pathover,eq_pathover], exact ap pathover_idp_of_eq (to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s)) ⬝ to_left_inv !pathover_idp s end definition square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a} {r : f a' = g a'} (s' : q = q') (s : q' =[p] r) : square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s := by induction s;induction s';reflexivity definition square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a} {r r' : f a' = g a'} (s' : r = r') (s : q =[p] r) : square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' := by induction s;induction s';reflexivity definition square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a} {q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p] q') (s' : q' =[p'] q'') : square_of_pathover (s ⬝o s') = ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ := by induction s';induction s;esimp [ap_con,hconcat_eq];exact !vconcat_vrfl⁻¹ definition eq_of_square_hrfl [unfold 4] (p : a = a') : eq_of_square hrfl = idp_con p := by induction p;reflexivity definition eq_of_square_vrfl [unfold 4] (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ := by induction p;reflexivity definition eq_of_square_hdeg_square {p q : a = a'} (r : p = q) : eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ := by induction r;induction p;reflexivity definition eq_of_square_vdeg_square {p q : a = a'} (r : p = q) : eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ := by induction r;induction p;reflexivity definition eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝pv s₁₁) = whisker_right r p₂₁ ⬝ eq_of_square s₁₁ := by induction s₁₁;cases r;reflexivity definition eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right r p₁₂)⁻¹ := by induction r;reflexivity definition eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r := by induction r;reflexivity definition eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ := by induction s₁₁; induction r;reflexivity -- definition vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : -- square p₁₀ p p₀₁ p₂₁ := -- by induction r; exact s₁₁ -- definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := -- by induction r; exact s₁₁ -- definition hconcat_eq [unfold 11] {p : a₂₀ = a₂₂} -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := -- by induction r; exact s₁₁ -- the following definition is very slow, maybe it's interesting to see why? -- definition eq_pathover_equiv_square' {f g : A → B}(p : a = a') (q : f a = g a) (r : f a' = g a') -- : square q r (ap f p) (ap g p) ≃ q =[p] r := -- equiv.MK eq_pathover -- square_of_pathover -- (λs, begin -- induction p, rewrite [↑[square_of_pathover,eq_pathover], -- to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s), -- to_left_inv !pathover_idp s] -- end) -- (λs, begin -- induction p, rewrite [↑[square_of_pathover,eq_pathover],▸*, -- to_right_inv !(@pathover_idp A) (eq_of_vdeg_square s), -- to_left_inv !vdeg_square_equiv s] -- end) /- recursors for squares where some sides are reflexivity -/ definition rec_on_b [recursor] {a₀₀ : A} {P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type} {a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂} (s : square t idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), from eq.rec_on (eq_of_square s : t ⬝ r = l) (by induction r; induction t; exact H), left_inv (to_fun !square_equiv_eq) s ▸ H2 definition rec_on_r [recursor] {a₀₀ : A} {P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type} {a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂} (s : square t b l idp) (H : P ids) : P s := let p : l ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H), left_inv (to_fun !square_equiv_eq) s ▸ !inv_inv ▸ H2 definition rec_on_l [recursor] {a₀₁ : A} {P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}, square t b idp r → Type} {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂} (s : square t b idp r) (H : P ids) : P s := let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)), from eq.rec_on p (by induction r; induction t; exact H), left_inv (to_fun !square_equiv_eq) s ▸ !con_inv_cancel_right ▸ H2 definition rec_on_t [recursor] {a₁₀ : A} {P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type} {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂} (s : square idp b l r) (H : P ids) : P s := let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in assert H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)), from eq.rec_on p (by induction b; induction l; exact H), assert H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)), from eq.rec_on !con_inv_cancel_right H2, assert H4 : P (square_of_eq (eq_of_square s)), from eq.rec_on !inv_inv H3, proof left_inv (to_fun !square_equiv_eq) s ▸ H4 qed definition rec_on_tb [recursor] {a : A} {P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type} {b : A} {l : a = b} {r : a = b} (s : square idp idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), from eq.rec_on (eq_of_square s : idp ⬝ r = l) (by induction r; exact H), left_inv (to_fun !square_equiv_eq) s ▸ H2 definition rec_on_lr [recursor] {a : A} {P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type} {a' : A} {t : a = a'} {b : a = a'} (s : square t b idp idp) (H : P ids) : P s := let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in assert H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H), to_left_inv (!square_equiv_eq) s ▸ !inv_inv ▸ H2 --we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed definition whisker_square [unfold 14 15 16 17] (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂') (r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀' p₁₂' p₀₁' p₂₁' := by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s /- squares commute with some operations on 2-paths -/ definition square_inv2 {p₁ p₂ p₃ p₄ : a = a'} {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r) : square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) := by induction s;constructor definition square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃} {t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄} {t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄} (s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂) : square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) := by induction s₂;induction s₁;constructor -- definition square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂} -- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} -- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp) -- : square t b l r := -- sorry --by induction s end eq
1748a7b24f97c3ffd4e73331fce2c8bcae7a9ea9
63abd62053d479eae5abf4951554e1064a4c45b4
/archive/imo/imo1959_q1.lean
aa9b76720eeda0e64100f4a99ddbab957b7ec09f
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
904
lean
/- Copyright (c) 2020 Kevin Lacker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker -/ import tactic.ring open nat /-! # IMO 1959 Q1 Prove that the fraction `(21n+4)/(14n+3)` is irreducible for every natural number `n`. Since Lean doesn't have a concept of "irreducible fractions" per se, we just formalize this as saying the numerator and denominator are relatively prime. -/ lemma calculation (n k : ℕ) (h1 : k ∣ 21 * n + 4) (h2 : k ∣ 14 * n + 3) : k ∣ 1 := have h3 : k ∣ 2 * (21 * n + 4), from dvd_mul_of_dvd_right h1 2, have h4 : k ∣ 3 * (14 * n + 3), from dvd_mul_of_dvd_right h2 3, have h5 : 3 * (14 * n + 3) = 2 * (21 * n + 4) + 1, by ring, (nat.dvd_add_right h3).mp (h5 ▸ h4) theorem imo1959_q1 : ∀ n : ℕ, coprime (21 * n + 4) (14 * n + 3) := assume n, coprime_of_dvd' $ λ k hp h1 h2, calculation n k h1 h2
8ab511060ceb6fbd0b0da93f105496245e863517
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/types/equiv.hlean
53c39e9faa0fcd9a147a6385de59d436cfe5afcd
[ "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
6,780
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about the types equiv and is_equiv -/ import .fiber .arrow arity ..hprop_trunc open eq is_trunc sigma sigma.ops pi fiber function equiv equiv.ops namespace is_equiv variables {A B : Type} (f : A → B) [H : is_equiv f] include H /- is_equiv f is a mere proposition -/ definition is_contr_fiber_of_is_equiv [instance] (b : B) : is_contr (fiber f b) := is_contr.mk (fiber.mk (f⁻¹ b) (right_inv f b)) (λz, fiber.rec_on z (λa p, fiber_eq ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) (calc right_inv f b = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ((ap (f ∘ f⁻¹) p) ⬝ right_inv f b) : by rewrite inv_con_cancel_left ... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (right_inv f (f a) ⬝ p) : by rewrite ap_con_eq_con ... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (ap f (left_inv f a) ⬝ p) : by rewrite adj ... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite con.assoc ... = (ap f (ap f⁻¹ p))⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_compose ... = ap f (ap f⁻¹ p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_inv ... = ap f ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) ⬝ p : by rewrite ap_con))) definition is_contr_right_inverse : is_contr (Σ(g : B → A), f ∘ g ~ id) := begin fapply is_trunc_equiv_closed, {apply sigma_equiv_sigma_id, intro g, apply eq_equiv_homotopy}, fapply is_trunc_equiv_closed, {apply fiber.sigma_char}, fapply is_contr_fiber_of_is_equiv, apply (to_is_equiv (arrow_equiv_arrow_right (equiv.mk f H))), end definition is_contr_right_coherence (u : Σ(g : B → A), f ∘ g ~ id) : is_contr (Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) := begin fapply is_trunc_equiv_closed, {apply equiv.symm, apply sigma_pi_equiv_pi_sigma}, fapply is_trunc_equiv_closed, {apply pi_equiv_pi_id, intro a, apply (fiber_eq_equiv (fiber.mk (u.1 (f a)) (u.2 (f a))) (fiber.mk a idp))}, end omit H protected definition sigma_char : (is_equiv f) ≃ (Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a)) := equiv.MK (λH, ⟨inv f, right_inv f, left_inv f, adj f⟩) (λp, is_equiv.mk f p.1 p.2.1 p.2.2.1 p.2.2.2) (λp, begin induction p with p1 p2, induction p2 with p21 p22, induction p22 with p221 p222, reflexivity end) (λH, by induction H; reflexivity) protected definition sigma_char' : (is_equiv f) ≃ (Σ(u : Σ(g : B → A), f ∘ g ~ id), Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) := calc (is_equiv f) ≃ (Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a)) : is_equiv.sigma_char ... ≃ (Σ(u : Σ(g : B → A), f ∘ g ~ id), Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) : {sigma_assoc_equiv (λu, Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a))} local attribute is_contr_right_inverse [instance] [priority 1600] local attribute is_contr_right_coherence [instance] [priority 1600] theorem is_hprop_is_equiv [instance] : is_hprop (is_equiv f) := is_hprop_of_imp_is_contr (λ(H : is_equiv f), is_trunc_equiv_closed -2 (equiv.symm !is_equiv.sigma_char')) definition inv_eq_inv {A B : Type} {f f' : A → B} {Hf : is_equiv f} {Hf' : is_equiv f'} (p : f = f') : f⁻¹ = f'⁻¹ := apd011 inv p !is_hprop.elim /- contractible fibers -/ definition is_contr_fun [reducible] (f : A → B) := Π(b : B), is_contr (fiber f b) definition is_contr_fun_of_is_equiv [H : is_equiv f] : is_contr_fun f := is_contr_fiber_of_is_equiv f definition is_hprop_is_contr_fun (f : A → B) : is_hprop (is_contr_fun f) := _ /- we cannot make the next theorem an instance, because it loops together with is_contr_fiber_of_is_equiv -/ definition is_equiv_of_is_contr_fun [H : is_contr_fun f] : is_equiv f := adjointify _ (λb, point (center (fiber f b))) (λb, point_eq (center (fiber f b))) (λa, ap point (center_eq (fiber.mk a idp))) definition is_equiv_of_imp_is_equiv (H : B → is_equiv f) : is_equiv f := @is_equiv_of_is_contr_fun _ _ f (λb, @is_contr_fiber_of_is_equiv _ _ _ (H b) _) definition is_equiv_equiv_is_contr_fun : is_equiv f ≃ is_contr_fun f := equiv_of_is_hprop _ (λH, !is_equiv_of_is_contr_fun) end is_equiv namespace equiv open is_equiv variables {A B : Type} definition equiv_mk_eq {f f' : A → B} [H : is_equiv f] [H' : is_equiv f'] (p : f = f') : equiv.mk f H = equiv.mk f' H' := apd011 equiv.mk p !is_hprop.elim definition equiv_eq {f f' : A ≃ B} (p : to_fun f = to_fun f') : f = f' := by (cases f; cases f'; apply (equiv_mk_eq p)) protected definition equiv.sigma_char [constructor] (A B : Type) : (A ≃ B) ≃ Σ(f : A → B), is_equiv f := begin fapply equiv.MK, {intro F, exact ⟨to_fun F, to_is_equiv F⟩}, {intro p, cases p with f H, exact (equiv.mk f H)}, {intro p, cases p, exact idp}, {intro F, cases F, exact idp}, end definition equiv_eq_char (f f' : A ≃ B) : (f = f') ≃ (to_fun f = to_fun f') := calc (f = f') ≃ (to_fun !equiv.sigma_char f = to_fun !equiv.sigma_char f') : eq_equiv_fn_eq (to_fun !equiv.sigma_char) ... ≃ ((to_fun !equiv.sigma_char f).1 = (to_fun !equiv.sigma_char f').1 ) : equiv_subtype ... ≃ (to_fun f = to_fun f') : equiv.refl definition is_equiv_ap_to_fun (f f' : A ≃ B) : is_equiv (ap to_fun : f = f' → to_fun f = to_fun f') := begin fapply adjointify, {intro p, cases f with f H, cases f' with f' H', cases p, apply ap (mk f'), apply is_hprop.elim}, {intro p, cases f with f H, cases f' with f' H', cases p, apply @concat _ _ (ap to_fun (ap (equiv.mk f') (is_hprop.elim H H'))), {apply idp}, generalize is_hprop.elim H H', intro q, cases q, apply idp}, {intro p, cases p, cases f with f H, apply ap (ap (equiv.mk f)), apply is_hset.elim} end definition equiv_pathover {A : Type} {a a' : A} (p : a = a') {B : A → Type} {C : A → Type} (f : B a ≃ C a) (g : B a' ≃ C a') (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g := begin fapply change_path_equiv', { intro a, apply equiv.sigma_char}, { fapply sigma_pathover, esimp, apply arrow_pathover, exact r, apply is_hprop.elimo} end end equiv
35ee81e9301f43f00abcd2a773e0aeb9b2d8cdc6
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/integral_closure.lean
3e9b27aeb6931ca19d2efcf21dfe04d49abc1cc8
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
16,939
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.adjoin /-! # Integral closure of a subring. -/ universes u v open_locale classical open polynomial submodule section variables (R : Type u) {A : Type v} variables [comm_ring R] [comm_ring A] variables [algebra R A] /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. -/ def is_integral (x : A) : Prop := ∃ p : polynomial R, monic p ∧ aeval R A x p = 0 variables {R} theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := ⟨X - C x, monic_X_sub_C _, by rw [alg_hom.map_sub, aeval_def, aeval_def, eval₂_X, eval₂_C, sub_self]⟩ theorem is_integral_of_subring {x : A} (T : set R) [is_subring T] (hx : is_integral T (algebra.comap.to_comap T R A x)) : is_integral R (x : A) := let ⟨p, hpm, hpx⟩ := hx in ⟨⟨p.support, λ n, (p.to_fun n).1, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, have _ := congr_arg subtype.val H, this, λ H, subtype.eq H⟩)⟩, have _ := congr_arg subtype.val hpm, this, hpx⟩ theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) (algebra.comap.to_comap (ring.closure s) R A r) := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, exact ⟨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, hpr⟩ }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A) : submodule R A).fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range at hr, rcases hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, finsupp.sum], refine sum_mem _ (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s : submodule R A).fg := set.finite.induction_on hfs (λ _, ⟨{1}, le_antisymm (span_le.2 $ finset.singleton_subset_set_iff.2 $ is_submonoid.one_mem) begin rw submodule.le_def, change ring.closure _ ⊆ _, simp only [set.union_empty, finset.coe_singleton, span_singleton_eq_range, algebra.smul_def, mul_one], exact ring.closure_subset (set.subset.refl _) end⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his theorem is_integral_of_noetherian' (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval R A x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_noetherian (S : subalgebra R A) (H : is_noetherian R (S : submodule R A)) (x : A) (hx : x ∈ S) : is_integral R x := begin letI : algebra R S := S.algebra, letI : comm_ring S := S.comm_ring R A, suffices : is_integral R (⟨x, hx⟩ : S), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg subtype.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, finsupp.sum], rw ← p.support.sum_hom subtype.val, { refine finset.sum_congr rfl (λ n hn, _), change _ = _ * _, rw is_semiring_hom.map_pow coe, refl, split; intros; refl }, refine { map_add := _, map_zero := _ }; intros; refl }, refine is_integral_of_noetherian' H ⟨x, hx⟩ end theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : (S : submodule R A).fg) (x : A) (hx : x ∈ S) : is_integral R x := begin cases HS with y hy, obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ (span R ↑y : submodule R A), { intros jk, let j : ↥(↑y : set A) := ⟨jk.1.1, (finset.mem_product.1 jk.2).1⟩, let k : ↥(↑y : set A) := ⟨jk.1.2, (finset.mem_product.1 jk.2).2⟩, have hj : j.1 ∈ (span R ↑y : submodule R A) := subset_span j.2, have hk : k.1 ∈ (span R ↑y : submodule R A) := subset_span k.2, revert hj hk, rw hy, exact @is_submonoid.mul_mem A _ S _ j.1 k.1 }, rw ← set.image_id ↑y at this, simp only [finsupp.mem_span_iff_total] at this, choose ly hly1 hly2, let S₀' : finset R := lx.frange ∪ finset.bind finset.univ (finsupp.frange ∘ ly), let S₀ : set R := ring.closure ↑S₀', refine is_integral_of_subring (ring.closure ↑S₀') _, letI : algebra S₀ (algebra.comap S₀ R A) := algebra.comap.algebra _ _ _, letI hmod : module S₀ (algebra.comap S₀ R A) := by apply_instance, have : (span S₀ (insert 1 (↑y:set A) : set (algebra.comap S₀ R A)) : submodule S₀ (algebra.comap S₀ R A)) = (algebra.adjoin S₀ ((↑y : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)), { apply le_antisymm, { rw [span_le, set.insert_subset, mem_coe], split, change _ ∈ ring.closure _, exact is_submonoid.one_mem, exact algebra.subset_adjoin }, rw [algebra.adjoin_eq_span, span_le], intros r hr, refine monoid.in_closure.rec_on hr _ _ _, { intros r hr, exact subset_span (set.mem_insert_of_mem _ hr) }, { exact subset_span (set.mem_insert _ _) }, intros r1 r2 hr1 hr2 ih1 ih2, rw ← set.image_id (insert _ ↑y) at ih1 ih2, simp only [mem_coe, finsupp.mem_span_iff_total] at ih1 ih2, have ih1' := ih1, have ih2' := ih2, rcases ih1' with ⟨l1, hl1, rfl⟩, rcases ih2' with ⟨l2, hl2, rfl⟩, simp only [finsupp.total_apply, finsupp.sum_mul, finsupp.mul_sum, mem_coe], rw [finsupp.sum], refine sum_mem _ _, intros r2 hr2, rw [finsupp.sum], refine sum_mem _ _, intros r1 hr1, rw [algebra.mul_smul_comm, algebra.smul_mul_assoc], letI : module ↥S₀ A := hmod, refine smul_mem _ _ (smul_mem _ _ _), rcases hl1 hr1 with rfl | hr1, { change 1 * r2 ∈ _, rw one_mul r2, exact subset_span (hl2 hr2) }, rcases hl2 hr2 with rfl | hr2, { change r1 * 1 ∈ _, rw mul_one, exact subset_span (set.mem_insert_of_mem _ hr1) }, let jk : ↥(↑(finset.product y y) : set (A × A)) := ⟨(r1, r2), finset.mem_product.2 ⟨hr1, hr2⟩⟩, specialize hly2 jk, change _ = r1 * r2 at hly2, rw [id, id, ← hly2, finsupp.total_apply], rw [finsupp.sum], refine sum_mem _ _, intros z hz, have : ly jk z ∈ S₀, { apply ring.subset_closure, apply finset.mem_union_right, apply finset.mem_bind.2, exact ⟨jk, finset.mem_univ _, by convert finset.mem_image_of_mem _ hz⟩ }, change @has_scalar.smul S₀ (algebra.comap S₀ R A) hmod.to_has_scalar ⟨ly jk z, this⟩ z ∈ _, exact smul_mem _ _ (subset_span (set.mem_insert_of_mem _ (hly1 _ hz))) }, haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _), apply is_integral_of_noetherian (algebra.adjoin S₀ ((↑y : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw finset.coe_insert; convert this⟩), show x ∈ ((algebra.adjoin S₀ ((↑y : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)) : submodule S₀ (algebra.comap S₀ R A)), rw [← hlx2, finsupp.total_apply, finsupp.sum], refine sum_mem _ _, intros r hr, rw ← this, have : lx r ∈ ring.closure ↑S₀' := ring.subset_closure (finset.mem_union_left _ (by convert finset.mem_image_of_mem _ hr)), change @has_scalar.smul S₀ (algebra.comap S₀ R A) hmod.to_has_scalar ⟨lx r, this⟩ r ∈ _, rw finsupp.mem_supported at hlx1, exact smul_mem _ _ (subset_span (set.mem_insert_of_mem _ (hlx1 hr))), end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure ({x, y} : set A)) : is_integral R z := begin have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (ring.closure_mono (set.subset_union_right _ _) hz) end theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).map_zero ▸ is_integral_algebra_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).map_one ▸ is_integral_algebra_map theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem (ring.subset_closure (or.inl rfl))) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := is_integral_add hx (is_integral_neg hy) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := is_integral_of_mem_closure hx hy (is_submonoid.mul_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) variables (R A) def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, subring := { zero_mem := is_integral_zero, one_mem := is_integral_one, add_mem := λ _ _, is_integral_add, neg_mem := λ _, is_integral_neg, mul_mem := λ _ _, is_integral_mul }, range_le' := λ y ⟨x, hx⟩, hx ▸ is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, (M : submodule R A).fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ theorem integral_closure_idem : integral_closure (integral_closure R A : set A) A = ⊥ := begin rw eq_bot_iff, intros r hr, rcases is_integral_iff_is_integral_closure_finite.1 hr with ⟨s, hfs, hr⟩, apply algebra.mem_bot.2, refine ⟨⟨_, _⟩, rfl⟩, refine (mem_integral_closure_iff_mem_fg _ _).2 ⟨algebra.adjoin _ (subtype.val '' s ∪ {r}), algebra.fg_trans (fg_adjoin_of_finite (set.finite_image _ hfs) (λ y ⟨x, hx, hxy⟩, hxy ▸ x.2)) _, algebra.subset_adjoin (or.inr rfl)⟩, refine fg_adjoin_singleton_of_integral _ _, rcases hr with ⟨p, hmp, hpx⟩, refine ⟨to_subring (of_subring _ (of_subring _ p)) _ _, _, hpx⟩, { intros x hx, rcases finsupp.mem_frange.1 hx with ⟨h1, n, rfl⟩, change (coeff p n).1.1 ∈ ring.closure _, rcases ring.exists_list_of_mem_closure (coeff p n).2 with ⟨L, HL1, HL2⟩, rw ← HL2, clear HL2 hfs h1 hx n hmp hpx hr r p, induction L with hd tl ih, { exact is_add_submonoid.zero_mem }, rw list.forall_mem_cons at HL1, rw [list.map_cons, list.sum_cons], refine is_add_submonoid.add_mem _ (ih HL1.2), cases HL1 with HL HL', clear HL' ih tl, induction hd with hd tl ih, { exact is_submonoid.one_mem }, rw list.forall_mem_cons at HL, rw list.prod_cons, refine is_submonoid.mul_mem _ (ih HL.2), rcases HL.1 with hs | rfl, { exact algebra.subset_adjoin (set.mem_image_of_mem _ hs) }, exact is_add_subgroup.neg_mem (is_submonoid.one_mem) }, replace hmp := congr_arg subtype.val hmp, replace hmp := congr_arg subtype.val hmp, exact subtype.eq hmp end end section algebra open algebra variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R A] [algebra A B] lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval A B x p = 0) (S : set (comap R A B)) (hS : S = (↑((finset.range (p.nat_degree + 1)).image (λ i, to_comap R A B (p.coeff i))) : set (comap R A B))) : is_integral (adjoin R S) (comap.to_comap R A B x) := begin have coeffs_mem : ∀ i, coeff (map ↑(to_comap R A B) p) i ∈ adjoin R S, { intro i, by_cases hi : i ∈ finset.range (p.nat_degree + 1), { apply algebra.subset_adjoin, subst S, rw [finset.mem_coe, finset.mem_image, coeff_map], exact ⟨i, hi, rfl⟩ }, { rw [finset.mem_range, not_lt] at hi, rw [coeff_map, coeff_eq_zero_of_nat_degree_lt hi, ring_hom.map_zero], exact submodule.zero_mem (adjoin R S : submodule R (comap R A B)) } }, obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) (comap R A B)) = (p.map $ to_comap R A B), { rw [← set.mem_range], dsimp only, apply (polynomial.mem_map_range _).2, { intros i, specialize coeffs_mem i, rw ← subalgebra.mem_coe at coeffs_mem, convert coeffs_mem, exact subtype.val_range } }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) (comap R A B))).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval (comap.to_comap R A B x)) hq, convert hq using 1; symmetry; apply eval_map }, end /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : ∀ x : A, is_integral R x) (x : B) (hx : is_integral A x) : is_integral R (comap.to_comap R A B x) := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set (comap R A B) := (↑((finset.range (p.nat_degree + 1)).image (λ i, to_comap R A B (p.coeff i))) : set (comap R A B)), refine is_integral_of_mem_of_fg (adjoin R (S ∪ {comap.to_comap R A B x})) _ _ _, swap, { apply subset_adjoin, simp }, apply fg_trans, { apply fg_adjoin_of_finite, { apply finset.finite_to_set }, intros x hx, rw [finset.mem_coe, finset.mem_image] at hx, rcases hx with ⟨i, hi, rfl⟩, rcases A_int (p.coeff i) with ⟨q, hq, hqx⟩, use [q, hq], replace hqx := congr_arg (to_comap R A B : A → (comap R A B)) hqx, rw alg_hom.map_zero at hqx, convert hqx using 1, symmetry, exact polynomial.hom_eval₂ _ _ _ _ }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp _ rfl } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (A_int : ∀ x : A, is_integral R x)(B_int : ∀ x:B, is_integral A x) : ∀ x:(comap R A B), is_integral R x := λ x, is_integral_trans A_int x (B_int x) end algebra
475411e6a4192e02cc0f6392460ff1e2dfe2a7aa
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/finset/sort.lean
4874953a1973a6ecadde79b71e9a88f67220b303
[ "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
9,067
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.lattice import data.multiset.sort /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section sort_linear_order variables [decidable_linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min' (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le H _ this } end lemma sorted_last_eq_max' (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' H _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.le_pred_of_lt i_lt) }, end /-- Given a finset `s` of cardinal `k` in a linear order `α`, the map `mono_of_fin s h` is the increasing bijection between `fin k` and `s` as an `α`-valued map. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ def mono_of_fin (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : α := have A : (i : ℕ) < (s.sort (≤)).length, by simpa [h] using i.2, (s.sort (≤)).nth_le i A lemma mono_of_fin_strict_mono (s : finset α) {k : ℕ} (h : s.card = k) : strict_mono (s.mono_of_fin h) := begin assume i j hij, exact list.pairwise_iff_nth_le.1 s.sort_sorted_lt _ _ _ hij end lemma mono_of_fin_bij_on (s : finset α) {k : ℕ} (h : s.card = k) : set.bij_on (s.mono_of_fin h) set.univ ↑s := begin have A : ∀ j, j ∈ s ↔ j ∈ (s.sort (≤)) := λ j, by simp, apply set.bij_on.mk, { assume i hi, simp only [mono_of_fin, set.mem_preimage, mem_coe, list.nth_le, A], exact list.nth_le_mem _ _ _ }, { exact ((mono_of_fin_strict_mono s h).injective).inj_on _ }, { assume x hx, simp only [mem_coe, A] at hx, obtain ⟨i, il, hi⟩ : ∃ (i : ℕ) (h : i < (s.sort (≤)).length), (s.sort (≤)).nth_le i h = x := list.nth_le_of_mem hx, simp [h] at il, exact ⟨⟨i, il⟩, set.mem_univ _, hi⟩ } end lemma mono_of_fin_injective (s : finset α) {k : ℕ} (h : s.card = k) : function.injective (s.mono_of_fin h) := set.injective_iff_inj_on_univ.mpr (s.mono_of_fin_bij_on h).inj_on /-- The bijection `mono_of_fin s h` sends `0` to the minimum of `s`. -/ lemma mono_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hs : s.nonempty) (hz : 0 < k) : mono_of_fin s h ⟨0, hz⟩ = s.min' hs := begin apply le_antisymm, { have : min' s hs ∈ s := min'_mem s hs, rcases (mono_of_fin_bij_on s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact zero_le a.val }, { have : mono_of_fin s h ⟨0, hz⟩ ∈ s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), exact min'_le s hs _ this } end /-- The bijection `mono_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma mono_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hs : s.nonempty) (hz : 0 < k) : mono_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' hs := begin have h'' : k - 1 < k := buffer.lt_aux_2 hz, apply le_antisymm, { have : mono_of_fin s h ⟨k-1, h''⟩ ∈ s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), exact le_max' s hs _ this }, { have : max' s hs ∈ s := max'_mem s hs, rcases (mono_of_fin_bij_on s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact le_pred_of_lt a.2}, end /-- Any increasing bijection between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. For a statement assuming only that `f` maps `univ` to `s`, see `mono_of_fin_unique'`.-/ lemma mono_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hbij : set.bij_on f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin ext ⟨i, hi⟩, induction i using nat.strong_induction_on with i IH, rcases lt_trichotomy (f ⟨i, hi⟩) (mono_of_fin s h ⟨i, hi⟩) with H|H|H, { have A : f ⟨i, hi⟩ ∈ ↑s := hbij.maps_to (set.mem_univ _), rcases (mono_of_fin_bij_on s h).surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := (mono_of_fin_strict_mono s h).lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j.1 ji (lt_trans ji hi), rw fin.ext_iff }, rw ← this at hj, exact (ne_of_lt (hmono ji) hj).elim }, { exact H }, { have A : mono_of_fin s h ⟨i, hi⟩ ∈ ↑s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), rcases hbij.surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := hmono.lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j.1 ji (lt_trans ji hi), rw fin.ext_iff }, rw this at hj, exact (ne_of_lt (mono_of_fin_strict_mono s h ji) hj).elim } end /-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. -/ lemma mono_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin have finj : set.inj_on f set.univ := hmono.injective.inj_on _, apply mono_of_fin_unique h (set.bij_on.mk fmap finj (λ y hy, _)) hmono, simp only [set.image_univ, set.mem_range], rcases surj_on_of_inj_on_of_card_le (λ i (hi : i ∈ finset.fin_range k), f i) (λ i hi, fmap (set.mem_univ i)) (λ i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij) (by simp [h]) y hy with ⟨x, _, hx⟩, exact ⟨x, hx.symm⟩ end /-- Two parametrizations `mono_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `i.val = j.val`. -/ @[simp] lemma mono_of_fin_eq_mono_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.mono_of_fin h i = s.mono_of_fin h' j ↔ i.val = j.val := begin have A : k = l, by rw [← h', ← h], have : s.mono_of_fin h = (s.mono_of_fin h') ∘ (λ j : (fin k), ⟨j.1, A ▸ j.2⟩) := rfl, rw [this, function.comp_app, (s.mono_of_fin_injective h').eq_iff, fin.ext_iff] end /-- Given a finset `s` of cardinal `k` in a linear order `α`, the equiv `mono_equiv_of_fin s h` is the increasing bijection between `fin k` and `s` as an `s`-valued map. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃ {x // x ∈ s} := (s.mono_of_fin_bij_on h).equiv _ end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
abfac9c6ed3582fe40aeb1a293f810a1549a1dfd
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/trace_tst.lean
3e4fa17ec6d9b98933af0285aa2b15ec5cc4e4f6
[ "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
69
lean
open nat vm_eval trace "step1" (λ u, trace "hello" (λ u, succ 3))
7b5bd9915a6e2f775f6efe9899b6c15ecbd10dc4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/def2.lean
0037c4ec98f3b5a77a050c7d6a9028a0e3a8c2ee
[ "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
95
lean
definition plus (a b : nat) : nat := nat.rec_on a b (λ a' ih, nat.succ ih) vm_eval plus 3 5
303e0c97d6f7ce159ceebc1d3a649e666e0a0628
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/ordmap/ordset.lean
98ae171d6183b155703ab1888d7516b07d3bf58a
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,878
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.ordmap.ordnode import algebra.order.ring import data.nat.dist import tactic.linarith /-! # Verification of the `ordnode α` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset α`, which is a wrapper around `ordnode α` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset α`: A well formed set of values of type `α` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode α` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode α` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and `¬ (b ≤ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {α : Type*} namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≤ s) : ¬ s ≤ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : false := not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 h₁) h₂) $ by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 ≤ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size : ordnode α → ℕ | nil := 0 | (node _ l _ r) := real_size l + real_size r + 1 /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized : ordnode α → Prop | nil := true | (node s l _ r) := s = size l + size r + 1 ∧ sized l ∧ sized r theorem sized.node' {l x r} (hl : @sized α l) (hr : sized r) : sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem sized.eq_node' {s l x r} (h : @sized α (node s l x r)) : node s l x r = node' l x r := by rw h.1; refl theorem sized.size_eq {s l x r} (H : sized (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.1 @[elab_as_eliminator] theorem sized.induction {t} (hl : @sized α t) {C : ordnode α → Prop} (H0 : C nil) (H1 : ∀ l x r, C l → C r → C (node' l x r)) : C t := begin induction t, {exact H0}, rw hl.eq_node', exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) end theorem size_eq_real_size : ∀ {t : ordnode α}, sized t → size t = real_size t | nil _ := rfl | (node s l x r) ⟨h₁, h₂, h₃⟩ := by rw [size, h₁, size_eq_real_size h₂, size_eq_real_size h₃]; refl @[simp] theorem sized.size_eq_zero {t : ordnode α} (ht : sized t) : size t = 0 ↔ t = nil := by cases t; [simp, simp [ht.1]] theorem sized.pos {s l x r} (h : sized (@node α s l x r)) : 0 < s := by rw h.1; apply nat.le_add_left /-! `dual` -/ theorem dual_dual : ∀ (t : ordnode α), dual (dual t) = t | nil := rfl | (node s l x r) := by rw [dual, dual, dual_dual, dual_dual] @[simp] theorem size_dual (t : ordnode α) : size (dual t) = size t := by cases t; refl /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l r : ℕ) : Prop := l + r ≤ 1 ∨ (l ≤ delta * r ∧ r ≤ delta * l) instance balanced_sz.dec : decidable_rel balanced_sz := λ l r, or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced : ordnode α → Prop | nil := true | (node _ l _ r) := balanced_sz (size l) (size r) ∧ balanced l ∧ balanced r instance balanced.dec : decidable_pred (@balanced α) | t := by induction t; unfold balanced; resetI; apply_instance theorem balanced_sz.symm {l r : ℕ} : balanced_sz l r → balanced_sz r l := or.imp (by rw add_comm; exact id) and.symm theorem balanced_sz_zero {l : ℕ} : balanced_sz l 0 ↔ l ≤ 1 := by simp [balanced_sz] { contextual := tt } theorem balanced_sz_up {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l) (H : balanced_sz l r₁) : balanced_sz l r₂ := begin refine or_iff_not_imp_left.2 (λ h, _), refine ⟨_, h₂.resolve_left h⟩, cases H, { cases r₂, { cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) }, { exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } }, { exact le_trans H.1 (nat.mul_le_mul_left _ h₁) } end theorem balanced_sz_down {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁) (H : balanced_sz l r₂) : balanced_sz l r₁ := have l + r₂ ≤ 1 → balanced_sz l r₁, from λ H, or.inl (le_trans (nat.add_le_add_left h₁ _) H), or.cases_on H this (λ H, or.cases_on h₂ this (λ h₂, or.inr ⟨h₂, le_trans h₁ H.2⟩)) theorem balanced.dual : ∀ {t : ordnode α}, balanced t → balanced (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨b, bl, br⟩ := ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_l l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_r l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l : ordnode α → α → ordnode α → ordnode α | l x (node _ m y r) := if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r | l x nil := node' l x nil -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r : ordnode α → α → ordnode α → ordnode α | (node _ l x m) y r := if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r | nil y r := node' nil y r -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size l > delta * size r then rotate_r l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else if size l > delta * size r then rotate_r l x r else node' l x r theorem dual_node' (l : ordnode α) (x : α) (r : ordnode α) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node4_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node'] theorem dual_node4_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node'] theorem dual_rotate_l (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := by cases r; simp [rotate_l, rotate_r, dual_node']; split_ifs; simp [dual_node3_l, dual_node4_l] theorem dual_rotate_r (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := by rw [← dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual] theorem dual_balance' (l : ordnode α) (x : α) (r : ordnode α) : dual (balance' l x r) = balance' (dual r) x (dual l) := begin simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r], cases delta_lt_false h_1 h_2 end theorem dual_balance_l (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := begin unfold balance_l balance_r, cases r with rs rl rx rr, { cases l with ls ll lx lr, {refl}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp only [dual]; try {refl}, split_ifs; repeat {simp [h, add_comm]} }, { cases l with ls ll lx lr, {refl}, dsimp only [dual], split_ifs, swap, {simp [add_comm]}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl}, dsimp only [dual], split_ifs; simp [h, add_comm] }, end theorem dual_balance_r (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := by rw [← dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual] theorem sized.node3_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := (hl.node' hm).node' hr theorem sized.node3_r {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := hl.node' (hm.node' hr) theorem sized.node4_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := by cases m; [exact (hl.node' hm).node' hr, exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3_l_size {l x m y r} : size (@node3_l α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_l, node', size]; rw add_right_comm _ 1 theorem node3_r_size {l x m y r} : size (@node3_r α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_r, node', size]; rw [← add_assoc, ← add_assoc] theorem node4_l_size {l x m y r} (hm : sized m) : size (@node4_l α l x m y r) = size l + size m + size r + 2 := by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]]; rw [← add_assoc, ← bit0]; simp [add_comm, add_left_comm] theorem sized.dual : ∀ {t : ordnode α} (h : sized t), sized (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨rfl, sl, sr⟩ := ⟨by simp [size_dual, add_comm], sized.dual sr, sized.dual sl⟩ theorem sized.dual_iff {t : ordnode α} : sized (dual t) ↔ sized t := ⟨λ h, by rw ← dual_dual t; exact h.dual, sized.dual⟩ theorem sized.rotate_l {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_l l x r) := begin cases r, {exact hl.node' hr}, rw rotate_l, split_ifs, { exact hl.node3_l hr.2.1 hr.2.2 }, { exact hl.node4_l hr.2.1 hr.2.2 } end theorem sized.rotate_r {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_r l x r) := sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual theorem sized.rotate_l_size {l x r} (hm : sized r) : size (@rotate_l α l x r) = size l + size r + 1 := begin cases r; simp [rotate_l], simp [size, hm.1, add_comm, add_left_comm], rw [← add_assoc, ← bit0], simp, split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm] end theorem sized.rotate_r_size {l x r} (hl : sized l) : size (@rotate_r α l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotate_r, hl.dual.rotate_l_size, size_dual, size_dual, add_comm (size l)] theorem sized.balance' {l x r} (hl : @sized α l) (hr : sized r) : sized (balance' l x r) := begin unfold balance', split_ifs, { exact hl.node' hr }, { exact hl.rotate_l hr }, { exact hl.rotate_r hr }, { exact hl.node' hr } end theorem size_balance' {l x r} (hl : @sized α l) (hr : sized r) : size (@balance' α l x r) = size l + size r + 1 := begin unfold balance', split_ifs, { refl }, { exact hr.rotate_l_size }, { exact hl.rotate_r_size }, { refl } end /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, all P t → all Q t | nil h := ⟨⟩ | (node _ l x r) ⟨h₁, h₂, h₃⟩ := ⟨h₁.imp, H _ h₂, h₃.imp⟩ theorem any.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, any P t → any Q t | nil := id | (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp theorem all_singleton {P : α → Prop} {x : α} : all P (singleton x) ↔ P x := ⟨λ h, h.2.1, λ h, ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : α → Prop} {x : α} : any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, λ h, or.inr (or.inl h)⟩ theorem all_dual {P : α → Prop} : ∀ {t : ordnode α}, all P (dual t) ↔ all P t | nil := iff.rfl | (node s l x r) := ⟨λ ⟨hr, hx, hl⟩, ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, λ ⟨hl, hx, hr⟩, ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : α → Prop} : ∀ {t}, all P t ↔ ∀ x, emem x t → P x | nil := (iff_true_intro $ by rintro _ ⟨⟩).symm | (node _ l x r) := by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib] theorem any_iff_exists {P : α → Prop} : ∀ {t}, any P t ↔ ∃ x, emem x t ∧ P x | nil := ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | (node _ l x r) := by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib] theorem emem_iff_all {x : α} {t} : emem x t ↔ ∀ P, all P t → P x := ⟨λ h P al, all_iff_forall.1 al _ h, λ H, H _ $ all_iff_forall.2 $ λ _, id⟩ theorem all_node' {P l x r} : @all α P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {P l x m y r} : @all α P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by simp [node3_l, all_node', and_assoc] theorem all_node3_r {P l x m y r} : @all α P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {P l x m y r} : @all α P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc] theorem all_node4_r {P l x m y r} : @all α P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc] theorem all_rotate_l {P l x r} : @all α P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := by cases r; simp [rotate_l, all_node']; split_ifs; simp [all_node3_l, all_node4_l, all] theorem all_rotate_r {P l x r} : @all α P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := by rw [← all_dual, dual_rotate_r, all_rotate_l]; simp [all_dual, and_comm, and.left_comm] theorem all_balance' {P l x r} : @all α P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r] /-! ### `to_list` -/ theorem foldr_cons_eq_to_list : ∀ (t : ordnode α) (r : list α), t.foldr list.cons r = to_list t ++ r | nil r := rfl | (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list, ← list.cons_append, ← list.append_assoc, ← foldr_cons_eq_to_list]; refl @[simp] theorem to_list_nil : to_list (@nil α) = [] := rfl @[simp] theorem to_list_node (s l x r) : to_list (@node α s l x r) = to_list l ++ x :: to_list r := by rw [to_list, foldr, foldr_cons_eq_to_list]; refl theorem emem_iff_mem_to_list {x : α} {t} : emem x t ↔ x ∈ to_list t := by unfold emem; induction t; simp [any, *, or_assoc] theorem length_to_list' : ∀ t : ordnode α, (to_list t).length = t.real_size | nil := rfl | (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons, length_to_list', length_to_list']; refl theorem length_to_list {t : ordnode α} (h : sized t) : (to_list t).length = t.size := by rw [length_to_list', size_eq_real_size h] theorem equiv_iff {t₁ t₂ : ordnode α} (h₁ : sized t₁) (h₂ : sized t₂) : equiv t₁ t₂ ↔ to_list t₁ = to_list t₂ := and_iff_right_of_imp $ λ h, by rw [← length_to_list h₁, h, length_to_list h₂] /-! ### `mem` -/ theorem pos_size_of_mem [has_le α] [@decidable_rel α (≤)] {x : α} {t : ordnode α} (h : sized t) (h_mem : x ∈ t) : 0 < size t := by { cases t, { contradiction }, { simp [h.1] } } /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual : ∀ t (x : α), find_min' (dual t) x = find_max' x t | nil x := rfl | (node _ l x r) _ := find_min'_dual r x theorem find_max'_dual (t) (x : α) : find_max' x (dual t) = find_min' t x := by rw [← find_min'_dual, dual_dual] theorem find_min_dual : ∀ t : ordnode α, find_min (dual t) = find_max t | nil := rfl | (node _ l x r) := congr_arg some $ find_min'_dual _ _ theorem find_max_dual (t : ordnode α) : find_max (dual t) = find_min t := by rw [← find_min_dual, dual_dual] theorem dual_erase_min : ∀ t : ordnode α, dual (erase_min t) = erase_max (dual t) | nil := rfl | (node _ nil x r) := rfl | (node _ l@(node _ _ _ _) x r) := by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max] theorem dual_erase_max (t : ordnode α) : dual (erase_max t) = erase_min (dual t) := by rw [← dual_dual (erase_min _), dual_erase_min, dual_dual] theorem split_min_eq : ∀ s l (x : α) r, split_min' l x r = (find_min' l x, erase_min (node s l x r)) | _ nil x r := rfl | _ (node ls ll lx lr) x r := by rw [split_min', split_min_eq, split_min', find_min', erase_min] theorem split_max_eq : ∀ s l (x : α) r, split_max' l x r = (erase_max (node s l x r), find_max' x r) | _ l x nil := rfl | _ l x (node ls ll lx lr) := by rw [split_max', split_max_eq, split_max', find_max', erase_max] @[elab_as_eliminator] theorem find_min'_all {P : α → Prop} : ∀ t (x : α), all P t → P x → P (find_min' t x) | nil x h hx := hx | (node _ ll lx lr) x ⟨h₁, h₂, h₃⟩ hx := find_min'_all _ _ h₁ h₂ @[elab_as_eliminator] theorem find_max'_all {P : α → Prop} : ∀ (x : α) t, P x → all P t → P (find_max' x t) | x nil hx h := hx | x (node _ ll lx lr) hx ⟨h₁, h₂, h₃⟩ := find_max'_all _ _ h₂ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : ordnode α) : merge t nil = t := by cases t; refl @[simp] theorem merge_nil_right (t : ordnode α) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node α ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balance_l (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balance_r ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] (x : α) : ∀ t : ordnode α, dual (ordnode.insert x t) = @ordnode.insert (order_dual α) _ _ x (dual t) | nil := rfl | (node _ l y r) := begin rw [ordnode.insert, dual, ordnode.insert, order_dual.cmp_le_flip, ← cmp_le_swap x y], cases cmp_le x y; simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert] end /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : @balance α l x r = balance' l x r := begin cases l with ls ll lx lr, { cases r with rs rl rx rr, { refl }, { rw sr.eq_node' at hr ⊢, cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr; dsimp [balance, balance'], { refl }, { have : size rrl = 0 ∧ size rrr = 0, { have := balanced_sz_zero.1 hr.1.symm, rwa [size, sr.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.2.2.1.size_eq_zero.1 this.1, cases sr.2.2.2.2.size_eq_zero.1 this.2, have : rrs = 1 := sr.2.2.1, subst rrs, rw [if_neg, if_pos, rotate_l, if_pos], {refl}, all_goals {exact dec_trivial} }, { have : size rll = 0 ∧ size rlr = 0, { have := balanced_sz_zero.1 hr.1, rwa [size, sr.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.2.1.size_eq_zero.1 this.1, cases sr.2.1.2.2.size_eq_zero.1 this.2, have : rls = 1 := sr.2.1.1, subst rls, rw [if_neg, if_pos, rotate_l, if_neg], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [zero_add, if_neg, if_pos, rotate_l], { split_ifs, { simp [node3_l, node', add_comm, add_left_comm] }, { simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) } } } }, { cases r with rs rl rx rr, { rw sl.eq_node' at hl ⊢, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp [balance, balance'], { refl }, { have : size lrl = 0 ∧ size lrr = 0, { have := balanced_sz_zero.1 hl.1.symm, rwa [size, sl.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.2.2.1.size_eq_zero.1 this.1, cases sl.2.2.2.2.size_eq_zero.1 this.2, have : lrs = 1 := sl.2.2.1, subst lrs, rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl}, all_goals {exact dec_trivial} }, { have : size lll = 0 ∧ size llr = 0, { have := balanced_sz_zero.1 hl.1, rwa [size, sl.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.1.2.1.size_eq_zero.1 this.1, cases sl.2.1.2.2.size_eq_zero.1 this.2, have : lls = 1 := sl.2.1.1, subst lls, rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [if_neg, if_neg, if_pos, rotate_r], { split_ifs, { simp [node3_r, node', add_comm, add_left_comm] }, { simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) } } }, { simp [balance, balance'], symmetry, rw [if_neg], { split_ifs, { have rd : delta ≤ size rl + size rr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h, rwa [sr.1, nat.lt_succ_iff] at this }, cases rl with rls rll rlx rlr, { rw [size, zero_add] at rd, exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial }, cases rr with rrs rrl rrx rrr, { exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial }, dsimp [rotate_l], split_ifs, { simp [node3_l, node', sr.1, add_comm, add_left_comm] }, { simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } }, { have ld : delta ≤ size ll + size lr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1, rwa [sl.1, nat.lt_succ_iff] at this }, cases ll with lls lll llx llr, { rw [size, zero_add] at ld, exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial }, cases lr with lrs lrl lrx lrr, { exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial }, dsimp [rotate_r], split_ifs, { simp [node3_r, node', sl.1, add_comm, add_left_comm] }, { simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } }, { simp [node'] } }, { exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 ≤ ls + rs) } } } end theorem balance_l_eq_balance {l x r} (sl : sized l) (sr : sized r) (H1 : size l = 0 → size r ≤ 1) (H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) : @balance_l α l x r = balance l x r := begin cases r with rs rl rx rr, { refl }, { cases l with ls ll lx lr, { have : size rl = 0 ∧ size rr = 0, { have := H1 rfl, rwa [size, sr.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.size_eq_zero.1 this.1, cases sr.2.2.size_eq_zero.1 this.2, rw sr.eq_node', refl }, { replace H2 : ¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos), simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } } end /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n m : ℕ) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : raised n m ↔ n ≤ m ∧ m ≤ n + 1 := begin split, rintro (rfl | rfl), { exact ⟨le_refl _, nat.le_succ _⟩ }, { exact ⟨nat.le_succ _, le_refl _⟩ }, { rintro ⟨h₁, h₂⟩, rcases eq_or_lt_of_le h₁ with rfl | h₁, { exact or.inl rfl }, { exact or.inr (le_antisymm h₂ h₁) } } end theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m ≤ 1 := by cases raised_iff.1 H with H1 H2; rwa [nat.dist_eq_sub_of_le H1, nat.sub_le_left_iff_le_add] theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n ≤ 1 := by rw nat.dist_comm; exact H.dist_le theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) := begin rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem raised.right {l x₁ x₂ r₁ r₂} (H : raised (size r₁) (size r₂)) : raised (size (@node' α l x₁ r₁)) (size (@node' α l x₂ r₂)) := begin dsimp [node', size], generalize_hyp : size r₂ = m at H ⊢, rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem balance_l_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : @balance_l α l x r = balance' l x r := begin rw [← balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr], { intro l0, rw l0 at H, rcases H with ⟨_, ⟨⟨⟩⟩|⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩, { exact balanced_sz_zero.1 H.symm }, exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) }, { intros l1 r1, rcases H with ⟨l', e, H | ⟨H₁, H₂⟩⟩ | ⟨r', e, H | ⟨H₁, H₂⟩⟩, { exact le_trans (le_trans (nat.le_add_left _ _) H) (mul_pos dec_trivial l1 : (0:ℕ)<_) }, { exact le_trans H₂ (nat.mul_le_mul_left _ (raised_iff.1 e).1) }, { cases raised_iff.1 e, unfold delta, linarith }, { exact le_trans (raised_iff.1 e).1 H₂ } } end theorem balance_sz_dual {l r} (H : (∃ l', raised (@size α l) l' ∧ balanced_sz l' (@size α r)) ∨ ∃ r', raised r' (size r) ∧ balanced_sz (size l) r') : (∃ l', raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ ∃ r', raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := begin rw [size_dual, size_dual], exact H.symm.imp (Exists.imp $ λ _, and.imp_right balanced_sz.symm) (Exists.imp $ λ _, and.imp_right balanced_sz.symm) end theorem size_balance_l {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : size (@balance_l α l x r) = size l + size r + 1 := by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_l {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : all P (@balance_l α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_l_eq_balance' hl hr sl sr H, all_balance'] theorem balance_r_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : @balance_r α l x r = balance' l x r := by rw [← dual_dual (balance_r l x r), dual_balance_r, balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balance_r {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : size (@balance_r α l x r) = size l + size r + 1 := by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_r {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : all P (@balance_r α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_r_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [preorder α] /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/ def bounded : ordnode α → with_bot α → with_top α → Prop | nil (some a) (some b) := a < b | nil _ _ := true | (node _ l x r) o₁ o₂ := bounded l o₁ ↑x ∧ bounded r ↑x o₂ theorem bounded.dual : ∀ {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂), @bounded (order_dual α) _ (dual t) o₂ o₁ | nil o₁ o₂ h := by cases o₁; cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨or.dual, ol.dual⟩ theorem bounded.dual_iff {t : ordnode α} {o₁ o₂} : bounded t o₁ o₂ ↔ @bounded (order_dual α) _ (dual t) o₂ o₁ := ⟨bounded.dual, λ h, by have := bounded.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem bounded.weak_left : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t ⊥ o₂ | nil o₁ o₂ h := by cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol.weak_left, or⟩ theorem bounded.weak_right : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t o₁ ⊤ | nil o₁ o₂ h := by cases o₁; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol, or.weak_right⟩ theorem bounded.weak {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂) : bounded t ⊥ ⊤ := h.weak_left.weak_right theorem bounded.mono_left {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t ↑y o → bounded t ↑x o | nil none h := ⟨⟩ | nil (some z) h := lt_of_le_of_lt xy h | (node s l z r) o ⟨ol, or⟩ := ⟨ol.mono_left, or⟩ theorem bounded.mono_right {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t o ↑x → bounded t o ↑y | nil none h := ⟨⟩ | nil (some z) h := lt_of_lt_of_le h xy | (node s l z r) o ⟨ol, or⟩ := ⟨ol, or.mono_right⟩ theorem bounded.to_lt : ∀ {t : ordnode α} {x y : α}, bounded t x y → x < y | nil x y h := h | (node _ l y r) x z ⟨h₁, h₂⟩ := lt_trans h₁.to_lt h₂.to_lt theorem bounded.to_nil {t : ordnode α} : ∀ {o₁ o₂}, bounded t o₁ o₂ → bounded nil o₁ o₂ | none _ h := ⟨⟩ | (some _) none h := ⟨⟩ | (some x) (some y) h := h.to_lt theorem bounded.trans_left {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₂ o₁ o₂ | none o₂ h₁ h₂ := h₂.weak_left | (some y) o₂ h₁ h₂ := h₂.mono_left (le_of_lt h₁.to_lt) theorem bounded.trans_right {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₁ o₁ o₂ | o₁ none h₁ h₂ := h₁.weak_right | o₁ (some y) h₁ h₂ := h₁.mono_right (le_of_lt h₂.to_lt) theorem bounded.mem_lt : ∀ {t o} {x : α}, bounded t o ↑x → all (< x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_lt.imp (λ z h, lt_trans h h₂.to_lt), h₂.to_lt, h₂.mem_lt⟩ theorem bounded.mem_gt : ∀ {t o} {x : α}, bounded t ↑x o → all (> x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_gt, h₁.to_lt, h₂.mem_gt.imp (λ z, lt_trans h₁.to_lt)⟩ theorem bounded.of_lt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil o₁ ↑x → all (< x) t → bounded t o₁ ↑x | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁, h₂.of_lt al₂ al₃⟩ theorem bounded.of_gt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil ↑x o₂ → all (> x) t → bounded t ↑x o₂ | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁.of_gt al₂ al₁, h₂⟩ theorem bounded.to_sep {t₁ t₂ o₁ o₂} {x : α} (h₁ : bounded t₁ o₁ ↑x) (h₂ : bounded t₂ ↑x o₂) : t₁.all (λ y, t₂.all (λ z : α, y < z)) := h₁.mem_lt.imp $ λ y yx, h₂.mem_gt.imp $ λ z xz, lt_trans yx xz end /-! ### `valid` -/ section variable [preorder α] /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' (lo : with_bot α) (t : ordnode α) (hi : with_top α) : Prop := (ord : t.bounded lo hi) (sz : t.sized) (bal : t.balanced) /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid (t : ordnode α) : Prop := valid' ⊥ t ⊤ theorem valid'.mono_left {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' ↑y t o) : valid' ↑x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem valid'.mono_right {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' o t ↑x) : valid' o t ↑y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem valid'.trans_left {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (h : bounded t₁ o₁ ↑x) (H : valid' ↑x t₂ o₂) : valid' o₁ t₂ o₂ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem valid'.trans_right {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t₁ ↑x) (h : bounded t₂ ↑x o₂) : valid' o₁ t₁ o₂ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem valid'.of_lt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil o₁ ↑x) (h₂ : all (< x) t) : valid' o₁ t ↑x := ⟨H.1.of_lt h₁ h₂, H.2, H.3⟩ theorem valid'.of_gt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil ↑x o₂) (h₂ : all (> x) t) : valid' ↑x t o₂ := ⟨H.1.of_gt h₁ h₂, H.2, H.3⟩ theorem valid'.valid {t o₁ o₂} (h : @valid' α _ o₁ t o₂) : valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ o₂} (h : bounded nil o₁ o₂) : valid' o₁ (@nil α) o₂ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : valid (@nil α) := valid'_nil ⟨⟩ theorem valid'.node {s l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (@node α s l x r) o₂ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem valid'.dual : ∀ {t : ordnode α} {o₁ o₂} (h : valid' o₁ t o₂), @valid' (order_dual α) _ o₂ (dual t) o₁ | nil o₁ o₂ h := valid'_nil h.1.dual | (node s l x r) o₁ o₂ ⟨⟨ol, or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ := let ⟨ol', sl', bl'⟩ := valid'.dual ⟨ol, sl, bl⟩, ⟨or', sr', br'⟩ := valid'.dual ⟨or, sr, br⟩ in ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem valid'.dual_iff {t : ordnode α} {o₁ o₂} : valid' o₁ t o₂ ↔ @valid' (order_dual α) _ o₂ (dual t) o₁ := ⟨valid'.dual, λ h, by have := valid'.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem valid.dual {t : ordnode α} : valid t → @valid (order_dual α) _ (dual t) := valid'.dual theorem valid.dual_iff {t : ordnode α} : valid t ↔ @valid (order_dual α) _ (dual t) := valid'.dual_iff theorem valid'.left {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem valid'.right {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' ↑x r o₂ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ theorem valid.left {s l x r} (H : valid (@node α s l x r)) : valid l := H.left.valid theorem valid.right {s l x r} (H : valid (@node α s l x r)) : valid r := H.right.valid theorem valid.size_eq {s l x r} (H : valid (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.2.1 theorem valid'.node' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) : valid' o₁ (@node' α l x r) o₂ := hl.node hr H rfl theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : bounded nil o₁ ↑x) (h₂ : bounded nil ↑x o₂) : valid' o₁ (singleton x : ordnode α) o₂ := (valid'_nil h₁).node (valid'_nil h₂) (or.inl zero_le_one) rfl theorem valid_singleton {x : α} : valid (singleton x : ordnode α) := valid'_singleton ⟨⟩ ⟨⟩ theorem valid'.node3_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (@node3_l α l x m y r) o₂ := (hl.node' hm H1).node' hr H2 theorem valid'.node3_r {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (@node3_r α l x m y r) o₂ := hl.node' (hm.node' hr H2) H1 theorem valid'.node4_l_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by linarith theorem valid'.node4_l_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by linarith theorem valid'.node4_l_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) : d ≤ 3 * c := by linarith theorem valid'.node4_l_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by linarith theorem valid'.node4_l_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by linarith theorem valid'.node4_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (Hm : 0 < size m) (H : (size l = 0 ∧ size m = 1 ∧ size r ≤ 1) ∨ (0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ 3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r)) : valid' o₁ (@node4_l α l x m y r) o₂ := begin cases m with s ml z mr, {cases Hm}, suffices : balanced_sz (size l) (size ml) ∧ balanced_sz (size mr) (size r) ∧ balanced_sz (size l + size ml + 1) (size mr + size r + 1), from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2), rcases H with ⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩, { rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1, rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial }, { cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0 at mr₂, cases not_le_of_lt Hm mr₂ }, rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂, by_cases mm : size ml + size mr ≤ 1, { have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans mr₁ (nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0, rw [r1, add_assoc] at lr₁, have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1)) l0, rw [l1, r1], cases size ml; cases size mr, { exact dec_trivial }, { rw zero_add at mm, rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rw nat.succ_add at mm, rcases mm with _|⟨_,⟨⟩⟩ } }, rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩, cases nat.eq_zero_or_pos (size ml) with ml0 ml0, { rw [ml0, mul_zero, nat.le_zero_iff] at mm₂, rw [ml0, mm₂] at mm, cases mm dec_trivial }, cases nat.eq_zero_or_pos (size mr) with mr0 mr0, { rw [mr0, mul_zero, nat.le_zero_iff] at mm₁, rw [mr0, mm₁] at mm, cases mm dec_trivial }, have : 2 * size l ≤ size ml + size mr + 1, { have := nat.mul_le_mul_left _ lr₁, rw [mul_left_comm, mul_add] at this, have := le_trans this (add_le_add_left mr₁ _), rw [← nat.succ_mul] at this, exact (mul_le_mul_left dec_trivial).1 this }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { refine (mul_le_mul_left dec_trivial).1 (le_trans this _), rw [two_mul, nat.succ_le_iff], refine add_lt_add_of_lt_of_le _ mm₂, simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) }, { exact nat.le_of_lt_succ (valid'.node4_l_lemma₁ lr₂ mr₂ mm₁) }, { exact valid'.node4_l_lemma₂ mr₂ }, { exact valid'.node4_l_lemma₃ mr₁ mm₁ }, { exact valid'.node4_l_lemma₄ lr₁ mr₂ mm₁ }, { exact valid'.node4_l_lemma₅ lr₂ mr₁ mm₂ } } end theorem valid'.rotate_l_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by linarith theorem valid'.rotate_l_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith theorem valid'.rotate_l_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith theorem valid'.rotate_l_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by linarith theorem valid'.rotate_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@rotate_l α l x r) o₂ := begin cases r with rs rl rx rr, {cases H2}, rw [hr.2.size_eq, nat.lt_succ_iff] at H2, rw [hr.2.size_eq] at H3, replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 := H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ, have H3_0 : size l = 0 → size rl + size rr ≤ 2, { intro l0, rw l0 at H3, exact (or_iff_right_of_imp $ by exact λ h, (mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 }, have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := λ l0 : 1 ≤ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3, have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1, {intros, linarith}, have hlp : size l > 0 → ¬ size rl + size rr ≤ 1 := λ l0 hb, absurd (le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial, rw rotate_l, split_ifs, { have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1 (lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _), suffices : balanced_sz (size l) (size rl) ∧ balanced_sz (size l + size rl + 1) (size rr), { exact hl.node3_l hr.left hr.right this.1 this.2 }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, replace H3 := H3_0 l0, have := hr.3.1, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at this ⊢, rw le_antisymm (balanced_sz_zero.1 this.symm) rr0, exact dec_trivial }, have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0, rw add_comm at H3, rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0], exact dec_trivial }, replace H3 := H3p l0, rcases hr.3.1.resolve_left (hlp l0) with ⟨hb₁, hb₂⟩, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at hb₂, cases not_le_of_gt rr0 hb₂ }, cases eq_or_lt_of_le (show 1 ≤ size rr, from rr0) with rr1 rr1, { rw [← rr1] at h H2 ⊢, have : size rl = 1 := le_antisymm (nat.lt_succ_iff.1 h) rl0, rw this at H2, exact absurd (le_trans (nat.mul_le_mul_left _ l0) H2) dec_trivial }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { exact valid'.rotate_l_lemma₁ H2 hb₂ }, { exact nat.le_of_lt_succ (valid'.rotate_l_lemma₂ H3 h) }, { exact valid'.rotate_l_lemma₃ H2 h }, { exact le_trans hb₂ (nat.mul_le_mul_left _ $ le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } }, { cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw [rl0, not_lt, nat.le_zero_iff, nat.mul_eq_zero] at h, replace h := h.resolve_left dec_trivial, rw [rl0, h, nat.le_zero_iff, nat.mul_eq_zero] at H2, rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1, cases H1 dec_trivial }, refine hl.node4_l hr.left hr.right rl0 _, cases nat.eq_zero_or_pos (size l) with l0 l0, { replace H3 := H3_0 l0, cases nat.eq_zero_or_pos (size rr) with rr0 rr0, { have := hr.3.1, rw rr0 at this, exact or.inl ⟨l0, le_antisymm (balanced_sz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩ }, exact or.inl ⟨l0, le_antisymm (ablem rr0 $ by rwa add_comm) rl0, ablem rl0 H3⟩ }, exact or.inr ⟨l0, not_lt.1 h, H2, valid'.rotate_l_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ } end theorem valid'.rotate_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@rotate_r α l x r) o₂ := begin refine valid'.dual_iff.2 _, rw dual_rotate_r, refine hr.dual.rotate_l hl.dual _ _ _, { rwa [size_dual, size_dual, add_comm] }, { rwa [size_dual, size_dual] }, { rwa [size_dual, size_dual] } end theorem valid'.balance'_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) (H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance' α l x r) o₂ := begin rw balance', split_ifs, { exact hl.node' hr (or.inl h) }, { exact hl.rotate_l hr h h_1 H₁ }, { exact hl.rotate_r hr h h_2 H₂ }, { exact hl.node' hr (or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) } end theorem valid'.balance'_lemma {α l l' r r'} (H1 : balanced_sz l' r') (H2 : nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l') : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := begin suffices : @size α r ≤ 3 * (size l + 1), { cases nat.eq_zero_or_pos (size l) with l0 l0, { apply or.inr, rwa l0 at this }, change 1 ≤ _ at l0, apply or.inl, linarith }, rcases H2 with ⟨hl, rfl⟩ | ⟨hr, rfl⟩; rcases H1 with h | ⟨h₁, h₂⟩, { exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) }, { exact le_trans h₂ (nat.mul_le_mul_left _ $ le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) }, { exact le_trans (nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) }, { rw nat.mul_succ, exact le_trans (nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr dec_trivial)) }, end theorem valid'.balance' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance' α l x r) o₂ := let ⟨l', r', H1, H2⟩ := H in valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm) theorem valid'.balance {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance α l x r) o₂ := by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H theorem valid'.balance_l_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance_l α l x r) o₂ := begin rw [balance_l_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2], refine hl.balance'_aux hr (or.inl _) H₃, cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0, exact nat.zero_le _ }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, exact le_trans (nat.mul_le_mul_left _ (H₁ l0)) dec_trivial }, replace H₂ : _ ≤ 3 * _ := H₂ l0 r0, linarith end theorem valid'.balance_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_l α l x r) o₂ := begin rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H, refine hl.balance' hr _, rcases H with ⟨l', e, H⟩ | ⟨r', e, H⟩, { exact ⟨_, _, H, or.inl ⟨e.dist_le', rfl⟩⟩ }, { exact ⟨_, _, H, or.inr ⟨e.dist_le, rfl⟩⟩ }, end theorem valid'.balance_r_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@balance_r α l x r) o₂ := begin rw [valid'.dual_iff, dual_balance_r], have := hr.dual.balance_l_aux hl.dual, rw [size_dual, size_dual] at this, exact this H₁ H₂ H₃ end theorem valid'.balance_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_r α l x r) o₂ := by rw [valid'.dual_iff, dual_balance_r]; exact hr.dual.balance_l hl.dual (balance_sz_dual H) theorem valid'.erase_max_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ (@erase_max α (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := begin have := H.2.eq_node', rw this at H, clear this, induction r with rs rl rx rr IHrl IHrr generalizing l x o₁, { exact ⟨H.left, rfl⟩ }, have := H.2.2.2.eq_node', rw this at H ⊢, rcases IHrr H.right with ⟨h, e⟩, refine ⟨valid'.balance_l H.left h (or.inr ⟨_, or.inr e, H.3.1⟩), _⟩, rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr ⟨_, or.inr e, H.3.1⟩)], rw [size, e], refl end theorem valid'.erase_min_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' ↑(find_min' l x) (@erase_min α (node' l x r)) o₂ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := by have := H.dual.erase_max_aux; rwa [← dual_node', size_dual, ← dual_erase_min, size_dual, ← valid'.dual_iff, find_max'_dual] at this theorem erase_min.valid : ∀ {t} (h : @valid α _ t), valid (erase_min t) | nil _ := valid_nil | (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid theorem erase_max.valid {t} (h : @valid α _ t) : valid (erase_max t) := by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual theorem valid'.glue_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) (bal : balanced_sz (size l) (size r)) : valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := begin cases l with ls ll lx lr, {exact ⟨hr, (zero_add _).symm⟩ }, cases r with rs rl rx rr, {exact ⟨hl, rfl⟩ }, dsimp [glue], split_ifs, { rw [split_max_eq, glue], cases valid'.erase_max_aux hl with v e, suffices H, refine ⟨valid'.balance_r v (hr.of_gt _ _) H, _⟩, { refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _), exact λ x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) }, { exact @find_max'_all _ (λ a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 }, { rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1], refl }, { refine or.inl ⟨_, or.inr e, _⟩, rwa hl.2.eq_node' at bal } }, { rw [split_min_eq, glue], cases valid'.erase_min_aux hr with v e, suffices H, refine ⟨valid'.balance_l (hl.of_lt _ _) v H, _⟩, { refine @find_min'_all _ (λ a, bounded nil o₁ ↑a) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil, exact λ y h, hl.1.1.to_nil.mono_right (le_of_lt h) }, { exact @find_min'_all _ (λ a, all (< a) (node ls ll lx lr)) rl rx (all_iff_forall.2 $ λ x hx, sep.imp $ λ y hy, all_iff_forall.1 hy.1 _ hx) (sep.imp $ λ y hy, hy.2.1) }, { rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1], refl }, { refine or.inr ⟨_, or.inr e, _⟩, rwa hr.2.eq_node' at bal } }, end theorem valid'.glue {l x r o₁ o₂} (hl : valid' o₁ l ↑(x:α)) (hr : valid' ↑x r o₂) : balanced_sz (size l) (size r) → valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r := valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) : 2 * (a + b) ≤ 9 * c + 5 := by linarith theorem valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t} (hl : valid' o₁ (@node α ls ll lx lr) o₂) (hr : valid' o₁ (node rs rl rx rr) o₂) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) o₂ ∧ size (balance_l t rx rr) = ls + rs := begin rw hl.2.1 at e, rw [hl.2.1, hr.2.1, delta] at h, rcases hr.3.1 with H|⟨hr₁, hr₂⟩, {linarith}, suffices H₂, suffices H₁, refine ⟨valid'.balance_l_aux v hr.right H₁ H₂ _, _⟩, { rw e, exact or.inl (valid'.merge_lemma h hr₁) }, { rw [balance_l_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] }, { rw [e, add_right_comm], rintro ⟨⟩ }, { intros _ h₁, rw e, unfold delta at hr₂ ⊢, linarith } end theorem valid'.merge_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) : valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := begin induction l with ls ll lx lr IHll IHlr generalizing o₁ o₂ r, { exact ⟨hr, (zero_add _).symm⟩ }, induction r with rs rl rx rr IHrl IHrr generalizing o₁ o₂, { exact ⟨hl, rfl⟩ }, rw [merge_node], split_ifs, { cases IHrl (sep.imp $ λ x h, h.1) (hl.of_lt hr.1.1.to_nil $ sep.imp $ λ x h, h.2.1) hr.left with v e, exact valid'.merge_aux₁ hl hr h v e }, { cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e, have := valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual, rw [size_dual, add_comm, size_dual, ← dual_balance_r, ← valid'.dual_iff, size_dual, add_comm rs] at this, exact this e }, { refine valid'.glue_aux hl hr sep (or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) } end theorem valid.merge {l r} (hl : valid l) (hr : valid r) (sep : l.all (λ x, r.all (λ y, x < y))) : valid (@merge α l r) := (valid'.merge_aux hl hr sep).1 theorem insert_with.valid_aux [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) : ∀ {t o₁ o₂}, valid' o₁ t o₂ → bounded nil o₁ ↑x → bounded nil ↑x o₂ → valid' o₁ (insert_with f x t) o₂ ∧ raised (size t) (size (insert_with f x t)) | nil o₁ o₂ _ bl br := ⟨valid'_singleton bl br, or.inr rfl⟩ | (node sz l y r) o₁ o₂ h bl br := begin rw [insert_with, cmp_le], split_ifs; rw [insert_with], { rcases h with ⟨⟨lx, xr⟩, hs, hb⟩, rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩, refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, or.inl rfl⟩ }, { rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩, suffices H, { refine ⟨vl.balance_l h.right H, _⟩, rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq], refine (e.add_right _).add_right _ }, { exact or.inl ⟨_, e, h.3.1⟩ } }, { have : y < x := lt_of_le_not_le ((total_of (≤) _ _).resolve_left h_1) h_1, rcases insert_with.valid_aux h.right this br with ⟨vr, e⟩, suffices H, { refine ⟨h.left.balance_r vr H, _⟩, rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq], refine (e.add_left _).add_right _ }, { exact or.inr ⟨_, e, h.3.1⟩ } }, end theorem insert_with.valid [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : valid t) : valid (insert_with f x t) := (insert_with.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, ordnode.insert x t = insert_with (λ _, x) x t | nil := rfl | (node _ l y r) := by unfold ordnode.insert insert_with; cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with] theorem insert.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (ordnode.insert x t) := by rw insert_eq_insert_with; exact insert_with.valid _ _ (λ _ _, ⟨le_refl _, le_refl _⟩) h theorem insert'_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, insert' x t = insert_with id x t | nil := rfl | (node _ l y r) := by unfold insert' insert_with; cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with] theorem insert'.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (insert' x t) := by rw insert'_eq_insert_with; exact insert_with.valid _ _ (λ _, id) h theorem valid'.map_aux {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' (option.map f a₁) (map f t) (option.map f a₂) ∧ (map f t).size = t.size := begin induction t generalizing a₁ a₂, { simp [map], apply valid'_nil, cases a₁, { trivial }, cases a₂, { trivial }, simp [bounded], exact f_strict_mono h.ord }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, simp [map], split, { exact and.intro t_l_valid.ord t_r_valid.ord }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.sz.1 }, { exact t_l_valid.sz }, { exact t_r_valid.sz } }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.bal.1 }, { exact t_l_valid.bal }, { exact t_r_valid.bal } } }, end theorem map.valid {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t} (h : valid t) : valid (map f t) := (valid'.map_aux f_strict_mono h).1 theorem valid'.erase_aux [@decidable_rel α (≤)] (x : α) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' a₁ (erase x t) a₂ ∧ raised (erase x t).size t.size := begin induction t generalizing a₁ a₂, { simp [erase, raised], exact h }, { simp [erase], have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, cases (cmp_le x t_x); simp [erase._match_1]; rw h.sz.1, { suffices h_balanceable, split, { exact valid'.balance_r t_l_valid h.right h_balanceable }, { rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable, repeat { apply raised.add_right }, exact t_l_size }, { left, existsi t_l.size, exact (and.intro t_l_size h.bal.1) } }, { have h_glue := valid'.glue h.left h.right h.bal.1, cases h_glue with h_glue_valid h_glue_sized, split, { exact h_glue_valid }, { right, rw h_glue_sized } }, { suffices h_balanceable, split, { exact valid'.balance_l h.left t_r_valid h_balanceable }, { rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable, apply raised.add_right, apply raised.add_left, exact t_r_size }, { right, existsi t_r.size, exact (and.intro t_r_size h.bal.1) } } }, end theorem erase.valid [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (erase x t) := (valid'.erase_aux x h).1 theorem size_erase_of_mem [@decidable_rel α (≤)] {x : α} {t a₁ a₂} (h : valid' a₁ t a₂) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := begin induction t generalizing a₁ a₂ h h_mem, { contradiction }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, unfold has_mem.mem mem at h_mem, unfold erase, cases (cmp_le x t_x); simp [mem._match_1] at h_mem; simp [erase._match_1], { have t_ih_l := t_ih_l' h_mem, clear t_ih_l' t_ih_r', have t_l_h := valid'.erase_aux x h.left, cases t_l_h with t_l_valid t_l_size, rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (or.inl (exists.intro t_l.size (and.intro t_l_size h.bal.1))), rw [t_ih_l, h.sz.1], have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem, cases t_l.size with t_l_size, { cases h_pos_t_l_size }, simp [nat.succ_add] }, { rw [(valid'.glue h.left h.right h.bal.1).2, h.sz.1], refl }, { have t_ih_r := t_ih_r' h_mem, clear t_ih_l' t_ih_r', have t_r_h := valid'.erase_aux x h.right, cases t_r_h with t_r_valid t_r_size, rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (or.inr (exists.intro t_r.size (and.intro t_r_size h.bal.1))), rw [t_ih_r, h.sz.1], have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem, cases t_r.size with t_r_size, { cases h_pos_t_r_size }, simp [nat.succ_add, nat.add_succ] } }, end end end ordnode /-- An `ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (α : Type*) [preorder α] := {t : ordnode α // t.valid} namespace ordset open ordnode variable [preorder α] /-- O(1). The empty set. -/ def nil : ordset α := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : ordset α) : ℕ := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : α) : ordset α := ⟨singleton a, valid_singleton⟩ instance : has_emptyc (ordset α) := ⟨nil⟩ instance : inhabited (ordset α) := ⟨nil⟩ instance : has_singleton α (ordset α) := ⟨ordset.singleton⟩ /-- O(1). Is the set empty? -/ def empty (s : ordset α) : Prop := s = ∅ theorem empty_iff {s : ordset α} : s = ∅ ↔ s.1.empty := ⟨λ h, by cases h; exact rfl, λ h, by cases s; cases s_val; [exact rfl, cases h]⟩ instance : decidable_pred (@empty α _) := λ s, decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.insert x s.1, insert.valid _ s.2⟩ instance [is_total α (≤)] [@decidable_rel α (≤)] : has_insert α (ordset α) := ⟨ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variables [@decidable_rel α (≤)] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : α) (s : ordset α) : bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : α) (s : ordset α) : option α := ordnode.find x s.val instance : has_mem α (ordset α) := ⟨λ x s, mem x s⟩ instance mem.decidable (x : α) (s : ordset α) : decidable (x ∈ s) := bool.decidable_eq _ _ theorem pos_size_of_mem {x : α} {t : ordset α} (h_mem : x ∈ t) : 0 < size t := begin simp [has_mem.mem, mem] at h_mem, apply ordnode.pos_size_of_mem t.property.sz h_mem, end end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.erase x s.val, ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {β} [preorder β] (f : α → β) (f_strict_mono : strict_mono f) (s : ordset α) : ordset β := ⟨ordnode.map f s.val, ordnode.map.valid f_strict_mono s.property⟩ end ordset
65ceacddad1a25ad0829d252f7b3d8f26d91575c
785b41b0993f39cbfa9b02fe0940ce3f2f51a57d
/conf/dz2.lean
b490a6c5ce48998a62e7a90d8ac58a419ddfd864
[ "MIT" ]
permissive
loso3000/OpenWrt-DIY-1
75b0d70314d703203508218a29acefc3b914d32d
5858be81ee44199908cbaa1a752b17505c9834e8
refs/heads/main
1,690,532,461,283
1,631,008,241,000
1,631,008,241,000
354,817,508
1
0
MIT
1,617,623,493,000
1,617,623,492,000
null
UTF-8
Lean
false
false
14,025
lean
CONFIG_TARGET_x86=y CONFIG_TARGET_x86_64=y CONFIG_TARGET_x86_64_DEVICE_generic=y # 设置固件大小 CONFIG_TARGET_KERNEL_PARTSIZE=64 CONFIG_TARGET_ROOTFS_PARTSIZE=1516 # EFI支持: CONFIG_GRUB_IMAGES=y CONFIG_EFI_IMAGES=y # CONFIG_VMDK_IMAGES is not set # 不压缩efi # CONFIG_TARGET_ROOTFS_TARGZ is not set # CONFIG_TARGET_IMAGES_GZIP is not set # Wireless # CONFIG_PACKAGE_wpad-basic-wolfssl is not set #ipv6 CONFIG_PACKAGE_ipv6helper=y CONFIG_PACKAGE_dnsmasq_full_dhcpv6=y #添加SD卡支持 CONFIG_PACKAGE_kmod-mmc=y CONFIG_PACKAGE_kmod-sdhci=y #添加USB扩展支持 CONFIG_PACKAGE_block-mount=y CONFIG_PACKAGE_librt=y # x86 CONFIG_PACKAGE_kmod-usb-hid=y CONFIG_PACKAGE_qemu-ga=y CONFIG_PACKAGE_lm-sensors-detect=y CONFIG_PACKAGE_kmod-bonding=y CONFIG_PACKAGE_kmod-mmc-spi=y CONFIG_PACKAGE_ppp-mod-pptp=y #VPN客户端 CONFIG_PACKAGE_kmod-vmxnet3=y CONFIG_PACKAGE_kmod-igbvf=y CONFIG_PACKAGE_kmod-ixgbe=y CONFIG_PACKAGE_kmod-pcnet32=y CONFIG_PACKAGE_kmod-r8125=y CONFIG_PACKAGE_kmod-r8168=y CONFIG_PACKAGE_kmod-8139cp=y CONFIG_PACKAGE_kmod-8139too=y CONFIG_PACKAGE_kmod-rtl8xxxu=y CONFIG_PACKAGE_kmod-i40e=y CONFIG_PACKAGE_kmod-i40evf=y CONFIG_PACKAGE_kmod-ath5k=y CONFIG_PACKAGE_kmod-ath9k=y CONFIG_PACKAGE_kmod-ath9k-htc=y CONFIG_PACKAGE_kmod-ath10k=y CONFIG_PACKAGE_kmod-rt2800-usb=y CONFIG_PACKAGE_kmod-mlx4-core=y CONFIG_PACKAGE_kmod-mlx5-core=y CONFIG_PACKAGE_kmod-alx=y CONFIG_PACKAGE_kmod-tulip=y CONFIG_PACKAGE_kmod-tg3=y CONFIG_PACKAGE_kmod-fs-antfs=y # CONFIG_PACKAGE_kmod-fs-ntfs is not set CONFIG_PACKAGE_ath10k-firmware-qca9888=y CONFIG_PACKAGE_ath10k-firmware-qca988x=y CONFIG_PACKAGE_ath10k-firmware-qca9984=y CONFIG_PACKAGE_brcmfmac-firmware-43602a1-pcie=y CONFIG_PACKAGE_kmod-ac97=y CONFIG_PACKAGE_kmod-sound-via82xx=y CONFIG_PACKAGE_alsa-utils=y CONFIG_PACKAGE_kmod-iwlwifi=y #工具 CONFIG_PACKAGE_acpid=y CONFIG_PACKAGE_blkid=y CONFIG_PACKAGE_smartmontools=y # CONFIG_PACKAGE_open-vm-tools is not set CONFIG_PACKAGE_ethtool=y CONFIG_PACKAGE_iperf3=y # CONFIG_PACKAGE_snmpd is not set # CONFIG_PACKAGE_parted is not set CONFIG_PACKAGE_fdisk=y CONFIG_PACKAGE_hdparm=y CONFIG_PACKAGE_curl=y # USB3.0支持: CONFIG_PACKAGE_kmod-usb2=y CONFIG_PACKAGE_kmod-usb2-pci=y CONFIG_PACKAGE_kmod-usb3=y CONFIG_PACKAGE_kmod-usb-audio=y CONFIG_PACKAGE_kmod-usb-printer=y #nfs CONFIG_PACKAGE_kmod-fs-nfsd=y CONFIG_PACKAGE_kmod-fs-nfs=y CONFIG_PACKAGE_kmod-fs-nfs-v4=y #Sound Support CONFIG_PACKAGE_kmod-sound-core=y CONFIG_PACKAGE_kmod-sound-hda-core=y CONFIG_PACKAGE_kmod-sound-hda-codec-realtek=y CONFIG_PACKAGE_kmod-sound-hda-codec-via=y CONFIG_PACKAGE_kmod-sound-hda-intel=y CONFIG_PACKAGE_kmod-sound-hda-codec-hdmi=y #USB net driver CONFIG_PACKAGE_kmod-rtlwifi=y CONFIG_PACKAGE_kmod-rtlwifi-btcoexist=y CONFIG_PACKAGE_kmod-rtlwifi-usb=y CONFIG_PACKAGE_kmod-rtl8812au-ac=y CONFIG_PACKAGE_usb-modeswitch=y CONFIG_PACKAGE_kmod-rtl8192cu=y CONFIG_PACKAGE_kmod-rtl8821cu=y CONFIG_PACKAGE_kmod-mt76=y CONFIG_PACKAGE_kmod-mt76x2u=y CONFIG_PACKAGE_kmod-usb-net-asix=y CONFIG_PACKAGE_kmod-usb-net-asix-ax88179=y CONFIG_PACKAGE_kmod-usb-net-rtl8152-vendor=y CONFIG_PACKAGE_kmod-usb-net-rndis=y CONFIG_PACKAGE_kmod-usb-net-cdc-ether=y CONFIG_PACKAGE_kmod-usb-net-ipheth=y # L2TP CONFIG_PACKAGE_kmod-pppol2tp=y # pptp # CONFIG_PACKAGE_kmod-pptp is not set # CONFIG_PACKAGE_kmod-gre is not set # CONFIG_PACKAGE_kmod-nf-nathelper-extra is not set # ipsec-vpnd CONFIG_PACKAGE_kmod-crypto-authenc=y CONFIG_PACKAGE_kmod-ipsec=y CONFIG_PACKAGE_kmod-ipsec4=y CONFIG_PACKAGE_kmod-ipsec6=y CONFIG_PACKAGE_kmod-ipt-ipsec=y # cifsmount # CONFIG_PACKAGE_kmod-fs-cifs=y CONFIG_PACKAGE_kmod-nls-utf8=y CONFIG_PACKAGE_kmod-crypto-misc=y # eqos CONFIG_PACKAGE_kmod-ifb=y # map CONFIG_PACKAGE_kmod-ip6-tunnel=y CONFIG_PACKAGE_kmod-nat46=y # ebtables CONFIG_PACKAGE_kmod-ebtables=y CONFIG_PACKAGE_kmod-ebtables-ipv4=y CONFIG_PACKAGE_kmod-ebtables-ipv6=y #add upnp # CONFIG_PACKAGE_irqbalance is not set CONFIG_PACKAGE_miniupnpd=y CONFIG_PACKAGE_miniupnpd-igdv1=y CONFIG_PACKAGE_luci-app-upnp=y # CONFIG_PACKAGE_luci-app-boostupnp is not set # CONFIG_PACKAGE_luci-app-wol is not set CONFIG_PACKAGE_luci-app-wolplus=y #base插件 CONFIG_PACKAGE_ddns-scripts_cloudflare.com-v4=y CONFIG_PACKAGE_ddns-scripts=y CONFIG_PACKAGE_ddns-scripts_freedns_42_pl=y CONFIG_PACKAGE_ddns-scripts_godaddy.com-v1=y CONFIG_PACKAGE_ddns-scripts_no-ip_com=y CONFIG_PACKAGE_ddns-scripts_nsupdate=y CONFIG_PACKAGE_ddns-scripts_route53-v1=y # CONFIG_PACKAGE_autosamba is not set # CONFIG_PACKAGE_autosamba-ksmbd is not set CONFIG_PACKAGE_autosamba-samba4=y # CONFIG_PACKAGE_luci-app-accesscontrol is not set # CONFIG_PACKAGE_luci-app-adbyby-plus is not set # CONFIG_PACKAGE_luci-app-adguardhome is not set CONFIG_PACKAGE_luci-app-advanced=y # CONFIG_PACKAGE_luci-app-autotimeset is not set CONFIG_PACKAGE_luci-app-rebootschedule=y # CONFIG_PACKAGE_luci-app-autoreboot is not set # CONFIG_PACKAGE_luci-app-control-timewol is not set CONFIG_PACKAGE_luci-app-control-weburl=y # CONFIG_PACKAGE_luci-app-control-webrestriction is not set CONFIG_PACKAGE_luci-app-control-speedlimit=y CONFIG_PACKAGE_luci-app-timecontrol=y # CONFIG_PACKAGE_luci-app-webadmin is not set # CONFIG_PACKAGE_luci-app-cpulimit is not set # CONFIG_PACKAGE_luci-app-diskman is not set CONFIG_PACKAGE_luci-app-diskman_INCLUDE_mdadm=y # CONFIG_PACKAGE_luci-app-eqos is not set # CONFIG_PACKAGE_luci-app-filetransfer is not set # CONFIG_PACKAGE_luci-app-hd-idle is not set # CONFIG_PACKAGE_luci-app-jd-dailybonus is not set # CONFIG_PACKAGE_luci-app-koolproxyR is not set # CONFIG_PACKAGE_luci-app-netdata is not set # CONFIG_PACKAGE_luci-app-onliner is not set # CONFIG_PACKAGE_luci-app-openclash is not set # CONFIG_PACKAGE_luci-app-samba is not set CONFIG_PACKAGE_luci-app-samba4=y # CONFIG_PACKAGE_luci-app-serverchan is not set # CONFIG_PACKAGE_luci-app-sfe is not set # CONFIG_PACKAGE_luci-app-flowoffload is not set # CONFIG_PACKAGE_luci-app-smartdns is not set # CONFIG_PACKAGE_luci-app-passwall is not set # CONFIG_PACKAGE_luci-app-ssr-plus is not set CONFIG_PACKAGE_luci-app-ttyd=y # CONFIG_PACKAGE_luci-app-turboacc is not set # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_flow-offload is not set # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_shortcut-fe=y # CONFIG_PACKAGE_luci-app-vssr is not set # CONFIG_PACKAGE_luci-app-wrtbwmon is not set CONFIG_PACKAGE_luci-app-nlbwmon=y # CONFIG_PACKAGE_luci-app-netspeedtest is not set # CONFIG_PACKAGE_luci-app-dnsto is not set # CONFIG_PACKAGE_luci-app-bypass is not set CONFIG_PACKAGE_luci-app-dnsfilter=y # CONFIG_PACKAGE_luci-app-kodexplorer is not set # CONFIG_PACKAGE_luci-app-uhttpd is not set # CONFIG_PACKAGE_luci-app-mentohust is not set # CONFIG_PACKAGE_luci-app-easymesh is not set # CONFIG_PACKAGE_luci-app-wifimac is not set CONFIG_PACKAGE_luci-app-ssrpro=y # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Kcptun is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_NaiveProxy is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Redsocks2 is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Shadowsocks_Libev_Client is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Shadowsocks_Libev_Server is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_ShadowsocksR_Libev_Client is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_ShadowsocksR_Libev_Server is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Simple_Obfs is not set CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Trojan=y # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_V2ray_Plugin is not set # CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Xray is not set # CONFIG_PACKAGE_luci-app-ttnode is not set # CONFIG_PACKAGE_luci-app-adblock-plus is not set # CONFIG_PACKAGE_luci-app-change-mac is not set CONFIG_PACKAGE_luci-app-mac=y # CONFIG_PACKAGE_luci-app-vsftpd is not set #主题 # CONFIG_PACKAGE_luci-theme-argon_new is not set # CONFIG_PACKAGE_luci-theme-btmod is not set # CONFIG_PACKAGE_luci-theme-opentomcat is not set CONFIG_PACKAGE_luci-theme-opentopd=y # CONFIG_PACKAGE_luci-theme-chuqitopd is not set # CONFIG_PACKAGE_luci-theme-ffpdboy is not set # 增加其它插件 # CONFIG_PACKAGE_luci-app-ksmbd is not set # CONFIG_PACKAGE_luci-app-cifsd is not set # CONFIG_PACKAGE_luci-app-cifs-mount is not set # CONFIG_PACKAGE_luci-app-xlnetacc is not set # CONFIG_PACKAGE_luci-app-zerotier is not set # CONFIG_PACKAGE_luci-app-unblockneteasemusic is not set # CONFIG_PACKAGE_luci-app-unblockmusic is not set CONFIG_UnblockNeteaseMusic_Go=y CONFIG_UnblockNeteaseMusic_NodeJS=y CONFIG_PACKAGE_luci-app-mwan3=y # CONFIG_PACKAGE_luci-app-minidlna is not set # CONFIG_PACKAGE_luci-app-rclone is not set # CONFIG_PACKAGE_luci-app-rclone_INCLUDE_fuse-utils is not set # CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-ng is not set # CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-webui is not set # CONFIG_PACKAGE_luci-app-pptp-server is not set # CONFIG_PACKAGE_luci-app-pppoe-server is not set # CONFIG_PACKAGE_luci-app-ipsec-vpnd is not set # CONFIG_PACKAGE_luci-app-ipsec-serve is not set # CONFIG_PACKAGE_luci-app-ipsec-vpnserver-manyusers is not set # CONFIG_PACKAGE_luci-app-docker is not set # CONFIG_PACKAGE_luci-app-dockerman is not set # CONFIG_PACKAGE_luci-app-koolddns is not set CONFIG_PACKAGE_luci-app-syncdial=y # CONFIG_PACKAGE_luci-app-softethervpn is not set # CONFIG_PACKAGE_luci-app-uugamebooster is not set # CONFIG_DEFAULT_luci-app-cpufreq is not set # CONFIG_PACKAGE_luci-app-udpxy is not set # CONFIG_PACKAGE_luci-app-socat is not set # CONFIG_PACKAGE_luci-app-oaf is not set # CONFIG_PACKAGE_luci-app-transmission is not set # CONFIG_PACKAGE_luci-app-usb-printer is not set # CONFIG_PACKAGE_luci-app-mwan3helper is not set # CONFIG_PACKAGE_luci-app-qbittorrent is not set # CONFIG_PACKAGE_luci-app-familycloud is not set # CONFIG_PACKAGE_luci-app-nps is not set # CONFIG_PACKAGE_luci-app-frpc is not set #CONFIG_PACKAGE_luci-app-nfs is not set # CONFIG_PACKAGE_luci-app-openvpn-server is not set # CONFIG_PACKAGE_luci-app-aria2 is not set # CONFIG_PACKAGE_luci-app-openvpn is not set # network # CONFIG_PACKAGE_r8169-firmware is not set CONFIG_PACKAGE_bnx2x-firmware=y CONFIG_PACKAGE_e100-firmware=y CONFIG_PACKAGE_kmod-3c59x=y CONFIG_PACKAGE_kmod-atl1=y CONFIG_PACKAGE_kmod-atl1c=y CONFIG_PACKAGE_kmod-atl1e=y CONFIG_PACKAGE_kmod-atl2=y CONFIG_PACKAGE_kmod-atm=y CONFIG_PACKAGE_kmod-b44=y CONFIG_PACKAGE_kmod-be2net=y CONFIG_PACKAGE_kmod-bnx2x=y CONFIG_PACKAGE_kmod-dm9000=y CONFIG_PACKAGE_kmod-dummy=y CONFIG_PACKAGE_kmod-e100=y CONFIG_PACKAGE_kmod-et131x=y CONFIG_PACKAGE_kmod-ethoc=y CONFIG_PACKAGE_kmod-hfcmulti=y CONFIG_PACKAGE_kmod-hfcpci=y CONFIG_PACKAGE_kmod-iavf=y CONFIG_PACKAGE_kmod-ixgbevf=y CONFIG_PACKAGE_kmod-lib-crc32c=y CONFIG_PACKAGE_kmod-mdio-gpio=y CONFIG_PACKAGE_kmod-misdn=y CONFIG_PACKAGE_kmod-natsemi=y CONFIG_PACKAGE_kmod-ne2k-pci=y CONFIG_PACKAGE_kmod-niu=y CONFIG_PACKAGE_kmod-of-mdio=y CONFIG_PACKAGE_kmod-phy-bcm84881=y CONFIG_PACKAGE_kmod-phy-broadcom=y CONFIG_PACKAGE_kmod-phy-realtek=y CONFIG_PACKAGE_kmod-phylib-broadcom=y CONFIG_PACKAGE_kmod-phylink=y # CONFIG_PACKAGE_kmod-r8169 is not set CONFIG_PACKAGE_kmod-random-core=y CONFIG_PACKAGE_kmod-sfp=y CONFIG_PACKAGE_kmod-siit=y CONFIG_PACKAGE_kmod-sis190=y CONFIG_PACKAGE_kmod-sis900=y CONFIG_PACKAGE_kmod-skge=y CONFIG_PACKAGE_kmod-sky2=y CONFIG_PACKAGE_kmod-solos-pci=y CONFIG_PACKAGE_kmod-spi-ks8995=y CONFIG_PACKAGE_kmod-ssb=y CONFIG_PACKAGE_kmod-swconfig=y CONFIG_PACKAGE_kmod-switch-bcm53xx=y CONFIG_PACKAGE_kmod-switch-bcm53xx-mdio=y CONFIG_PACKAGE_kmod-switch-ip17xx=y CONFIG_PACKAGE_kmod-switch-mvsw61xx=y CONFIG_PACKAGE_kmod-switch-rtl8306=y CONFIG_PACKAGE_kmod-switch-rtl8366-smi=y CONFIG_PACKAGE_kmod-switch-rtl8366rb=y CONFIG_PACKAGE_kmod-switch-rtl8366s=y CONFIG_PACKAGE_kmod-switch-rtl8367b=y CONFIG_PACKAGE_kmod-usb-atm=y CONFIG_PACKAGE_kmod-usb-atm-cxacru=y CONFIG_PACKAGE_kmod-usb-atm-speedtouch=y CONFIG_PACKAGE_kmod-usb-atm-ueagle=y CONFIG_PACKAGE_kmod-usb-cm109=y CONFIG_PACKAGE_kmod-usb-dwc2=y CONFIG_PACKAGE_kmod-usb-dwc3=y CONFIG_PACKAGE_kmod-usb-ehci=y CONFIG_PACKAGE_kmod-usb-ledtrig-usbport=y CONFIG_PACKAGE_kmod-usb-net-cdc-eem=y CONFIG_PACKAGE_kmod-usb-net-cdc-mbim=y CONFIG_PACKAGE_kmod-usb-net-cdc-ncm=y CONFIG_PACKAGE_kmod-usb-net-cdc-subset=y CONFIG_PACKAGE_kmod-usb-net-dm9601-ether=y CONFIG_PACKAGE_kmod-usb-net-hso=y CONFIG_PACKAGE_kmod-usb-net-huawei-cdc-ncm=y CONFIG_PACKAGE_kmod-usb-net-kalmia=y CONFIG_PACKAGE_kmod-usb-net-kaweth=y CONFIG_PACKAGE_kmod-usb-net-mcs7830=y CONFIG_PACKAGE_kmod-usb-net-pegasus=y CONFIG_PACKAGE_kmod-usb-net-pl=y CONFIG_PACKAGE_kmod-usb-net-qmi-wwan=y CONFIG_PACKAGE_kmod-usb-net-sierrawireless=y CONFIG_PACKAGE_kmod-usb-net-smsc95xx=y CONFIG_PACKAGE_kmod-usb-net-sr9700=y CONFIG_PACKAGE_kmod-usb-ohci=y CONFIG_PACKAGE_kmod-usb-ohci-pci=y CONFIG_PACKAGE_kmod-usb-uhci=y CONFIG_PACKAGE_kmod-usb-wdm=y CONFIG_PACKAGE_kmod-usb-yealink=y CONFIG_PACKAGE_kmod-usbip=y CONFIG_PACKAGE_kmod-usbip-client=y CONFIG_PACKAGE_kmod-usbip-server=y CONFIG_PACKAGE_kmod-usbmon=y CONFIG_PACKAGE_kmod-via-rhine=y CONFIG_PACKAGE_kmod-via-velocity=y #add drive CONFIG_PACKAGE_kmod-usb-net-rtl8150=y CONFIG_PACKAGE_kmod-usb-storage=y # Block Devices 挂载硬盘支持 CONFIG_PACKAGE_kmod-ata-core=y CONFIG_PACKAGE_kmod-block2mtd=y CONFIG_PACKAGE_kmod-scsi-core=y CONFIG_PACKAGE_kmod-scsi-generic=y CONFIG_PACKAGE_blockd=y CONFIG_PACKAGE_kmod-ata-ahci=y CONFIG_PACKAGE_kmod-ata-artop=y CONFIG_PACKAGE_kmod-ata-marvell-sata=y CONFIG_PACKAGE_kmod-ata-nvidia-sata=y CONFIG_PACKAGE_kmod-ata-pdc202xx-old=y CONFIG_PACKAGE_kmod-ata-piix=y CONFIG_PACKAGE_kmod-ata-sil=y CONFIG_PACKAGE_kmod-ata-sil24=y CONFIG_PACKAGE_kmod-ata-via-sata=y CONFIG_PACKAGE_kmod-dax=y CONFIG_PACKAGE_kmod-dm-raid=y CONFIG_PACKAGE_kmod-fs-autofs4=y CONFIG_PACKAGE_kmod-lib-crc32c=y CONFIG_PACKAGE_kmod-lib-raid6=y CONFIG_PACKAGE_kmod-lib-xor=y CONFIG_PACKAGE_kmod-md-mod=y CONFIG_PACKAGE_kmod-md-raid0=y CONFIG_PACKAGE_kmod-md-raid1=y CONFIG_PACKAGE_kmod-md-raid10=y CONFIG_PACKAGE_kmod-md-raid456=y #3G/4G Support CONFIG_PACKAGE_kmod-usb-serial=y CONFIG_PACKAGE_kmod-usb-serial-option=y CONFIG_PACKAGE_kmod-usb-serial-wwan=y CONFIG_PACKAGE_kmod-mii=y CONFIG_PACKAGE_kmod-usb-acm=y
f9a68fb71c83e101886a0cf49777ed869753ba46
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Tactic/Conv/Congr.lean
15373d736d293d759b413518c02d25536f910b2a
[ "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
7,798
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Congr import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta private def congrImplies (mvarId : MVarId) : MetaM (List MVarId) := do let [mvarId₁, mvarId₂, _, _] ← mvarId.apply (← mkConstWithFreshMVarLevels ``implies_congr) | throwError "'apply implies_congr' unexpected result" let mvarId₁ ← markAsConvGoal mvarId₁ let mvarId₂ ← markAsConvGoal mvarId₂ return [mvarId₁, mvarId₂] private def isImplies (e : Expr) : MetaM Bool := if e.isArrow then isProp e.bindingDomain! <&&> isProp e.bindingBody! else return false def congr (mvarId : MVarId) (addImplicitArgs := false) : MetaM (List (Option MVarId)) := mvarId.withContext do let (lhs, rhs) ← getLhsRhsCore mvarId let lhs := (← instantiateMVars lhs).cleanupAnnotations if (← isImplies lhs) then return (← congrImplies mvarId).map Option.some else if lhs.isApp then let funInfo ← getFunInfo lhs.getAppFn let args := lhs.getAppArgs let some congrThm ← mkCongrSimp? lhs.getAppFn (subsingletonInstImplicitRhs := false) | throwError "'congr' conv tactic failed to create congruence theorem" unless args.size == congrThm.argKinds.size do throwError "'congr' conv tactic failed, unexpected number of arguments in congruence theorem" let mut proof := congrThm.proof let mut mvarIdsNew := #[] let mut mvarIdsNewInsts := #[] for i in [:args.size] do let arg := args[i]! let argInfo := funInfo.paramInfo[i]! match congrThm.argKinds[i]! with | .fixed | .cast => proof := mkApp proof arg; if addImplicitArgs || argInfo.isExplicit then mvarIdsNew := mvarIdsNew.push none | .eq => if addImplicitArgs || argInfo.isExplicit then let (rhs, mvarNew) ← mkConvGoalFor arg; proof := mkApp3 proof arg rhs mvarNew mvarIdsNew := mvarIdsNew.push (some mvarNew.mvarId!) else proof := mkApp3 proof arg arg (← mkEqRefl arg) | .subsingletonInst => proof := mkApp proof arg let rhs ← mkFreshExprMVar (← whnf (← inferType proof)).bindingDomain! proof := mkApp proof rhs mvarIdsNewInsts := mvarIdsNewInsts.push (some rhs.mvarId!) | .heq | .fixedNoParam => unreachable! let some (_, _, rhs') := (← whnf (← inferType proof)).eq? | throwError "'congr' conv tactic failed, equality expected" unless (← isDefEqGuarded rhs rhs') do throwError "invalid 'congr' conv tactic, failed to resolve{indentExpr rhs}\n=?={indentExpr rhs'}" mvarId.assign proof return mvarIdsNew.toList ++ mvarIdsNewInsts.toList else throwError "invalid 'congr' conv tactic, application or implication expected{indentExpr lhs}" @[builtinTactic Lean.Parser.Tactic.Conv.congr] def evalCongr : Tactic := fun _ => do replaceMainGoal <| List.filterMap id (← congr (← getMainGoal)) private def selectIdx (tacticName : String) (mvarIds : List (Option MVarId)) (i : Int) : TacticM Unit := do if i >= 0 then let i := i.toNat if h : i < mvarIds.length then for mvarId? in mvarIds, j in [:mvarIds.length] do match mvarId? with | none => pure () | some mvarId => if i != j then mvarId.refl match mvarIds[i] with | none => throwError "cannot select argument" | some mvarId => replaceMainGoal [mvarId] return () throwError "invalid '{tacticName}' conv tactic, application has only {mvarIds.length} (nondependent) argument(s)" @[builtinTactic Lean.Parser.Tactic.Conv.skip] def evalSkip : Tactic := fun _ => pure () @[builtinTactic Lean.Parser.Tactic.Conv.lhs] def evalLhs : Tactic := fun _ => do let mvarIds ← congr (← getMainGoal) selectIdx "lhs" mvarIds ((mvarIds.length : Int) - 2) @[builtinTactic Lean.Parser.Tactic.Conv.rhs] def evalRhs : Tactic := fun _ => do let mvarIds ← congr (← getMainGoal) selectIdx "rhs" mvarIds ((mvarIds.length : Int) - 1) @[builtinTactic Lean.Parser.Tactic.Conv.arg] def evalArg : Tactic := fun stx => do match stx with | `(conv| arg $[@%$tk?]? $i:num) => let i := i.getNat if i == 0 then throwError "invalid 'arg' conv tactic, index must be greater than 0" let i := i - 1 let mvarIds ← congr (← getMainGoal) (addImplicitArgs := tk?.isSome) selectIdx "arg" mvarIds i | _ => throwUnsupportedSyntax def extLetBodyCongr? (mvarId : MVarId) (lhs rhs : Expr) : MetaM (Option MVarId) := do match lhs with | .letE n t v b _ => let u₁ ← getLevel t let f := mkLambda n .default t b unless (← isTypeCorrect f) do throwError "failed to abstract let-expression, result is not type correct" let (β, u₂, f') ← withLocalDeclD n t fun a => do let type ← inferType (mkApp f a) let β ← mkLambdaFVars #[a] type let u₂ ← getLevel type let rhsBody ← mkFreshExprMVar type let f' ← mkLambdaFVars #[a] rhsBody let rhs' := mkLet n t v f'.bindingBody! unless (← isDefEq rhs rhs') do throwError "failed to go inside let-declaration, type error" return (β, u₂, f') let (arg, mvarId') ← withLocalDeclD n t fun x => do let eqLhs := f.beta #[x] let eqRhs := f'.beta #[x] let mvarNew ← mkFreshExprSyntheticOpaqueMVar (← mkEq eqLhs eqRhs) let arg ← mkLambdaFVars #[x] mvarNew return (arg, mvarNew.mvarId!) let val := mkApp6 (mkConst ``let_body_congr [u₁, u₂]) t β f f' v arg mvarId.assign val return some (← markAsConvGoal mvarId') | _ => return none private def extCore (mvarId : MVarId) (userName? : Option Name) : MetaM MVarId := mvarId.withContext do let (lhs, rhs) ← getLhsRhsCore mvarId let lhs := (← instantiateMVars lhs).cleanupAnnotations if let .forallE n d b bi := lhs then let u ← getLevel d let p : Expr := .lam n d b bi let userName ← if let some userName := userName? then pure userName else mkFreshBinderNameForTactic n let (q, h, mvarNew) ← withLocalDecl userName bi d fun a => do let pa := b.instantiate1 a let (qa, mvarNew) ← mkConvGoalFor pa let q ← mkLambdaFVars #[a] qa let h ← mkLambdaFVars #[a] mvarNew let rhs' ← mkForallFVars #[a] qa unless (← isDefEqGuarded rhs rhs') do throwError "invalid 'ext' conv tactic, failed to resolve{indentExpr rhs}\n=?={indentExpr rhs'}" return (q, h, mvarNew) let proof := mkApp4 (mkConst ``forall_congr [u]) d p q h mvarId.assign proof return mvarNew.mvarId! else if let some mvarId ← extLetBodyCongr? mvarId lhs rhs then return mvarId else let lhsType ← whnfD (← inferType lhs) unless lhsType.isForall do throwError "invalid 'ext' conv tactic, function or arrow expected{indentD m!"{lhs} : {lhsType}"}" let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``funext) | throwError "'apply funext' unexpected result" let userNames := if let some userName := userName? then [userName] else [] let (_, mvarId) ← mvarId.introN 1 userNames markAsConvGoal mvarId private def ext (userName? : Option Name) : TacticM Unit := do replaceMainGoal [← extCore (← getMainGoal) userName?] @[builtinTactic Lean.Parser.Tactic.Conv.ext] def evalExt : Tactic := fun stx => do let ids := stx[1].getArgs if ids.isEmpty then ext none else for id in ids do withRef id <| ext id.getId end Lean.Elab.Tactic.Conv
3385991c40b165d6f1c75de78f7b470c1d28e879
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/trust0/t1.lean
b5a37320680114112239906f9d2a9ade6821ef25
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
35
lean
import Init.System.IO #print trust
c33ca7048ecf1f09133e68114bcc096adb454ddc
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_1/Part_A_logic.lean
f328aa414d16e0ea42b37dca50f7fccab9aa3de6
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
11,734
lean
-- We import all of Lean's standard tactics import tactic /-! # Logic We will develop the basic theory of following five basic logical symbols * `→` ("implies" -- type with `\l`) * `¬` ("not" -- type with `\not` or `\n`) * `∧` ("and" -- type with `\and` or `\an`) * `↔` ("iff" -- type with `\iff` or `\lr`) * `∨` ("or" -- type with `\or` or `\v` # Tactics you will need to know * `intro` * `exact` * `apply` * `rw` * `cases` * `split` * `left` * `right` See `README.md` in `src/week_1` for an explanation of what these tactics do. Note that there are plenty of other tactics, and indeed once you've "got the hang of it" you might want to try tactics such as `cc`, `tauto` and its variant `tauto!`, `finish`, and `library_search`. # What to do The `example`s are to demonstrate things to you. They sometimes use tactics you don't know. You can look at them but you don't need to touch them. The `theorem`s and `lemma`s are things which have no proof. You need to change the `sorry`s into proofs which Lean will accept. This paragraph is a comment, by the way. One-line comments are preceded with `--`. -/ -- We work in a "namespace". All this means is that whenever it -- looks like we've defined a new theorem called `id`, its full -- name is `xena.id`. Which is good because `id` is already -- defined in Lean. namespace xena -- Throughout this namespace, P Q and R will be arbitrary (variable) -- true-false statements. variables (P Q R : Prop) /-! ## implies (→) To prove the theorems in this section, you will need to know about the tactics `intro`, `apply` and `exact`. You might also like the `assumption` tactic. -/ /-- Every proposition implies itself. -/ theorem id : P → P := begin -- Prove this using `intro` and `exact` sorry end /- Note that → isn't associative! Try working out `false → (false → false) and (false → false) → false -/ example : (false → (false → false)) ↔ true := by simp example : ((false → false) → false) ↔ false := by simp -- in Lean, `P → Q → R` is _defined_ to mean `P → (Q → R)` -- Here's a proof of what I just said. example : (P → Q → R) ↔ (P → (Q → R)) := begin -- look at the goal! refl -- true because ↔ is reflexive end theorem imp_intro : P → Q → P := begin -- remember that by definition the goal is P → (Q → P). -- Prove this proposition using `intro` and `exact`. -- Experiment. Can you prove it using `intros` and `assumption`? sorry end /-- If we know `P`, and we also know `P → Q`, we can deduce `Q`. -/ lemma modus_ponens : P → (P → Q) → Q := begin -- You might find the `apply` tactic useful here. sorry end /-- implication is transitive -/ lemma imp_trans : (P → Q) → (Q → R) → (P → R) := begin -- The tactics you know should be enough sorry end -- This one is a "relative modus ponens" -- in the -- presence of P, if Q -> R and Q then R. lemma forall_imp : (P → Q → R) → (P → Q) → (P → R) := begin -- `intros hPQR hPQ hP,` would be a fast way to start. -- Make sure you understand what is going on there, if you use it. sorry end /- ### not `not P`, with notation `¬ P`, is *defined* to mean `P → false` in Lean, i.e., the proposition that P implies false. You can easily check with a truth table that P → false and ¬ P are equivalent. We develop a basic interface for `¬`. -/ -- I'll prove this one for you theorem not_iff_imp_false : ¬ P ↔ (P → false) := begin -- true by definition refl end theorem not_not_intro : P → ¬ (¬ P) := begin intro hP, rw not_iff_imp_false, -- You can use `rw not_iff_imp_false` to change `¬ X` into `X → false`. -- But you don't actually have to, because they are the same *by definition* sorry, end -- Here is a funny alternative proof! Can you work out how it works? example : P → ¬ (¬ P) := begin apply modus_ponens, end -- Here is a proof which does not use tactics at all, but uses lambda calculus. -- It is called a "term mode" proof. We will not be discussing term mode -- much in this course. It is a cool way to do basic logic proofs, but -- it does not scale well in practice. example : P → ¬ (¬ P) := λ hP hnP, hnP hP -- This is "modus tollens". Some mathematicians think of it as -- "proof by contradiction". theorem modus_tollens : (P → Q) → (¬ Q → ¬ P) := begin sorry, end -- This one cannot be proved using constructive mathematics! -- You _have_ to use a tactic like `by_contra` (or, if you're happy -- to cheat, the full "truth table" tactic `tauto!`. -- Try it without using these, and you'll get stuck! theorem double_negation_elimination : ¬ (¬ P) → P := begin sorry, end /-! ### and The hypothesis `hPaQ : P ∧ Q` in Lean, is equivalent to hypotheses `hP : P` and `hQ : Q`. If you have `hPaQ` as a hypothesis, and you want to get to `hP` and `hQ`, you can use the `cases` tactic. If you have `⊢ P ∧ Q` as a goal, and want to turn the goal into two goals `⊢ P` and `⊢ Q`, then use the `split` tactic. Note that after `split` it's good etiquette to use braces e.g. example (hP : P) (hQ : Q) : P ∧ Q := begin split, { exact hP }, { exact hQ } end but for this sort of stuff I think principled indentation is OK ``` example (hP : P) (hQ : Q) : P ∧ Q := begin split, exact hP, exact hQ end ``` -/ theorem and.elim_left : P ∧ Q → P := begin -- I would recommend starting with -- `intro hPaQ,` and then `cases hPaQ with hP hQ`. sorry end theorem and.elim_right : P ∧ Q → Q := begin sorry end -- fancy term mode proof example : P ∧ Q → Q := λ hPaQ, hPaQ.2 theorem and.intro : P → Q → P ∧ Q := begin -- remember the `split` tactic. sorry end /-- the eliminator for `∧` -/ theorem and.elim : P ∧ Q → (P → Q → R) → R := begin sorry, end /-- The recursor for `∧` -/ theorem and.rec : (P → Q → R) → P ∧ Q → R := begin sorry end /-- `∧` is symmetric -/ theorem and.symm : P ∧ Q → Q ∧ P := begin sorry end -- term mode proof example : P ∧ Q → Q ∧ P := λ ⟨hP, hQ⟩, ⟨hQ, hP⟩ /-- `∧` is transitive -/ theorem and.trans : (P ∧ Q) → (Q ∧ R) → (P ∧ R) := begin -- The `rintro` tactic will do `intro` and `cases` all in one go. -- If you like, try starting this proof with `rintro ⟨hP, hQ⟩` if you want -- to experiment with it. Get the pointy brackets with `\<` and `\>`, -- or both at once with `\<>`. sorry, end /- Recall that the convention for the implies sign → is that it is _right associative_, by which I mean that `P → Q → R` means `P → (Q → R)` by definition. Now note that if `P` implies `Q → R` then this means that `P` and `Q` together, imply `R`, so `P → Q → R` is logically equivalent to `(P ∧ Q) → R`. We proved that `P → Q → R` implied `(P ∧ Q) → R`; this was `and.rec`. Let's go the other way. -/ lemma imp_imp_of_and_imp : ((P ∧ Q) → R) → (P → Q → R) := begin sorry, end /-! ### iff The basic theory of `iff`. In Lean, to prove `P ∧ Q` you have to prove `P` and `Q`. Similarly, to prove `P ↔ Q` in Lean, you have to prove `P → Q` and `Q → P`. Just like `∧`, you can uses `cases h` if you have a hypothesis `h : P ↔ Q`, and `split` if you have a goal `⊢ P ↔ Q`. -/ /-- `P ↔ P` is true for all propositions `P`, i.e. `↔` is reflexive. -/ theorem iff.refl : P ↔ P := begin -- start with `split` sorry, end -- If you get stuck, there is always the "truth table" tactic `tauto!` example : P ↔ P := begin tauto!, -- the "truth table" tactic. end -- refl tactic also works example : P ↔ P := begin refl -- `refl` knows that `=` and `↔` are reflexive. end /-- `↔` is symmetric -/ theorem iff.symm : (P ↔ Q) → (Q ↔ P) := begin sorry end -- NB there is quite a devious proof of this using `rw`. -- show-off term mode proof example : (P ↔ Q) → (Q ↔ P) := λ ⟨hPQ, hQP⟩, ⟨hQP, hPQ⟩ /-- `↔` is commutative -/ theorem iff.comm : (P ↔ Q) ↔ (Q ↔ P) := begin sorry end -- without rw or cc this is painful! /-- `↔` is transitive -/ theorem iff.trans : (P ↔ Q) → (Q ↔ R) → (P ↔ R) := begin sorry, end -- This can be done constructively, but it's hard. You'll need to know -- about the `have` tactic to do it. Alternatively the truth table -- tactic `tauto!` will do it. theorem iff.boss : ¬ (P ↔ ¬ P) := begin sorry end -- Now we have iff we can go back to and. /-! ### ↔ and ∧ -/ /-- `∧` is commutative -/ theorem and.comm : P ∧ Q ↔ Q ∧ P := begin sorry, end -- fancy term-mode proof example : P ∧ Q ↔ Q ∧ P := ⟨and.symm _ _, and.symm _ _⟩ -- Note that ∧ is "right associative" in Lean, which means -- that `P ∧ Q ∧ R` is _defined to mean_ `P ∧ (Q ∧ R)`. -- Associativity can hence be written like this: /-- `∧` is associative -/ theorem and_assoc : ((P ∧ Q) ∧ R) ↔ (P ∧ Q ∧ R) := begin sorry, end /-! ## Or `P ∨ Q` is true when at least one of `P` and `Q` are true. Here is how to work with `∨` in Lean. If you have a hypothesis `hPoQ : P ∨ Q` then you can break into the two cases `hP : P` and `hQ : Q` using `cases hPoQ with hP hQ` If you have a _goal_ of the form `⊢ P ∨ Q` then you need to decide whether you're going to prove `P` or `Q`. If you want to prove `P` then use the `left` tactic, and if you want to prove `Q` then use the `right` tactic. -/ -- recall that P, Q, R are Propositions. We'll need S for this one. variable (S : Prop) -- You will need to use the `left` tactic for this one. theorem or.intro_left : P → P ∨ Q := begin sorry end theorem or.intro_right : Q → P ∨ Q := begin sorry, end /-- the eliminator for `∨`. -/ theorem or.elim : P ∨ Q → (P → R) → (Q → R) → R := begin sorry end /-- `∨` is symmetric -/ theorem or.symm : P ∨ Q → Q ∨ P := begin sorry end /-- `∨` is commutative -/ theorem or.comm : P ∨ Q ↔ Q ∨ P := begin sorry, end /-- `∨` is associative -/ theorem or.assoc : (P ∨ Q) ∨ R ↔ P ∨ Q ∨ R := begin sorry, end /-! ### More about → and ∨ -/ theorem or.imp : (P → R) → (Q → S) → P ∨ Q → R ∨ S := begin sorry, end theorem or.imp_left : (P → Q) → P ∨ R → Q ∨ R := begin sorry, end theorem or.imp_right : (P → Q) → R ∨ P → R ∨ Q := begin sorry, end theorem or.left_comm : P ∨ Q ∨ R ↔ Q ∨ P ∨ R := begin -- Try rewriting `or.comm` and `or.assoc` to do this one quickly. sorry, end /-- the recursor for `∨` -/ theorem or.rec : (P → R) → (Q → R) → P ∨ Q → R := begin sorry, end theorem or_congr : (P ↔ R) → (Q ↔ S) → (P ∨ Q ↔ R ∨ S) := begin sorry, end /-! ### true and false `true` is a true-false statement, which can be proved with the `trivial` tactic. `false` is a true-false statment which can only be proved if you manage to find a contradiction within your assumptions. If you manage to end up with a hypothesis `h : false` then there's quite a funny way to proceed, which we now explain. If you have `h : P ∧ Q` then you can uses `cases h with hP hQ` to split into two cases. If you have `h : false` then what do you think happens if we do `cases h`? Hint: how many cases are there? -/ /-- eliminator for `false` -/ theorem false.elim : false → P := begin sorry, end theorem and_true_iff : P ∧ true ↔ P := begin sorry, end theorem or_false_iff : P ∨ false ↔ P := begin sorry, end -- false.elim is handy for this one theorem or.resolve_left : P ∨ Q → ¬P → Q := begin sorry, end -- this one you can't do constructively theorem or_iff_not_imp_left : P ∨ Q ↔ ¬P → Q := begin sorry, end end xena
734133b5f20ffe4ff2acffdcf06cd18863c5e519
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Util/Store.lean
b4fc130e66f0748741febdf36a8b9f52ab785c5c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,301
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ namespace Lake /-- A monad equipped with a dependently typed key-value store for a particular key. -/ class MonadStore1 {κ : Type u} (k : κ) (α : outParam $ Type v) (m : Type v → Type w) where fetch? : m (Option α) store : α → m PUnit export MonadStore1 (fetch? store) /-- A monad equipped with a dependently typed key-object store. -/ class MonadDStore (κ : Type u) (β : outParam $ κ → Type v) (m : Type v → Type w) where fetch? : (key : κ) → m (Option (β key)) store : (key : κ) → β key → m PUnit instance [MonadDStore κ β m] : MonadStore1 k (β k) m where fetch? := MonadDStore.fetch? k store o := MonadDStore.store k o /-- A monad equipped with a key-object store. -/ abbrev MonadStore κ α m := MonadDStore κ (fun _ => α) m instance [MonadLift m n] [MonadDStore κ β m] : MonadDStore κ β n where fetch? k := liftM (m := m) <| fetch? k store k a := liftM (m := m) <| store k a @[inline] def fetchOrCreate [Monad m] (key : κ) [MonadStore1 key α m] (create : m α) : m α := do if let some val ← fetch? key then return val else let val ← create store key val return val
1079b968d60bb4a26b505712575df2f3c52b6364
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/continuous_function/bounded.lean
7ecf9de6162385861a704442c58826aed5de6a7e
[ "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
58,728
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, Mario Carneiro, Yury Kudryashov, Heather Macbeth -/ import analysis.normed_space.lattice_ordered_group import analysis.normed_space.operator_norm import analysis.normed_space.star.basic import data.real.sqrt import topology.continuous_function.algebra /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ noncomputable theory open_locale topological_space classical nnreal open set filter metric function universes u v w variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w} /-- `α →ᵇ β` is the type of bounded continuous functions `α → β` from a topological space to a metric space. When possible, instead of parametrizing results over `(f : α →ᵇ β)`, you should parametrize over `(F : Type*) [bounded_continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `bounded_continuous_map_class`. -/ structure bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [pseudo_metric_space β] extends continuous_map α β : Type (max u v) := (map_bounded' : ∃ C, ∀ x y, dist (to_fun x) (to_fun y) ≤ C) localized "infixr ` →ᵇ `:25 := bounded_continuous_function" in bounded_continuous_function /-- `bounded_continuous_map_class F α β` states that `F` is a type of bounded continuous maps. You should also extend this typeclass when you extend `bounded_continuous_function`. -/ class bounded_continuous_map_class (F α β : Type*) [topological_space α] [pseudo_metric_space β] extends continuous_map_class F α β := (map_bounded (f : F) : ∃ C, ∀ x y, dist (f x) (f y) ≤ C) export bounded_continuous_map_class (map_bounded) namespace bounded_continuous_function section basics variables [topological_space α] [pseudo_metric_space β] [pseudo_metric_space γ] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : bounded_continuous_map_class (α →ᵇ β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := λ f, f.continuous_to_fun, map_bounded := λ f, f.map_bounded' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →ᵇ β) (λ _, α → β) := fun_like.has_coe_to_fun instance [bounded_continuous_map_class F α β] : has_coe_t F (α →ᵇ β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, map_bounded' := map_bounded f }⟩ @[simp] lemma coe_to_continuous_fun (f : α →ᵇ β) : (f.to_continuous_map : α → β) = f := rfl /-- 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 initialize_simps_projections bounded_continuous_function (to_continuous_map_to_fun → apply) protected lemma bounded (f : α →ᵇ β) : ∃C, ∀ x y : α, dist (f x) (f y) ≤ C := f.map_bounded' protected lemma continuous (f : α →ᵇ β) : continuous f := f.to_continuous_map.continuous @[ext] lemma ext (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h lemma bounded_range (f : α →ᵇ β) : bounded (range f) := bounded_range_iff.2 f.bounded lemma bounded_image (f : α →ᵇ β) (s : set α) : bounded (f '' s) := f.bounded_range.mono $ image_subset_range _ _ lemma eq_of_empty [is_empty α] (f g : α →ᵇ β) : f = g := ext $ is_empty.elim ‹_› /-- A continuous function with an explicit bound is a bounded continuous function. -/ def mk_of_bound (f : C(α, β)) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, ⟨C, h⟩⟩ @[simp] lemma mk_of_bound_coe {f} {C} {h} : (mk_of_bound f C h : α → β) = (f : α → β) := rfl /-- A continuous function on a compact space is automatically a bounded continuous function. -/ def mk_of_compact [compact_space α] (f : C(α, β)) : α →ᵇ β := ⟨f, bounded_range_iff.1 (is_compact_range f.continuous).bounded⟩ @[simp] lemma mk_of_compact_apply [compact_space α] (f : C(α, β)) (a : α) : mk_of_compact f a = f a := rfl /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ @[simps] def mk_of_discrete [discrete_topology α] (f : α → β) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨⟨f, continuous_of_discrete_topology⟩, ⟨C, h⟩⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (α →ᵇ β) := ⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩ lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C := begin rcases f.bounded_range.union g.bounded_range with ⟨C, hC⟩, refine ⟨max 0 C, le_max_left _ _, λ x, (hC _ _ _ _).trans (le_max_right _ _)⟩; [left, right]; apply mem_range_self end /-- The pointwise distance is controlled by the distance between functions, by definition. -/ lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_cInf dist_set_exists $ λb hb, hb.2 x /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superseded by the general result that the distance is nonnegative in metric spaces. -/ private lemma dist_nonneg' : 0 ≤ dist f g := le_cInf dist_set_exists (λ C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩ lemma dist_le_iff_of_nonempty [nonempty α] : dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ w, (dist_le (le_trans dist_nonneg (w (nonempty.some ‹_›)))).mpr w⟩ lemma dist_lt_of_nonempty_compact [nonempty α] [compact_space α] (w : ∀x:α, dist (f x) (g x) < C) : dist f g < C := begin have c : continuous (λ x, dist (f x) (g x)), { continuity, }, obtain ⟨x, -, le⟩ := is_compact.exists_forall_ge compact_univ set.univ_nonempty (continuous.continuous_on c), exact lt_of_le_of_lt (dist_le_iff_of_nonempty.mpr (λ y, le y trivial)) (w x), end lemma dist_lt_iff_of_compact [compact_space α] (C0 : (0 : ℝ) < C) : dist f g < C ↔ ∀x:α, dist (f x) (g x) < C := begin fsplit, { intros w x, exact lt_of_le_of_lt (dist_coe_le_dist x) w, }, { by_cases h : nonempty α, { resetI, exact dist_lt_of_nonempty_compact, }, { rintro -, convert C0, apply le_antisymm _ dist_nonneg', rw [dist_eq], exact cInf_le ⟨0, λ C, and.left⟩ ⟨le_rfl, λ x, false.elim (h (nonempty.intro x))⟩, }, }, end lemma dist_lt_iff_of_nonempty_compact [nonempty α] [compact_space α] : dist f g < C ↔ ∀x:α, dist (f x) (g x) < C := ⟨λ w x, lt_of_le_of_lt (dist_coe_le_dist x) w, dist_lt_of_nonempty_compact⟩ /-- The type of bounded continuous functions, with the uniform distance, is a pseudometric space. -/ instance : pseudo_metric_space (α →ᵇ β) := { dist_self := λ f, le_antisymm ((dist_le le_rfl).2 $ λ x, by simp) dist_nonneg', dist_comm := λ f g, by simp [dist_eq, dist_comm], dist_triangle := λ f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance {α β} [topological_space α] [metric_space β] : metric_space (α →ᵇ β) := { eq_of_dist_eq_zero := λ f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg) } lemma nndist_eq : nndist f g = Inf {C | ∀ x : α, nndist (f x) (g x) ≤ C} := subtype.ext $ dist_eq.trans $ begin rw [nnreal.coe_Inf, nnreal.coe_image], simp_rw [mem_set_of_eq, ←nnreal.coe_le_coe, subtype.coe_mk, exists_prop, coe_nndist], end lemma nndist_set_exists : ∃ C, ∀ x : α, nndist (f x) (g x) ≤ C := subtype.exists.mpr $ dist_set_exists.imp $ λ a ⟨ha, h⟩, ⟨ha, h⟩ lemma nndist_coe_le_nndist (x : α) : nndist (f x) (g x) ≤ nndist f g := dist_coe_le_dist x /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty [is_empty α] : dist f g = 0 := by rw [(ext is_empty_elim : f = g), dist_self] lemma dist_eq_supr : dist f g = ⨆ x : α, dist (f x) (g x) := begin casesI is_empty_or_nonempty α, { rw [supr_of_empty', real.Sup_empty, dist_zero_of_empty] }, refine (dist_le_iff_of_nonempty.mpr $ le_csupr _).antisymm (csupr_le dist_coe_le_dist), exact dist_set_exists.imp (λ C hC, forall_range_iff.2 hC.2) end lemma nndist_eq_supr : nndist f g = ⨆ x : α, nndist (f x) (g x) := subtype.ext $ dist_eq_supr.trans $ by simp_rw [nnreal.coe_supr, coe_nndist] lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → (α →ᵇ β)} {f : α →ᵇ β} {l : filter ι} : tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l := iff.intro (λ h, tendsto_uniformly_iff.2 (λ ε ε0, (metric.tendsto_nhds.mp h ε ε0).mp (eventually_of_forall $ λ n hn x, lt_of_le_of_lt (dist_coe_le_dist x) (dist_comm (F n) f ▸ hn)))) (λ h, metric.tendsto_nhds.mpr $ λ ε ε_pos, (h _ (dist_mem_uniformity $ half_pos ε_pos)).mp (eventually_of_forall $ λ n hn, lt_of_le_of_lt ((dist_le (half_pos ε_pos).le).mpr $ λ x, dist_comm (f x) (F n x) ▸ le_of_lt (hn x)) (half_lt_self ε_pos))) variables (α) {β} /-- Constant as a continuous bounded function. -/ @[simps {fully_applied := ff}] def const (b : β) : α →ᵇ β := ⟨continuous_map.const α b, 0, by simp [le_rfl]⟩ variable {α} lemma const_apply' (a : α) (b : β) : (const α b : α → β) a = b := rfl /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α default⟩ lemma lipschitz_evalx (x : α) : lipschitz_with 1 (λ f : α →ᵇ β, f x) := lipschitz_with.mk_one $ λ f g, dist_coe_le_dist x theorem uniform_continuous_coe : @uniform_continuous (α →ᵇ β) (α → β) _ _ coe_fn := uniform_continuous_pi.2 $ λ x, (lipschitz_evalx x).uniform_continuous lemma continuous_coe : continuous (λ (f : α →ᵇ β) x, f x) := uniform_continuous.continuous uniform_continuous_coe /-- When `x` is fixed, `(f : α →ᵇ β) ↦ f x` is continuous -/ @[continuity] theorem continuous_eval_const {x : α} : continuous (λ f : α →ᵇ β, f x) := (continuous_apply x).comp continuous_coe /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ @[continuity] theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) := continuous_prod_of_continuous_lipschitz _ 1 (λ f, f.continuous) $ lipschitz_evalx /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space (α →ᵇ β) := complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : ∀x, cauchy_seq (λn, f n x) := λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N := λ x N, le_of_tendsto (tendsto_const_nhds.dist (hF x)) (filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨⟨F, _⟩, _⟩, _⟩, { /- Check that `F` is continuous, as a uniform limit of continuous functions -/ have : tendsto_uniformly (λn x, f n x) F at_top, { refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _), refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _), rw dist_comm, exact lt_of_le_of_lt (fF_bdd x n) hn }, exact this.continuous (eventually_of_forall $ λ N, (f N).continuous) }, { /- Check that `F` is bounded -/ rcases (f 0).bounded with ⟨C, hC⟩, refine ⟨C + (b 0 + b 0), λ x y, _⟩, calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≤ C + (b 0 + b 0) : by mono* }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim), exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) } end /-- Composition of a bounded continuous function and a continuous function. -/ @[simps { fully_applied := ff }] def comp_continuous {δ : Type*} [topological_space δ] (f : α →ᵇ β) (g : C(δ, α)) : δ →ᵇ β := { to_continuous_map := f.1.comp g, map_bounded' := f.map_bounded'.imp (λ C hC x y, hC _ _) } lemma lipschitz_comp_continuous {δ : Type*} [topological_space δ] (g : C(δ, α)) : lipschitz_with 1 (λ f : α →ᵇ β, f.comp_continuous g) := lipschitz_with.mk_one $ λ f₁ f₂, (dist_le dist_nonneg).2 $ λ x, dist_coe_le_dist (g x) lemma continuous_comp_continuous {δ : Type*} [topological_space δ] (g : C(δ, α)) : continuous (λ f : α →ᵇ β, f.comp_continuous g) := (lipschitz_comp_continuous g).continuous /-- Restrict a bounded continuous function to a set. -/ @[simps apply { fully_applied := ff }] def restrict (f : α →ᵇ β) (s : set α) : s →ᵇ β := f.comp_continuous $ (continuous_map.id _).restrict s /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : β → γ) {C : ℝ≥0} (H : lipschitz_with C G) (f : α →ᵇ β) : α →ᵇ γ := ⟨⟨λx, G (f x), H.continuous.comp f.continuous⟩, let ⟨D, hD⟩ := f.bounded in ⟨max C 0 * D, λ x y, calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _ ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ lemma lipschitz_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) : lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) := lipschitz_with.of_dist_le_mul $ λ f g, (dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x, calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _ ... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2 /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ lemma uniform_continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) : uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).uniform_continuous /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) : continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s := ⟨⟨s.cod_restrict f H, continuous_subtype_mk _ f.continuous⟩, f.bounded⟩ section extend variables {δ : Type*} [topological_space δ] [discrete_topology δ] /-- A version of `function.extend` for bounded continuous maps. We assume that the domain has discrete topology, so we only need to verify boundedness. -/ def extend (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : δ →ᵇ β := { to_fun := extend f g h, continuous_to_fun := continuous_of_discrete_topology, map_bounded' := begin rw [← bounded_range_iff, range_extend f.injective, metric.bounded_union], exact ⟨g.bounded_range, h.bounded_image _⟩ end } @[simp] lemma extend_apply (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) (x : α) : extend f g h (f x) = g x := extend_apply f.injective _ _ _ @[simp] lemma extend_comp (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h ∘ f = g := extend_comp f.injective _ _ lemma extend_apply' {f : α ↪ δ} {x : δ} (hx : x ∉ range f) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h x = h x := extend_apply' _ _ _ hx lemma extend_of_empty [is_empty α] (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h = h := fun_like.coe_injective $ function.extend_of_empty f g h @[simp] lemma dist_extend_extend (f : α ↪ δ) (g₁ g₂ : α →ᵇ β) (h₁ h₂ : δ →ᵇ β) : dist (g₁.extend f h₁) (g₂.extend f h₂) = max (dist g₁ g₂) (dist (h₁.restrict (range f)ᶜ) (h₂.restrict (range f)ᶜ)) := begin refine le_antisymm ((dist_le $ le_max_iff.2 $ or.inl dist_nonneg).2 $ λ x, _) (max_le _ _), { rcases em (∃ y, f y = x) with (⟨x, rfl⟩|hx), { simp only [extend_apply], exact (dist_coe_le_dist x).trans (le_max_left _ _) }, { simp only [extend_apply' hx], lift x to ((range f)ᶜ : set δ) using hx, calc dist (h₁ x) (h₂ x) = dist (h₁.restrict (range f)ᶜ x) (h₂.restrict (range f)ᶜ x) : rfl ... ≤ dist (h₁.restrict (range f)ᶜ) (h₂.restrict (range f)ᶜ) : dist_coe_le_dist x ... ≤ _ : le_max_right _ _ } }, { refine (dist_le dist_nonneg).2 (λ x, _), rw [← extend_apply f g₁ h₁, ← extend_apply f g₂ h₂], exact dist_coe_le_dist _ }, { refine (dist_le dist_nonneg).2 (λ x, _), calc dist (h₁ x) (h₂ x) = dist (extend f g₁ h₁ x) (extend f g₂ h₂ x) : by rw [extend_apply' x.coe_prop, extend_apply' x.coe_prop] ... ≤ _ : dist_coe_le_dist _ } end lemma isometry_extend (f : α ↪ δ) (h : δ →ᵇ β) : isometry (λ g : α →ᵇ β, extend f g h) := isometry_emetric_iff_metric.2 $ λ g₁ g₂, by simp [dist_nonneg] end extend end basics section arzela_ascoli variables [topological_space α] [compact_space α] [pseudo_metric_space β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space β] (A : set (α →ᵇ β)) (closed : is_closed A) (H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : is_compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (λ ε ε0, _), rcases exists_between ε0 with ⟨ε₁, ε₁0, εε₁⟩, let ε₂ := ε₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to ε. This information will be provided by the values of `u` on a sufficiently dense set tα, slightly translated to fit in a finite ε₂-dense set tβ in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to ε, one uses the control on the modulus of continuity to extend the closeness on tα to closeness everywhere. -/ have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0), have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β}, f ∈ A → dist (f y) (f z) < ε₂ := λ x, let ⟨U, nhdsU, hU⟩ := H x _ ε₂0, ⟨V, VU, openV, xV⟩ := _root_.mem_nhds_iff.1 nhdsU in ⟨V, xV, openV, λy hy z hz f hf, hU y (VU hy) z (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most ε₂. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_univ.elim_finite_subcover_image (λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tα, _, ⟨_⟩, htα⟩, /- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/ rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0 with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI, /- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/ /- Associate to every point `y` in the space a nearby point `F y` in tβ -/ choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y), /- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/ /- Associate to every function a discrete approximation, mapping each point in `tα` to a point in `tβ` close to its true image by the function. -/ refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance ε -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁, obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_Union₂.1 (htα (mem_univ x)), calc dist (f x) (g x) ≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = ε₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ hx' _ ((hU x').1) hf }, { exact (hU x').2.2 _ hx' _ ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _), calc dist (f x') (g x') ≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = ε₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ (s : set β) (hs : is_compact s) (A : set (α →ᵇ β)) (closed : is_closed A) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : is_compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s, let F : (α →ᵇ s) → α →ᵇ β := comp coe M, refine compact_of_is_closed_subset ((_ : is_compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _), { haveI : compact_space s := is_compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (λ x ε ε0, bex.imp_right (λ U U_nhds hU y hy z hz f hf, _) (H x ε ε0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < ε : hU y hy z hz (F f) hf }, { let g := cod_restrict s f (λx, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊢, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli [t2_space β] (s : set β) (hs : is_compact s) (A : set (α →ᵇ β)) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : is_compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoli₂ s hs (closure A) is_closed_closure (λ f x hf, (mem_of_closed' hs.is_closed).2 $ λ ε ε0, let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (λ x ε ε0, show ∃ U ∈ 𝓝 x, ∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε, begin refine bex.imp_right (λ U U_set hU y hy z hz f hf, _) (H x (ε/2) (half_pos ε0)), rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < ε/2/2 + ε/2/2 + ε/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y hy z hz g gA) ... = ε : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {α : Type u} [pseudo_metric_space α] (b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (α →ᵇ β)) (H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y)) (x:α) (ε : ℝ) (ε0 : 0 < ε) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε := begin rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩, refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y hy z hz f hf, _⟩, have : dist y z < δ := calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... < δ/2 + δ/2 : add_lt_add hy hz ... = δ : add_halves _, calc dist (f y) (f z) ≤ b (dist y z) : H y z f hf ... ≤ |b (dist y z)| : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < ε : hδ (by simpa [real.dist_eq] using this), end end arzela_ascoli section has_one variables [topological_space α] [pseudo_metric_space β] [has_one β] @[to_additive] instance : has_one (α →ᵇ β) := ⟨const α 1⟩ @[simp, to_additive] lemma coe_one : ((1 : α →ᵇ β) : α → β) = 1 := rfl @[simp, to_additive] lemma mk_of_compact_one [compact_space α] : mk_of_compact (1 : C(α, β)) = 1 := rfl @[to_additive] lemma forall_coe_one_iff_one (f : α →ᵇ β) : (∀ x, f x = 1) ↔ f = 1 := (@fun_like.ext_iff _ _ _ _ f 1).symm @[simp, to_additive] lemma one_comp_continuous [topological_space γ] (f : C(γ, α)) : (1 : α →ᵇ β).comp_continuous f = 1 := rfl end has_one section has_lipschitz_add /- In this section, if `β` is an `add_monoid` whose addition operation is Lipschitz, then we show that the space of bounded continuous functions from `α` to `β` inherits a topological `add_monoid` structure, by using pointwise operations and checking that they are compatible with the uniform distance. Implementation note: The material in this section could have been written for `has_lipschitz_mul` and transported by `@[to_additive]`. We choose not to do this because this causes a few lemma names (for example, `coe_mul`) to conflict with later lemma names for normed rings; this is only a trivial inconvenience, but in any case there are no obvious applications of the multiplicative version. -/ variables [topological_space α] [pseudo_metric_space β] [add_monoid β] variables [has_lipschitz_add β] variables (f g : α →ᵇ β) {x : α} {C : ℝ} /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (α →ᵇ β) := { add := λ f g, bounded_continuous_function.mk_of_bound (f.to_continuous_map + g.to_continuous_map) (↑(has_lipschitz_add.C β) * max (classical.some f.bounded) (classical.some g.bounded)) begin intros x y, refine le_trans (lipschitz_with_lipschitz_const_add ⟨f x, g x⟩ ⟨f y, g y⟩) _, rw prod.dist_eq, refine mul_le_mul_of_nonneg_left _ (has_lipschitz_add.C β).coe_nonneg, apply max_le_max, exact classical.some_spec f.bounded x y, exact classical.some_spec g.bounded x y, end } @[simp] lemma coe_add : ⇑(f + g) = f + g := rfl lemma add_apply : (f + g) x = f x + g x := rfl @[simp] lemma mk_of_compact_add [compact_space α] (f g : C(α, β)) : mk_of_compact (f + g) = mk_of_compact f + mk_of_compact g := rfl lemma add_comp_continuous [topological_space γ] (h : C(γ, α)) : (g + f).comp_continuous h = g.comp_continuous h + f.comp_continuous h := rfl @[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f | 0 := by rw [nsmul_rec, zero_smul, coe_zero] | (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec] instance has_nat_scalar : has_scalar ℕ (α →ᵇ β) := { smul := λ n f, { to_continuous_map := n • f.to_continuous_map, map_bounded' := by simpa [coe_nsmul_rec] using (nsmul_rec n f).map_bounded' } } @[simp] lemma coe_nsmul (r : ℕ) (f : α →ᵇ β) : ⇑(r • f) = r • f := rfl @[simp] lemma nsmul_apply (r : ℕ) (f : α →ᵇ β) (v : α) : (r • f) v = r • f v := rfl instance : add_monoid (α →ᵇ β) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, coe_nsmul _ _) instance : has_lipschitz_add (α →ᵇ β) := { lipschitz_add := ⟨has_lipschitz_add.C β, begin have C_nonneg := (has_lipschitz_add.C β).coe_nonneg, rw lipschitz_with_iff_dist_le_mul, rintros ⟨f₁, g₁⟩ ⟨f₂, g₂⟩, rw dist_le (mul_nonneg C_nonneg dist_nonneg), intros x, refine le_trans (lipschitz_with_lipschitz_const_add ⟨f₁ x, g₁ x⟩ ⟨f₂ x, g₂ x⟩) _, refine mul_le_mul_of_nonneg_left _ C_nonneg, apply max_le_max; exact dist_coe_le_dist x, end⟩ } /-- Coercion of a `normed_group_hom` is an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn` -/ @[simps] def coe_fn_add_hom : (α →ᵇ β) →+ (α → β) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } variables (α β) /-- The additive map forgetting that a bounded continuous function is bounded. -/ @[simps] def to_continuous_map_add_hom : (α →ᵇ β) →+ C(α, β) := { to_fun := to_continuous_map, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, } end has_lipschitz_add section comm_has_lipschitz_add variables [topological_space α] [pseudo_metric_space β] [add_comm_monoid β] [has_lipschitz_add β] @[to_additive] instance : add_comm_monoid (α →ᵇ β) := { add_comm := assume f g, by ext; simp [add_comm], .. bounded_continuous_function.add_monoid } open_locale big_operators @[simp] lemma coe_sum {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) : ⇑(∑ i in s, f i) = (∑ i in s, (f i : α → β)) := (@coe_fn_add_hom α β _ _ _ _).map_sum f s lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) (a : α) : (∑ i in s, f i) a = (∑ i in s, f i a) := by simp end comm_has_lipschitz_add section normed_group /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] [semi_normed_group β] variables (f g : α →ᵇ β) {x : α} {C : ℝ} instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩ lemma norm_def : ∥f∥ = dist f 0 := rfl /-- The norm of a bounded continuous function is the supremum of `∥f x∥`. We use `Inf` to ensure that the definition works if `α` has no elements. -/ lemma norm_eq (f : α →ᵇ β) : ∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} := by simp [norm_def, bounded_continuous_function.dist_eq] /-- When the domain is non-empty, we do not need the `0 ≤ C` condition in the formula for ∥f∥ as an `Inf`. -/ lemma norm_eq_of_nonempty [h : nonempty α] : ∥f∥ = Inf {C : ℝ | ∀ (x : α), ∥f x∥ ≤ C} := begin unfreezingI { obtain ⟨a⟩ := h, }, rw norm_eq, congr, ext, simp only [and_iff_right_iff_imp], exact λ h', le_trans (norm_nonneg (f a)) (h' a), end @[simp] lemma norm_eq_zero_of_empty [h : is_empty α] : ∥f∥ = 0 := dist_zero_of_empty lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc ∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right] ... ≤ ∥f∥ : dist_coe_le_dist _ lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) : dist (f x) (f y) ≤ 2 * C := calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _ ... ≤ C + C : add_le_add (hC x) (hC y) ... = 2 * C : (two_mul _).symm /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ := dist_le_two_norm' f.norm_coe_le_norm x y variable {f} /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C := by simpa using @dist_le _ _ _ _ f 0 _ C0 lemma norm_le_of_nonempty [nonempty α] {f : α →ᵇ β} {M : ℝ} : ∥f∥ ≤ M ↔ ∀ x, ∥f x∥ ≤ M := begin simp_rw [norm_def, ←dist_zero_right], exact dist_le_iff_of_nonempty, end lemma norm_lt_iff_of_compact [compact_space α] {f : α →ᵇ β} {M : ℝ} (M0 : 0 < M) : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M := begin simp_rw [norm_def, ←dist_zero_right], exact dist_lt_iff_of_compact M0, end lemma norm_lt_iff_of_nonempty_compact [nonempty α] [compact_space α] {f : α →ᵇ β} {M : ℝ} : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M := begin simp_rw [norm_def, ←dist_zero_right], exact dist_lt_iff_of_nonempty_compact, end variable (f) /-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty, then it is equal to `∥b∥`. -/ lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ := (norm_le (norm_nonneg b)).2 $ λ x, le_rfl @[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ := le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {α : Type u} {β : Type v} [topological_space α] [semi_normed_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : α →ᵇ β := ⟨⟨λn, f n, Hf⟩, ⟨_, dist_le_two_norm' H⟩⟩ @[simp] lemma coe_of_normed_group {α : Type u} {β : Type v} [topological_space α] [semi_normed_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : (of_normed_group f Hf C H : α → β) = f := rfl lemma norm_of_normed_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_group f hfc C hfC∥ ≤ C := (norm_le hC).2 hfC /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [semi_normed_group β] (f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β := of_normed_group f continuous_of_discrete_topology C H @[simp] lemma coe_of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [semi_normed_group β] (f : α → β) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : (of_normed_group_discrete f C H : α → β) = f := rfl /-- Taking the pointwise norm of a bounded continuous function with values in a `semi_normed_group`, yields a bounded continuous function with values in ℝ. -/ def norm_comp : α →ᵇ ℝ := f.comp norm lipschitz_with_one_norm @[simp] lemma coe_norm_comp : (f.norm_comp : α → ℝ) = norm ∘ f := rfl @[simp] lemma norm_norm_comp : ∥f.norm_comp∥ = ∥f∥ := by simp only [norm_eq, coe_norm_comp, norm_norm] lemma bdd_above_range_norm_comp : bdd_above $ set.range $ norm ∘ f := (real.bounded_iff_bdd_below_bdd_above.mp $ @bounded_range _ _ _ _ f.norm_comp).2 lemma norm_eq_supr_norm : ∥f∥ = ⨆ x : α, ∥f x∥ := by simp_rw [norm_def, dist_eq_supr, coe_zero, pi.zero_apply, dist_zero_right] /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (α →ᵇ β) := ⟨λf, of_normed_group (-f) f.continuous.neg ∥f∥ $ λ x, trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩ /-- The pointwise difference of two bounded continuous functions is again bounded continuous. -/ instance : has_sub (α →ᵇ β) := ⟨λf g, of_normed_group (f - g) (f.continuous.sub g.continuous) (∥f∥ + ∥g∥) $ λ x, by { simp only [sub_eq_add_neg], exact le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) $ trans_rel_right _ (norm_neg _) (g.norm_coe_le_norm x)) }⟩ @[simp] lemma coe_neg : ⇑(-f) = -f := rfl lemma neg_apply : (-f) x = -f x := rfl @[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl lemma sub_apply : (f - g) x = f x - g x := rfl @[simp] lemma mk_of_compact_neg [compact_space α] (f : C(α, β)) : mk_of_compact (-f) = -mk_of_compact f := rfl @[simp] lemma mk_of_compact_sub [compact_space α] (f g : C(α, β)) : mk_of_compact (f - g) = mk_of_compact f - mk_of_compact g := rfl @[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f | (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul] | -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec] instance has_int_scalar : has_scalar ℤ (α →ᵇ β) := { smul := λ n f, { to_continuous_map := n • f.to_continuous_map, map_bounded' := by simpa using (zsmul_rec n f).map_bounded' } } @[simp] lemma coe_zsmul (r : ℤ) (f : α →ᵇ β) : ⇑(r • f) = r • f := rfl @[simp] lemma zsmul_apply (r : ℤ) (f : α →ᵇ β) (v : α) : (r • f) v = r • f v := rfl instance : add_comm_group (α →ᵇ β) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, coe_nsmul _ _) (λ _ _, coe_zsmul _ _) instance : semi_normed_group (α →ᵇ β) := { dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] } instance {α β} [topological_space α] [normed_group β] : normed_group (α →ᵇ β) := { ..bounded_continuous_function.semi_normed_group } lemma nnnorm_def : ∥f∥₊ = nndist f 0 := rfl lemma nnnorm_coe_le_nnnorm (x : α) : ∥f x∥₊ ≤ ∥f∥₊ := norm_coe_le_norm _ _ lemma nndist_le_two_nnnorm (x y : α) : nndist (f x) (f y) ≤ 2 * ∥f∥₊ := dist_le_two_norm _ _ _ /-- The nnnorm of a function is controlled by the supremum of the pointwise nnnorms -/ lemma nnnorm_le (C : ℝ≥0) : ∥f∥₊ ≤ C ↔ ∀x:α, ∥f x∥₊ ≤ C := norm_le C.prop lemma nnnorm_const_le (b : β) : ∥const α b∥₊ ≤ ∥b∥₊ := norm_const_le _ @[simp] lemma nnnorm_const_eq [h : nonempty α] (b : β) : ∥const α b∥₊ = ∥b∥₊ := subtype.ext $ norm_const_eq _ lemma nnnorm_eq_supr_nnnorm : ∥f∥₊ = ⨆ x : α, ∥f x∥₊ := subtype.ext $ (norm_eq_supr_norm f).trans $ by simp_rw [nnreal.coe_supr, coe_nnnorm] lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g := by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x } lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 lemma norm_comp_continuous_le [topological_space γ] (f : α →ᵇ β) (g : C(γ, α)) : ∥f.comp_continuous g∥ ≤ ∥f∥ := ((lipschitz_comp_continuous g).dist_le_mul f 0).trans $ by rw [nnreal.coe_one, one_mul, dist_zero_right] end normed_group section has_bounded_smul /-! ### `has_bounded_smul` (in particular, topological module) structure In this section, if `β` is a metric space and a `𝕜`-module whose addition and scalar multiplication are compatible with the metric structure, then we show that the space of bounded continuous functions from `α` to `β` inherits a so-called `has_bounded_smul` structure (in particular, a `has_continuous_mul` structure, which is the mathlib formulation of being a topological module), by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [pseudo_metric_space 𝕜] [topological_space α] [pseudo_metric_space β] section has_scalar variables [has_zero 𝕜] [has_zero β] [has_scalar 𝕜 β] [has_bounded_smul 𝕜 β] instance : has_scalar 𝕜 (α →ᵇ β) := { smul := λ c f, { to_continuous_map := c • f.to_continuous_map, map_bounded' := let ⟨b, hb⟩ := f.bounded in ⟨dist c 0 * b, λ x y, begin refine (dist_smul_pair c (f x) (f y)).trans _, refine mul_le_mul_of_nonneg_left _ dist_nonneg, exact hb x y end⟩ } } @[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl instance [has_scalar 𝕜ᵐᵒᵖ β] [is_central_scalar 𝕜 β] : is_central_scalar 𝕜 (α →ᵇ β) := { op_smul_eq_smul := λ _ _, ext $ λ _, op_smul_eq_smul _ _ } instance : has_bounded_smul 𝕜 (α →ᵇ β) := { dist_smul_pair' := λ c f₁ f₂, begin rw dist_le (mul_nonneg dist_nonneg dist_nonneg), intros x, refine (dist_smul_pair c (f₁ x) (f₂ x)).trans _, exact mul_le_mul_of_nonneg_left (dist_coe_le_dist x) dist_nonneg end, dist_pair_smul' := λ c₁ c₂ f, begin rw dist_le (mul_nonneg dist_nonneg dist_nonneg), intros x, refine (dist_pair_smul c₁ c₂ (f x)).trans _, convert mul_le_mul_of_nonneg_left (dist_coe_le_dist x) dist_nonneg, simp end } end has_scalar section mul_action variables [monoid_with_zero 𝕜] [has_zero β] [mul_action 𝕜 β] [has_bounded_smul 𝕜 β] instance : mul_action 𝕜 (α →ᵇ β) := fun_like.coe_injective.mul_action _ coe_smul end mul_action section distrib_mul_action variables [monoid_with_zero 𝕜] [add_monoid β] [distrib_mul_action 𝕜 β] [has_bounded_smul 𝕜 β] variables [has_lipschitz_add β] instance : distrib_mul_action 𝕜 (α →ᵇ β) := function.injective.distrib_mul_action ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul end distrib_mul_action section module variables [semiring 𝕜] [add_comm_monoid β] [module 𝕜 β] [has_bounded_smul 𝕜 β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} variables [has_lipschitz_add β] instance : module 𝕜 (α →ᵇ β) := function.injective.module _ ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul variables (𝕜) /-- The evaluation at a point, as a continuous linear map from `α →ᵇ β` to `β`. -/ def eval_clm (x : α) : (α →ᵇ β) →L[𝕜] β := { to_fun := λ f, f x, map_add' := λ f g, add_apply _ _, map_smul' := λ c f, smul_apply _ _ _ } @[simp] lemma eval_clm_apply (x : α) (f : α →ᵇ β) : eval_clm 𝕜 x f = f x := rfl variables (α β) /-- The linear map forgetting that a bounded continuous function is bounded. -/ @[simps] def to_continuous_map_linear_map : (α →ᵇ β) →ₗ[𝕜] C(α, β) := { to_fun := to_continuous_map, map_smul' := λ f g, rfl, map_add' := λ c f, rfl } end module end has_bounded_smul section normed_space /-! ### Normed space structure In this section, if `β` is a normed space, then we show that the space of bounded continuous functions from `α` to `β` inherits a normed space structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} variables [topological_space α] [semi_normed_group β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance [normed_field 𝕜] [normed_space 𝕜 β] : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, begin refine norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, exact (λ x, trans_rel_right _ (norm_smul _ _) (mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))) end⟩ variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 β] variables [semi_normed_group γ] [normed_space 𝕜 γ] variables (α) -- TODO does this work in the `has_bounded_smul` setting, too? /-- Postcomposition of bounded continuous functions into a normed module by a continuous linear map is a continuous linear map. Upgraded version of `continuous_linear_map.comp_left_continuous`, similar to `linear_map.comp_left`. -/ protected def _root_.continuous_linear_map.comp_left_continuous_bounded (g : β →L[𝕜] γ) : (α →ᵇ β) →L[𝕜] (α →ᵇ γ) := linear_map.mk_continuous { to_fun := λ f, of_normed_group (g ∘ f) (g.continuous.comp f.continuous) (∥g∥ * ∥f∥) (λ x, (g.le_op_norm_of_le (f.norm_coe_le_norm x))), map_add' := λ f g, by ext; simp, map_smul' := λ c f, by ext; simp } ∥g∥ (λ f, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg g) (norm_nonneg f)) _) @[simp] lemma _root_.continuous_linear_map.comp_left_continuous_bounded_apply (g : β →L[𝕜] γ) (f : α →ᵇ β) (x : α) : (g.comp_left_continuous_bounded α f) x = g (f x) := rfl end normed_space section normed_ring /-! ### Normed ring structure In this section, if `R` is a normed ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] {R : Type*} section non_unital section semi_normed variables [non_unital_semi_normed_ring R] instance : has_mul (α →ᵇ R) := { mul := λ f g, of_normed_group (f * g) (f.continuous.mul g.continuous) (∥f∥ * ∥g∥) $ λ x, le_trans (norm_mul_le (f x) (g x)) $ mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _) } @[simp] lemma coe_mul (f g : α →ᵇ R) : ⇑(f * g) = f * g := rfl lemma mul_apply (f g : α →ᵇ R) (x : α) : (f * g) x = f x * g x := rfl instance : non_unital_ring (α →ᵇ R) := fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, coe_nsmul _ _) (λ _ _, coe_zsmul _ _) instance : non_unital_semi_normed_ring (α →ᵇ R) := { norm_mul := λ f g, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, .. bounded_continuous_function.semi_normed_group } end semi_normed instance [non_unital_normed_ring R] : non_unital_normed_ring (α →ᵇ R) := { .. bounded_continuous_function.non_unital_semi_normed_ring, .. bounded_continuous_function.normed_group } end non_unital section semi_normed variables [semi_normed_ring R] @[simp] lemma coe_npow_rec (f : α →ᵇ R) : ∀ n, ⇑(npow_rec n f) = f ^ n | 0 := by rw [npow_rec, pow_zero, coe_one] | (n + 1) := by rw [npow_rec, pow_succ, coe_mul, coe_npow_rec] instance has_nat_pow : has_pow (α →ᵇ R) ℕ := { pow := λ f n, { to_continuous_map := f.to_continuous_map ^ n, map_bounded' := by simpa [coe_npow_rec] using (npow_rec n f).map_bounded' } } @[simp] lemma coe_pow (n : ℕ) (f : α →ᵇ R) : ⇑(f ^ n) = f ^ n := rfl @[simp] lemma pow_apply (n : ℕ) (f : α →ᵇ R) (v : α) : (f ^ n) v = f v ^ n := rfl instance : ring (α →ᵇ R) := fun_like.coe_injective.ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub (λ _ _, coe_nsmul _ _) (λ _ _, coe_zsmul _ _) (λ _ _, coe_pow _ _) instance : semi_normed_ring (α →ᵇ R) := { ..bounded_continuous_function.non_unital_semi_normed_ring } end semi_normed instance [normed_ring R] : normed_ring (α →ᵇ R) := { ..bounded_continuous_function.non_unital_normed_ring } end normed_ring section normed_comm_ring /-! ### Normed commutative ring structure In this section, if `R` is a normed commutative ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed commutative ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] {R : Type*} instance [semi_normed_comm_ring R] : comm_ring (α →ᵇ R) := { mul_comm := λ f₁ f₂, ext $ λ x, mul_comm _ _, .. bounded_continuous_function.ring } instance [semi_normed_comm_ring R] : semi_normed_comm_ring (α →ᵇ R) := { .. bounded_continuous_function.comm_ring, .. bounded_continuous_function.semi_normed_group } instance [normed_comm_ring R] : normed_comm_ring (α →ᵇ R) := { .. bounded_continuous_function.comm_ring, .. bounded_continuous_function.normed_group } end normed_comm_ring section normed_algebra /-! ### Normed algebra structure In this section, if `γ` is a normed algebra, then we show that the space of bounded continuous functions from `α` to `γ` inherits a normed algebra structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [semi_normed_group β] [normed_space 𝕜 β] variables [normed_ring γ] [normed_algebra 𝕜 γ] variables {f g : α →ᵇ γ} {x : α} {c : 𝕜} /-- `bounded_continuous_function.const` as a `ring_hom`. -/ def C : 𝕜 →+* (α →ᵇ γ) := { to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c), map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one, map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _, map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero, map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ } instance : algebra 𝕜 (α →ᵇ γ) := { to_ring_hom := C, commutes' := λ c f, ext $ λ x, algebra.commutes' _ _, smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _, ..bounded_continuous_function.module, ..bounded_continuous_function.ring } @[simp] lemma algebra_map_apply (k : 𝕜) (a : α) : algebra_map 𝕜 (α →ᵇ γ) k a = k • 1 := by { rw algebra.algebra_map_eq_smul_one, refl, } instance : normed_algebra 𝕜 (α →ᵇ γ) := { ..bounded_continuous_function.normed_space } /-! ### Structure as normed module over scalar functions If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous functions from `α` to `β` is naturally a module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ instance has_scalar' : has_scalar (α →ᵇ 𝕜) (α →ᵇ β) := ⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_group (λ x, (f x) • (g x)) (f.continuous.smul g.continuous) (∥f∥ * ∥g∥) (λ x, calc ∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _ ... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _) (norm_nonneg _)) ⟩ instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) := module.of_core $ { smul := (•), smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _, add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ := norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ /- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts show that the space of bounded continuous functions from `α` to `β` is naturally a normed module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ end normed_algebra lemma nnreal.upper_bound {α : Type*} [topological_space α] (f : α →ᵇ ℝ≥0) (x : α) : f x ≤ nndist f 0 := begin have key : nndist (f x) ((0 : α →ᵇ ℝ≥0) x) ≤ nndist f 0, { exact @dist_coe_le_dist α ℝ≥0 _ _ f 0 x, }, simp only [coe_zero, pi.zero_apply] at key, rwa nnreal.nndist_zero_eq_val' (f x) at key, end /-! ### Star structures In this section, if `β` is a normed ⋆-group, then so is the space of bounded continuous functions from `α` to `β`, by using the star operation pointwise. If `𝕜` is normed field and a ⋆-ring over which `β` is a normed algebra and a star module, then the space of bounded continuous functions from `α` to `β` is a star module. If `β` is a ⋆-ring in addition to being a normed ⋆-group, then `α →ᵇ β` inherits a ⋆-ring structure. In summary, if `β` is a C⋆-algebra over `𝕜`, then so is `α →ᵇ β`; note that completeness is guaranteed when `β` is complete (see `bounded_continuous_function.complete`). -/ section normed_group variables {𝕜 : Type*} [normed_field 𝕜] [star_ring 𝕜] variables [topological_space α] [semi_normed_group β] [star_add_monoid β] [normed_star_group β] variables [normed_space 𝕜 β] [star_module 𝕜 β] instance : star_add_monoid (α →ᵇ β) := { star := λ f, f.comp star star_normed_group_hom.lipschitz, star_involutive := λ f, ext $ λ x, star_star (f x), star_add := λ f g, ext $ λ x, star_add (f x) (g x) } /-- The right-hand side of this equality can be parsed `star ∘ ⇑f` because of the instance `pi.has_star`. Upon inspecting the goal, one sees `⊢ ⇑(star f) = star ⇑f`.-/ @[simp] lemma coe_star (f : α →ᵇ β) : ⇑(star f) = star f := rfl @[simp] lemma star_apply (f : α →ᵇ β) (x : α) : star f x = star (f x) := rfl instance : normed_star_group (α →ᵇ β) := { norm_star := λ f, by simp only [norm_eq, star_apply, norm_star] } instance : star_module 𝕜 (α →ᵇ β) := { star_smul := λ k f, ext $ λ x, star_smul k (f x) } end normed_group section cstar_ring variables [topological_space α] variables [non_unital_normed_ring β] [star_ring β] instance [normed_star_group β] : star_ring (α →ᵇ β) := { star_mul := λ f g, ext $ λ x, star_mul (f x) (g x), ..bounded_continuous_function.star_add_monoid } variable [cstar_ring β] instance : cstar_ring (α →ᵇ β) := { norm_star_mul_self := begin intro f, refine le_antisymm _ _, { rw [←sq, norm_le (sq_nonneg _)], dsimp [star_apply], intro x, rw [cstar_ring.norm_star_mul_self, ←sq], refine sq_le_sq' _ _, { linarith [norm_nonneg (f x), norm_nonneg f] }, { exact norm_coe_le_norm f x }, }, { rw [←sq, ←real.le_sqrt (norm_nonneg _) (norm_nonneg _), norm_le (real.sqrt_nonneg _)], intro x, rw [real.le_sqrt (norm_nonneg _) (norm_nonneg _), sq, ←cstar_ring.norm_star_mul_self], exact norm_coe_le_norm (star f * f) x } end } end cstar_ring section normed_lattice_ordered_group variables [topological_space α] [normed_lattice_add_comm_group β] instance : partial_order (α →ᵇ β) := partial_order.lift (λ f, f.to_fun) (by tidy) /-- Continuous normed lattice group valued functions form a meet-semilattice -/ instance : semilattice_inf (α →ᵇ β) := { inf := λ f g, { to_fun := λ t, f t ⊓ g t, continuous_to_fun := f.continuous.inf g.continuous, map_bounded' := begin obtain ⟨C₁, hf⟩ := f.bounded, obtain ⟨C₂, hg⟩ := g.bounded, refine ⟨C₁ + C₂, λ x y, _⟩, simp_rw normed_group.dist_eq at hf hg ⊢, exact (norm_inf_sub_inf_le_add_norm _ _ _ _).trans (add_le_add (hf _ _) (hg _ _)), end }, inf_le_left := λ f g, continuous_map.le_def.mpr (λ _, inf_le_left), inf_le_right := λ f g, continuous_map.le_def.mpr (λ _, inf_le_right), le_inf := λ f g₁ g₂ w₁ w₂, continuous_map.le_def.mpr (λ _, le_inf (continuous_map.le_def.mp w₁ _) (continuous_map.le_def.mp w₂ _)), ..bounded_continuous_function.partial_order } instance : semilattice_sup (α →ᵇ β) := { sup := λ f g, { to_fun := λ t, f t ⊔ g t, continuous_to_fun := f.continuous.sup g.continuous, map_bounded' := begin obtain ⟨C₁, hf⟩ := f.bounded, obtain ⟨C₂, hg⟩ := g.bounded, refine ⟨C₁ + C₂, λ x y, _⟩, simp_rw normed_group.dist_eq at hf hg ⊢, exact (norm_sup_sub_sup_le_add_norm _ _ _ _).trans (add_le_add (hf _ _) (hg _ _)), end }, le_sup_left := λ f g, continuous_map.le_def.mpr (λ _, le_sup_left), le_sup_right := λ f g, continuous_map.le_def.mpr (λ _, le_sup_right), sup_le := λ f g₁ g₂ w₁ w₂, continuous_map.le_def.mpr (λ _, sup_le (continuous_map.le_def.mp w₁ _) (continuous_map.le_def.mp w₂ _)), ..bounded_continuous_function.partial_order } instance : lattice (α →ᵇ β) := { .. bounded_continuous_function.semilattice_sup, .. bounded_continuous_function.semilattice_inf } @[simp] lemma coe_fn_sup (f g : α →ᵇ β) : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma coe_fn_abs (f : α →ᵇ β) : ⇑|f| = |f| := rfl instance : normed_lattice_add_comm_group (α →ᵇ β) := { add_le_add_left := begin intros f g h₁ h t, simp only [coe_to_continuous_fun, pi.add_apply, add_le_add_iff_left, coe_add, continuous_map.to_fun_eq_coe], exact h₁ _, end, solid := begin intros f g h, have i1: ∀ t, ∥f t∥ ≤ ∥g t∥ := λ t, solid (h t), rw norm_le (norm_nonneg _), exact λ t, (i1 t).trans (norm_coe_le_norm g t), end, ..bounded_continuous_function.lattice, } end normed_lattice_ordered_group end bounded_continuous_function
436fd0feac342366e04222f6db6284af3ad94f7d
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/homotopy/sphere.hlean
94d4de7d27f79700e1fdecf48632f74cf2064b92
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
13,723
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the n-spheres -/ import .susp types.trunc open eq nat susp bool is_trunc unit pointed algebra /- We can define spheres with the following possible indices: - trunc_index (defining S^-2 = S^-1 = empty) - nat (forgetting that S^-1 = empty) - nat, but counting wrong (S^0 = empty, S^1 = bool, ...) - some new type "integers >= -1" We choose the last option here. -/ /- Sphere levels -/ inductive sphere_index : Type₀ := | minus_one : sphere_index | succ : sphere_index → sphere_index notation `ℕ₋₁` := sphere_index namespace trunc_index definition sub_one [reducible] (n : ℕ₋₁) : ℕ₋₂ := sphere_index.rec_on n -2 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_sphere_index [reducible] (n : ℕ₋₁) : ℕ₋₂ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) end trunc_index namespace sphere_index /- notation for sphere_index is -1, 0, 1, ... from 0 and up this comes from a coercion from num to sphere_index (via nat) -/ postfix `.+1`:(max+1) := sphere_index.succ postfix `.+2`:(max+1) := λ(n : sphere_index), (n .+1 .+1) notation `-1` := minus_one definition has_zero_sphere_index [instance] : has_zero ℕ₋₁ := has_zero.mk (succ minus_one) definition has_one_sphere_index [instance] : has_one ℕ₋₁ := has_one.mk (succ (succ minus_one)) definition add_plus_one (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.rec_on m n (λ k l, l .+1) -- addition of sphere_indices, where (-1 + -1) is defined to be -1. protected definition add (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.cases_on m (sphere_index.cases_on n -1 id) (sphere_index.rec n (λn' r, succ r)) inductive le (a : ℕ₋₁) : ℕ₋₁ → Type := | sp_refl : le a a | step : Π {b}, le a b → le a (b.+1) infix ` +1+ `:65 := sphere_index.add_plus_one definition has_add_sphere_index [instance] [priority 2000] [reducible] : has_add ℕ₋₁ := has_add.mk sphere_index.add definition has_le_sphere_index [instance] : has_le ℕ₋₁ := has_le.mk sphere_index.le definition sub_one [reducible] (n : ℕ) : ℕ₋₁ := nat.rec_on n -1 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_nat [coercion] [reducible] (n : ℕ) : ℕ₋₁ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) definition add_one [reducible] (n : ℕ₋₁) : ℕ := sphere_index.rec_on n 0 (λ n k, nat.succ k) definition add_plus_one_of_nat (n m : ℕ) : (n +1+ m) = sphere_index.of_nat (n + m + 1) := begin induction m with m IH, { reflexivity }, { exact ap succ IH} end definition succ_sub_one (n : ℕ) : (nat.succ n)..-1 = n :> ℕ₋₁ := idp definition add_sub_one (n m : ℕ) : (n + m)..-1 = n..-1 +1+ m..-1 :> ℕ₋₁ := begin induction m with m IH, { reflexivity }, { exact ap succ IH } end definition succ_le_succ {n m : ℕ₋₁} (H : n ≤ m) : n.+1 ≤[ℕ₋₁] m.+1 := by induction H with m H IH; apply le.sp_refl; exact le.step IH definition minus_one_le (n : ℕ₋₁) : -1 ≤[ℕ₋₁] n := by induction n with n IH; apply le.sp_refl; exact le.step IH open decidable protected definition has_decidable_eq [instance] : Π(n m : ℕ₋₁), decidable (n = m) | has_decidable_eq -1 -1 := inl rfl | has_decidable_eq (n.+1) -1 := inr (by contradiction) | has_decidable_eq -1 (m.+1) := inr (by contradiction) | has_decidable_eq (n.+1) (m.+1) := match has_decidable_eq n m with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ n = succ m, by injection h with xeqy; exact absurd xeqy xney) end definition not_succ_le_minus_two {n : sphere_index} (H : n .+1 ≤[ℕ₋₁] -1) : empty := by cases H protected definition le_trans {n m k : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] k) : n ≤[ℕ₋₁] k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end definition le_of_succ_le_succ {n m : ℕ₋₁} (H : n.+1 ≤[ℕ₋₁] m.+1) : n ≤[ℕ₋₁] m := begin cases H with m H', { apply le.sp_refl}, { exact sphere_index.le_trans (le.step !le.sp_refl) H'} end theorem not_succ_le_self {n : ℕ₋₁} : ¬n.+1 ≤[ℕ₋₁] n := begin induction n with n IH: intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end protected definition le_antisymm {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] n) : n = m := begin induction H2 with n H2 IH, { reflexivity}, { exfalso, apply @not_succ_le_self n, exact sphere_index.le_trans H1 H2} end protected definition le_succ {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m): n ≤[ℕ₋₁] m.+1 := le.step H1 definition add_plus_one_minus_one (n : ℕ₋₁) : n +1+ -1 = n := idp definition add_plus_one_succ (n m : ℕ₋₁) : n +1+ (m.+1) = (n +1+ m).+1 := idp definition minus_one_add_plus_one (n : ℕ₋₁) : -1 +1+ n = n := begin induction n with n IH, reflexivity, exact ap succ IH end definition succ_add_plus_one (n m : ℕ₋₁) : (n.+1) +1+ m = (n +1+ m).+1 := begin induction m with m IH, reflexivity, exact ap succ IH end definition sphere_index_of_nat_add_one (n : ℕ₋₁) : sphere_index.of_nat (add_one n) = n.+1 := begin induction n with n IH, reflexivity, exact ap succ IH end definition add_one_succ (n : ℕ₋₁) : add_one (n.+1) = succ (add_one n) := by reflexivity definition add_one_sub_one (n : ℕ) : add_one (n..-1) = n := begin induction n with n IH, reflexivity, exact ap nat.succ IH end definition add_one_of_nat (n : ℕ) : add_one n = nat.succ n := ap nat.succ (add_one_sub_one n) definition sphere_index.of_nat_succ (n : ℕ) : sphere_index.of_nat (nat.succ n) = (sphere_index.of_nat n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end /- warning: if this coercion is available, the coercion ℕ → ℕ₋₂ is the composition of the coercions ℕ → ℕ₋₁ → ℕ₋₂. We don't want this composition as coercion, because it has worse computational properties. You can rewrite it with trans_to_of_sphere_index_eq defined below. -/ attribute trunc_index.of_sphere_index [coercion] end sphere_index open sphere_index definition weak_order_sphere_index [trans_instance] [reducible] : weak_order sphere_index := weak_order.mk le sphere_index.le.sp_refl @sphere_index.le_trans @sphere_index.le_antisymm namespace trunc_index definition sub_two_eq_sub_one_sub_one (n : ℕ) : n.-2 = n..-1..-1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition of_nat_sub_one (n : ℕ) : (sphere_index.of_nat n)..-1 = (trunc_index.sub_two n).+1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition sub_one_of_sphere_index (n : ℕ) : of_sphere_index n..-1 = (trunc_index.sub_two n).+1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition succ_sub_one (n : ℕ₋₁) : n.+1..-1 = n :> ℕ₋₂ := idp definition of_sphere_index_of_nat (n : ℕ) : of_sphere_index (sphere_index.of_nat n) = of_nat n :> ℕ₋₂ := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition trans_to_of_sphere_index_eq (n : ℕ) : trunc_index._trans_to_of_sphere_index n = of_nat n :> ℕ₋₂ := of_sphere_index_of_nat n definition trunc_index_of_nat_add_one (n : ℕ₋₁) : trunc_index.of_nat (add_one n) = (of_sphere_index n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end definition of_sphere_index_succ (n : ℕ₋₁) : of_sphere_index (n.+1) = (of_sphere_index n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end end trunc_index open sphere_index equiv definition sphere (n : ℕ₋₁) : Type₀ := iterate_susp (add_one n) empty namespace sphere export [notation] sphere_index definition base {n : ℕ} : sphere n := north definition pointed_sphere [instance] [constructor] (n : ℕ) : pointed (sphere n) := pointed.mk base definition psphere [constructor] (n : ℕ) : Type* := pointed.mk' (sphere n) namespace ops abbreviation S := sphere notation `S*` := psphere end ops open sphere.ops definition sphere_minus_one : S -1 = empty := idp definition sphere_succ [unfold_full] (n : ℕ₋₁) : S n.+1 = susp (S n) := idp definition psphere_succ [unfold_full] (n : ℕ) : S* (n + 1) = psusp (S* n) := idp definition psphere_eq_iterate_susp (n : ℕ) : S* n = pointed.MK (iterate_susp (succ n) empty) !north := begin esimp, apply ap (λx, pointed.MK (susp x) (@north x)); apply ap (λx, iterate_susp x empty), apply add_one_sub_one end definition equator [constructor] (n : ℕ) : S* n →* Ω (S* (succ n)) := loop_psusp_unit (S* n) definition surf {n : ℕ} : Ω[n] (S* n) := begin induction n with n s, { exact south }, { exact (loopn_succ_in (S* (succ n)) n)⁻¹ᵉ* (apn n (equator n) s) } end definition bool_of_sphere [unfold 1] : S 0 → bool := proof susp.rec ff tt (λx, empty.elim x) qed definition sphere_of_bool [unfold 1] : bool → S 0 | ff := proof north qed | tt := proof south qed definition sphere_equiv_bool [constructor] : S 0 ≃ bool := equiv.MK bool_of_sphere sphere_of_bool (λb, match b with | tt := idp | ff := idp end) (λx, proof susp.rec_on x idp idp (empty.rec _) qed) definition psphere_pequiv_pbool [constructor] : S* 0 ≃* pbool := pequiv_of_equiv sphere_equiv_bool idp definition sphere_eq_bool : S 0 = bool := ua sphere_equiv_bool definition sphere_eq_pbool : S* 0 = pbool := pType_eq sphere_equiv_bool idp definition psphere_pmap_pequiv' (A : Type*) (n : ℕ) : ppmap (S* n) A ≃* Ω[n] A := begin revert A, induction n with n IH: intro A, { refine _ ⬝e* !pmap_pbool_pequiv, exact pequiv_ppcompose_right psphere_pequiv_pbool⁻¹ᵉ* }, { refine psusp_adjoint_loop (S* n) A ⬝e* IH (Ω A) ⬝e* !loopn_succ_in⁻¹ᵉ* } end definition psphere_pmap_pequiv (A : Type*) (n : ℕ) : ppmap (S* n) A ≃* Ω[n] A := begin fapply pequiv_change_fun, { exact psphere_pmap_pequiv' A n }, { exact papn_fun A surf }, { revert A, induction n with n IH: intro A, { reflexivity }, { intro f, refine ap !loopn_succ_in⁻¹ᵉ* (IH (Ω A) _ ⬝ !apn_pcompose _) ⬝ _, exact !loopn_succ_in_inv_natural⁻¹* _ }} end protected definition elim {n : ℕ} {P : Type*} (p : Ω[n] P) : S* n →* P := !psphere_pmap_pequiv⁻¹ᵉ* p -- definition elim_surf {n : ℕ} {P : Type*} (p : Ω[n] P) : apn n (sphere.elim p) surf = p := -- begin -- induction n with n IH, -- { esimp [apn,surf,sphere.elim,psphere_pmap_equiv], apply sorry}, -- { apply sorry} -- end end sphere namespace sphere open is_conn trunc_index sphere_index sphere.ops -- Corollary 8.2.2 theorem is_conn_sphere [instance] (n : ℕ₋₁) : is_conn (n..-1) (S n) := begin induction n with n IH, { apply is_conn_minus_two }, { rewrite [trunc_index.succ_sub_one n, sphere.sphere_succ], apply is_conn_susp } end theorem is_conn_psphere [instance] (n : ℕ) : is_conn (n.-1) (S* n) := transport (λx, is_conn x (sphere n)) (of_nat_sub_one n) (is_conn_sphere n) end sphere open sphere sphere.ops namespace is_trunc open trunc_index variables {n : ℕ} {A : Type} definition is_trunc_of_psphere_pmap_equiv_constant (H : Π(a : A) (f : S* n →* pointed.Mk a) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply iff.elim_right !is_trunc_iff_is_contr_loop, intro a, apply is_trunc_equiv_closed, exact !psphere_pmap_pequiv, fapply is_contr.mk, { exact pmap.mk (λx, a) idp}, { intro f, fapply pmap_eq, { intro x, esimp, refine !respect_pt⁻¹ ⬝ (!H ⬝ !H⁻¹)}, { rewrite [▸*,con.right_inv,▸*,con.left_inv]}} end definition is_trunc_iff_map_sphere_constant (H : Π(f : S n → A) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply is_trunc_of_psphere_pmap_equiv_constant, intros, cases f with f p, esimp at *, apply H end definition psphere_pmap_equiv_constant_of_is_trunc' [H : is_trunc (n.-2.+1) A] (a : A) (f : S* n →* pointed.Mk a) (x : S n) : f x = f base := begin let H' := iff.elim_left (is_trunc_iff_is_contr_loop n A) H a, note H'' := @is_trunc_equiv_closed_rev _ _ _ !psphere_pmap_pequiv H', esimp at H'', have p : f = pmap.mk (λx, f base) (respect_pt f), by apply is_prop.elim, exact ap10 (ap pmap.to_fun p) x end definition psphere_pmap_equiv_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (a : A) (f : S* n →* pointed.Mk a) (x y : S n) : f x = f y := let H := psphere_pmap_equiv_constant_of_is_trunc' a f in !H ⬝ !H⁻¹ definition map_sphere_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (f : S n → A) (x y : S n) : f x = f y := psphere_pmap_equiv_constant_of_is_trunc (f base) (pmap.mk f idp) x y definition map_sphere_constant_of_is_trunc_self [H : is_trunc (n.-2.+1) A] (f : S n → A) (x : S n) : map_sphere_constant_of_is_trunc f x x = idp := !con.right_inv end is_trunc
aba11c3a072596724ac6e7be97fb525e5a700e77
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/matchtac.lean
ca3ed4f0f9e00cb2a43b1143eae084162f758922
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
3,347
lean
theorem tst1 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match (generalizing := false) h:xs with | [] => exact h₂ h | z::zs => apply h₁ z zs; assumption theorem tst1' {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match xs with | [] => exact h₂ rfl | z::zs => exact h₁ z zs rfl theorem tst2 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match (generalizing := false) h:xs with | [] => ?nilCase | z::zs => ?consCase; case consCase => exact h₁ z zs h; case nilCase => exact h₂ h def tst3 {α β γ : Type} (h : α × β × γ) : β × α × γ := by { match h with | (a, b, c) => exact (b, a, c) } theorem tst4 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by match (generalizing := false) h:xs with | [] => _ | z::zs => _ case match_2 => exact h₁ z zs h exact h₂ h theorem tst5 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => ?c1 | Or.inr (Or.inr h) => ?c2 case c2 => apply Or.inl assumption case c1 => apply Or.inr apply Or.inl assumption theorem tst6 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => ?c1 | Or.inr (Or.inr h) => apply Or.inl assumption case c1 => apply Or.inr; apply Or.inl; assumption theorem tst7 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => apply Or.inr; apply Or.inl; assumption | Or.inr (Or.inr h) => apply Or.inl; assumption inductive ListLast.{u} {α : Type u} : List α → Type u | empty : ListLast [] | nonEmpty : (as : List α) → (a : α) → ListLast (as ++ [a]) axiom last {α} (xs : List α) : ListLast xs axiom back {α} [Inhabited α] (xs : List α) : α axiom popBack {α} : List α → List α axiom backEq {α} [Inhabited α] : (xs : List α) → (x : α) → back (xs ++ [x]) = x axiom popBackEq {α} : (xs : List α) → (x : α) → popBack (xs ++ [x]) = xs theorem tst8 {α} [Inhabited α] (xs : List α) : xs ≠ [] → xs = popBack xs ++ [back xs] := match (generalizing := false) xs, h:last xs with | _, ListLast.empty => fun h => absurd rfl h | _, ListLast.nonEmpty ys y => fun _ => sorry theorem tst9 {α} [Inhabited α] (xs : List α) : xs ≠ [] → xs = popBack xs ++ [back xs] := by match (generalizing := false) xs, h:last xs with | _, ListLast.empty => intro h; exact absurd rfl h | _, ListLast.nonEmpty ys y => intro; rw [popBackEq, backEq] theorem tst8' {α} [Inhabited α] (xs : List α) : xs ≠ [] → xs = popBack xs ++ [back xs] := match xs, last xs with | _, ListLast.empty => fun h => absurd rfl h | _, ListLast.nonEmpty ys y => fun _ => sorry theorem tst8'' {α} [Inhabited α] (xs : List α) (h : xs ≠ []) : xs = popBack xs ++ [back xs] := match xs, last xs with | _, ListLast.empty => absurd rfl h | _, ListLast.nonEmpty ys y => sorry
6f9baec3ff1a372a7535f6835299454c0858514a
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/subgroup.lean
b3e489115a99cc7adcad084a84c4d27e2ab2cecc
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
64,443
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import algebra.group.conj import algebra.pointwise import order.atoms /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` * `is_simple_group G` : a class indicating that a group has exactly two normal subgroups ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : set_like (subgroup G) G := ⟨subgroup.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp, to_additive] lemma mem_carrier {s : subgroup G} {x : G} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance (K : subgroup G) [d : decidable_pred (∈ K)] [fintype G] : fintype K := show fintype {g : G // g ∈ K}, from infer_instance end subgroup namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := set_like.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[simp, to_additive] theorem inv_coe_set : (H : set G)⁻¹ = H := by { ext, simp, } @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := subtype.coe_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := subtype.coe_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of an `ordered_comm_group` is an `ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_ordered_comm_group` is an `add_ordered_comm_group`."] instance to_ordered_comm_group {G : Type*} [ordered_comm_group G] (H : subgroup G) : ordered_comm_group H := subtype.coe_injective.ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of a `linear_ordered_comm_group` is a `linear_ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`."] instance to_linear_ordered_comm_group {G : Type*} [linear_ordered_comm_group G] (H : subgroup G) : linear_ordered_comm_group H := subtype.coe_injective.linear_ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ /-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/ @[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."] def inclusion {H K : subgroup G} (h : H ≤ K) : H →* K := monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl) @[simp, to_additive] lemma coe_inclusion {H K : subgroup G} {h : H ≤ K} (a : H) : (inclusion h a : G) = a := by { cases a, simp only [inclusion, coe_mk, monoid_hom.coe_mk'] } @[simp, to_additive] lemma subtype_comp_inclusion {H K : subgroup G} (hH : H ≤ K) : K.subtype.comp (inclusion hH) = H.subtype := by { ext, simp } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin rw set_like.ext'_iff, simp only [coe_bot, set.eq_singleton_iff_unique_mem, set_like.mem_coe, H.one_mem, true_and], end @[to_additive] lemma eq_bot_of_subsingleton [subsingleton H] : H = ⊥ := begin rw subgroup.eq_bot_iff_forall, intros y hy, rw [← subgroup.coe_mk H y hy, subsingleton.elim (⟨y, hy⟩ : H) 1, subgroup.coe_one], end @[to_additive] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1}, by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩ @[simp] lemma _root_.add_subgroup.card_bot : fintype.card (⊥ : add_subgroup A) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(0 : A), set.mem_singleton 0⟩, λ ⟨y, hy⟩, subtype.eq $ add_subgroup.mem_bot.1 hy⟩ -- `@[to_additive]` doesn't work, because it converts the `1 : ℕ` to `0`. @[simp] lemma card_bot : fintype.card (⊥ : subgroup G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩ @[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin haveI : fintype (H : set G) := ‹fintype H›, rw [set_like.ext'_iff, coe_top, ← finset.coe_univ, ← (H : set G).coe_to_finset, finset.coe_inj, ← finset.card_eq_iff_eq_univ, ← h, set.to_finset_card], congr end @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := subtype.nontrivial_iff_exists_ne (λ x, x ∈ H) (1 : H) /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from set_like.coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[to_additive] lemma subsingleton_iff : subsingleton G ↔ subsingleton (subgroup G) := ⟨ λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩, λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩⟩ @[to_additive] lemma nontrivial_iff : nontrivial G ↔ nontrivial (subgroup G) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : unique (subgroup G) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mp ‹_›) a _⟩ @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mp ‹_› @[to_additive] lemma eq_top_iff' : H = ⊤ ↔ ∀ x : G, x ∈ H := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and inverses, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction' variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_mono {f : G →* N} {K K' : subgroup N} : K ≤ K' → comap f K ≤ comap f K' := preimage_mono @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_mono {f : G →* N} {K K' : subgroup G} : K ≤ K' → map f K ≤ map f K' := image_subset _ @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma comap_subtype_inf_left {H K : subgroup G} : comap H.subtype (H ⊓ K) = comap H.subtype K := ext $ λ x, and_iff_right_of_imp (λ _, x.prop) @[simp, to_additive] lemma comap_subtype_inf_right {H K : subgroup G} : comap K.subtype (H ⊓ K) = comap K.subtype H := ext $ λ x, and_iff_left_of_imp (λ _, x.prop) /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ @[priority 100, to_additive] instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } lemma mem_normalizer_fintype {S : set G} [fintype S] {x : G} (h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S := by haveI := classical.prop_decidable; haveI := set.fintype_image S (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' S = S := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective S conj_injective), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' S := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩ variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (λ x, x ∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def to_range (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- Restriction of a group hom to a subgroup of the domain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the domain."] def restrict (f : G →* N) (H : subgroup G) : H →* N := f.comp H.subtype @[simp, to_additive] lemma restrict_apply {H : subgroup G} (f : G →* N) (x : H) : f.restrict H x = f (x : G) := rfl /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] instance decidable_mem_ker [decidable_eq N] (f : G →* N) : decidable_pred (∈ f.ker) := λ x, decidable_of_iff (f x = 1) f.mem_ker @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end @[to_additive] lemma ker_eq_bot_iff (f : G →* N) : f.ker = ⊥ ↔ function.injective f := begin split, { intros h x y hxy, rwa [←mul_inv_eq_one, ←map_inv, ←map_mul, ←mem_ker, h, mem_bot, mul_inv_eq_one] at hxy }, { exact λ h, le_bot_iff.mp (λ x hx, h (hx.trans f.map_one.symm)) }, end /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [set_like.mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace subgroup variables {N : Type*} [group N] (H : subgroup G) @[to_additive] lemma map_eq_bot_iff {f : G →* N} : H.map f = ⊥ ↔ H ≤ f.ker := begin rw eq_bot_iff, split, { exact λ h x hx, h ⟨x, hx, rfl⟩ }, { intros h x hx, obtain ⟨y, hy, rfl⟩ := hx, exact h hy }, end @[to_additive] lemma map_eq_bot_iff_of_injective {f : G →* N} (hf : function.injective f) : H.map f = ⊥ ↔ H = ⊥ := by rw [map_eq_bot_iff, f.ker_eq_bot_iff.mpr hf, le_bot_iff] end subgroup namespace subgroup open monoid_hom variables {H : Type*} [group H] @[to_additive] lemma map_le_range (f : G →* H) (K : subgroup G) : map f K ≤ f.range := (range_eq_map f).symm ▸ map_mono le_top @[to_additive] lemma ker_le_comap (f : G →* H) (K : subgroup H) : f.ker ≤ comap f K := comap_mono bot_le @[to_additive] lemma map_comap_le (f : G →* H) (K : subgroup H) : map f (comap f K) ≤ K := (gc_map_comap f).l_u_le _ @[to_additive] lemma le_comap_map (f : G →* H) (K : subgroup G) : K ≤ comap f (map f K) := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_eq (f : G →* H) (K : subgroup H) : map f (comap f K) = f.range ⊓ K := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp [set.inter_comm], end @[to_additive] lemma comap_map_eq (f : G →* H) (K : subgroup G) : comap f (map f K) = K ⊔ f.ker := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (ker_le_comap _ _)), intros x hx, simp only [exists_prop, mem_map, mem_comap] at hx, rcases hx with ⟨y, hy, hy'⟩, have : y⁻¹ * x ∈ f.ker, { rw mem_ker, simp [hy'] }, convert mul_mem _ (mem_sup_left hy) (mem_sup_right this), simp, end @[to_additive] lemma map_comap_eq_self {f : G →* H} {K : subgroup H} (h : K ≤ f.range) : map f (comap f K) = K := by rwa [map_comap_eq, inf_eq_right] @[to_additive] lemma map_comap_eq_self_of_surjective {f : G →* H} (h : function.surjective f) (K : subgroup H) : map f (comap f K) = K := map_comap_eq_self ((range_top_of_surjective _ h).symm ▸ le_top) @[to_additive] lemma comap_injective {f : G →* H} (h : function.surjective f) : function.injective (comap f) := λ K L hKL, by { apply_fun map f at hKL, simpa [map_comap_eq_self_of_surjective h] using hKL } @[to_additive] lemma comap_map_eq_self {f : G →* H} {K : subgroup G} (h : f.ker ≤ K) : comap f (map f K) = K := by rwa [comap_map_eq, sup_eq_left] @[to_additive] lemma comap_map_eq_self_of_injective {f : G →* H} (h : function.injective f) (K : subgroup G) : comap f (map f K) = K := comap_map_eq_self (((ker_eq_bot_iff _).mpr h).symm ▸ bot_le) @[to_additive] lemma map_injective {f : G →* H} (h : function.injective f) : function.injective (map f) := λ K L hKL, by { apply_fun comap f at hKL, simpa [comap_map_eq_self_of_injective h] using hKL } @[to_additive] lemma map_eq_comap_of_inverse {f : G →* H} {g : H →* G} (hl : function.left_inverse g f) (hr : function.right_inverse g f) (K : subgroup G) : map f K = comap g K := set_like.ext' $ by rw [coe_map, coe_comap, set.image_eq_preimage_of_inverse hl hr] end subgroup namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) (f_inv : G₂ → G₁) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ @[to_additive "Auxiliary definition used to define `lift_of_right_inverse`"] def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (f_inv b), map_one' := hg (hf 1), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [hf _], end } @[simp, to_additive] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f x) = g x := begin dsimp [lift_of_right_inverse_aux], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [hf _], end /-- `lift_of_right_inverse f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+* G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_right_inverse f f_inv hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`add_monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+ G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+ G₃` satisfies `hg : f.ker ≤ g.ker`. See `add_monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `monoid_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp, to_additive "A non-computable version of `add_monoid_hom.lift_of_right_inverse` for when no computable right inverse is available."] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) @[simp, to_additive] lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) (x : G₁) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x @[simp, to_additive] lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := monoid_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g @[to_additive] lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance @[priority 100, to_additive] instance subgroup.normal_inf (H N : subgroup G) [hN : N.normal] : ((H ⊓ N).comap H.subtype).normal := ⟨λ x hx g, begin simp only [subgroup.mem_inf, coe_subtype, subgroup.mem_comap] at hx, simp only [subgroup.coe_mul, subgroup.mem_inf, coe_subtype, subgroup.coe_inv, subgroup.mem_comap], exact ⟨H.mul_mem (H.mul_mem g.2 hx.1) (H.inv_mem g.2), hN.1 x hx.2 g⟩, end⟩ namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset end add_subgroup lemma of_mul_image_gpowers_eq_gmultiples_of_mul { x : G } : additive.of_mul '' ((subgroup.gpowers x) : set G) = add_subgroup.gmultiples (additive.of_mul x) := begin ext y, split, { rintro ⟨z, ⟨m, hm⟩, hz2⟩, use m, simp only, rwa [← of_mul_gpow, hm] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_gpow } end lemma of_add_image_gmultiples_eq_gpowers_of_add {x : A} : multiplicative.of_add '' ((add_subgroup.gmultiples x) : set A) = subgroup.gpowers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_gpowers_eq_gmultiples_of_mul, end namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ? namespace subgroup variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C} @[to_additive] lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := ⟨λ h, begin rw [← closure_eq s, ← closure_eq t, ← closure_union] at h, apply closure_induction h, { rintro y (h | h), { exact ⟨y, h, 1, t.one_mem, by simp⟩ }, { exact ⟨1, s.one_mem, y, h, by simp⟩ } }, { exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, mul_mem _ hy₁ hy₂, _, mul_mem _ hz₁ hz₂, by simp [mul_assoc]; cc⟩ }, { rintro _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, inv_mem _ hy, _, inv_mem _ hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem _ ((le_sup_left : s ≤ s ⊔ t) hy) ((le_sup_right : t ≤ s ⊔ t) hz)⟩ @[to_additive] lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] @[to_additive] instance : is_modular_lattice (subgroup C) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw ← inv_mul_cancel_left b c, apply z.mul_mem (z.inv_mem (xz hb)) haz, end⟩ end subgroup section variables (G) (A) /-- A `group` is simple when it has exactly two normal `subgroup`s. -/ class is_simple_group extends nontrivial G : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : subgroup G, H.normal → H = ⊥ ∨ H = ⊤) /-- An `add_group` is simple when it has exactly two normal `add_subgroup`s. -/ class is_simple_add_group extends nontrivial A : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : add_subgroup A, H.normal → H = ⊥ ∨ H = ⊤) attribute [to_additive] is_simple_group variables {G} {A} @[to_additive] lemma subgroup.normal.eq_bot_or_eq_top [is_simple_group G] {H : subgroup G} (Hn : H.normal) : H = ⊥ ∨ H = ⊤ := is_simple_group.eq_bot_or_eq_top_of_normal H Hn namespace is_simple_group @[to_additive] instance {C : Type*} [comm_group C] [is_simple_group C] : is_simple_lattice (subgroup C) := ⟨λ H, H.normal_of_comm.eq_bot_or_eq_top⟩ open subgroup @[to_additive] lemma is_simple_group_of_surjective {H : Type*} [group H] [is_simple_group G] [nontrivial H] (f : G →* H) (hf : function.surjective f) : is_simple_group H := ⟨nontrivial.exists_pair_ne, λ H iH, begin refine ((iH.comap f).eq_bot_or_eq_top).imp (λ h, _) (λ h, _), { rw [←map_bot f, ←h, map_comap_eq_self_of_surjective hf] }, { rw [←comap_top f] at h, exact comap_injective hf h } end⟩ end is_simple_group end section pointwise namespace subgroup @[to_additive] lemma closure_mul_le (S T : set G) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : subgroup G) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) @[to_additive] private def mul_normal_aux (H N : subgroup G) [hN : N.normal] : subgroup G := { carrier := (H : set G) * N, one_mem' := ⟨1, 1, H.one_mem, N.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨h, n, hh, hn, ha⟩ ⟨h', n', hh', hn', hb⟩, ⟨h * h', h'⁻¹ * n * h' * n', H.mul_mem hh hh', N.mul_mem (by simpa using hN.conj_mem _ hn h'⁻¹) hn', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨h, n, hh, hn, hx⟩, ⟨h⁻¹, h * n⁻¹ * h⁻¹, H.inv_mem hh, hN.conj_mem _ (N.inv_mem hn) h, by rw [mul_assoc h, inv_mul_cancel_left, ← hx, mul_inv_rev]⟩ } /-- The carrier of `H ⊔ N` is just `↑H * ↑N` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `H ⊔ N` is just `↑H + ↑N` (pointwise set addition) when `N` is normal."] lemma mul_normal (H N : subgroup G) [N.normal] : (↑(H ⊔ N) : set G) = H * N := set.subset.antisymm (show H ⊔ N ≤ mul_normal_aux H N, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure H N).symm ▸ subset_closure) @[to_additive] private def normal_mul_aux (N H : subgroup G) [hN : N.normal] : subgroup G := { carrier := (N : set G) * H, one_mem' := ⟨1, 1, N.one_mem, H.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨n, h, hn, hh, ha⟩ ⟨n', h', hn', hh', hb⟩, ⟨n * (h * n' * h⁻¹), h * h', N.mul_mem hn (hN.conj_mem _ hn' _), H.mul_mem hh hh', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨n, h, hn, hh, hx⟩, ⟨h⁻¹ * n⁻¹ * h, h⁻¹, by simpa using hN.conj_mem _ (N.inv_mem hn) h⁻¹, H.inv_mem hh, by rw [mul_inv_cancel_right, ← mul_inv_rev, hx]⟩ } /-- The carrier of `N ⊔ H` is just `↑N * ↑H` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `N ⊔ H` is just `↑N + ↑H` (pointwise set addition) when `N` is normal."] lemma normal_mul (N H : subgroup G) [N.normal] : (↑(N ⊔ H) : set G) = N * H := set.subset.antisymm (show N ⊔ H ≤ normal_mul_aux N H, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure N H).symm ▸ subset_closure) end subgroup end pointwise
e47fde9b48ef6669169a645ae0e1276d541b84b6
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/algebra/char_p/basic.lean
b8a754fe5b0814a31cc170d79a0ef24a17dfa361
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,197
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz -/ import data.fintype.basic import data.nat.choose import data.int.modeq import algebra.module.basic import algebra.iterate_hom import group_theory.order_of_element import algebra.group.type_tags /-! # Characteristic of semirings -/ universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) @[simp] lemma char_p.cast_card_eq_zero (R : Type*) [ring R] [fintype R] : (fintype.card R : R) = 0 := begin have : fintype.card R •ℕ (1 : R) = 0 := @pow_card_eq_one (multiplicative R) _ _ (multiplicative.of_add 1), simpa only [mul_one, nsmul_eq_mul] end lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end lemma char_p.int_coe_eq_int_coe_iff (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = (b : R) ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ theorem char_p.congr {R : Type u} [semiring R] {p : ℕ} (q : ℕ) [hq : char_p R q] (h : q = p) : char_p R p := h ▸ hq /-- Noncomputable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) namespace ring_char variables (R : Type u) [semiring R] theorem spec : ∀ x:ℕ, (x:R) = 0 ↔ ring_char R ∣ x := by letI := (classical.some_spec (char_p.exists_unique R)).1; unfold ring_char; exact char_p.cast_eq_zero_iff R (ring_char R) theorem eq {p : ℕ} (C : char_p R p) : p = ring_char R := (classical.some_spec (char_p.exists_unique R)).2 p C instance char_p : char_p R (ring_char R) := ⟨spec R⟩ variables {R} theorem of_eq {p : ℕ} (h : ring_char R = p) : char_p R p := char_p.congr (ring_char R) h theorem eq_iff {p : ℕ} : ring_char R = p ↔ char_p R p := ⟨of_eq, eq.symm ∘ eq R⟩ theorem dvd {x : ℕ} (hx : (x : R) = 0) : ring_char R ∣ x := (spec R x).1 hx end ring_char theorem add_pow_char_of_commute (R : Type u) [semiring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x + y)^p = x^p + y^p := begin rw [commute.add_pow h, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one], congr' 1, convert finset.sum_eq_single 0 _ _, { simp }, swap, { intro h1, contrapose! h1, rw finset.mem_range, apply nat.prime.pos, assumption }, intros b h1 h2, suffices : (p.choose b : R) = 0, { rw this, simp }, rw char_p.cast_eq_zero_iff R p, refine nat.prime.dvd_choose_self (pos_iff_ne_zero.mpr h2) _ (by assumption), rwa ← finset.mem_range end theorem add_pow_char_pow_of_commute (R : Type u) [semiring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply add_pow_char_of_commute, apply commute.pow_pow h, end theorem sub_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x - y)^p = x^p - y^p := begin rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)], simp, repeat {apply_instance}, end theorem sub_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply sub_pow_char_of_commute, apply commute.pow_pow h, end theorem add_pow_char (α : Type u) [comm_semiring α] {p : ℕ} [fact p.prime] [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := add_pow_char_of_commute _ _ _ (commute.all _ _) theorem add_pow_char_pow (R : Type u) [comm_semiring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := add_pow_char_pow_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact p.prime] [char_p α p] (x y : α) : (x - y)^p = x^p - y^p := sub_pow_char_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := sub_pow_char_pow_of_commute _ _ _ (commute.all _ _) lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] lemma char_p.neg_one_ne_one (R : Type*) [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] : (-1 : R) ≠ (1 : R) := begin suffices : (2 : R) ≠ 0, { symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this }, assume h, rw [show (2 : R) = (2 : ℕ), by norm_cast] at h, have := (char_p.cast_eq_zero_iff R p 2).mp h, have := nat.le_of_dvd dec_trivial this, rw fact at *, linarith, end lemma ring_hom.char_p_iff_char_p {K L : Type*} [field K] [field L] (f : K →+* L) (p : ℕ) : char_p K p ↔ char_p L p := begin split; { introI _c, constructor, intro n, rw [← @char_p.cast_eq_zero_iff _ _ p _c n, ← f.injective.eq_iff, f.map_nat_cast, f.map_zero] } end section frobenius section comm_semiring variables (R : Type u) [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt), map_add' := add_pow_char R } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n := begin induction n, {simp}, rw [function.iterate_succ', pow_succ', pow_mul, function.comp_apply, frobenius_def, n_ih] end theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ variable {R} theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := function.semiconj.iterate_right (f.map_frobenius p) n x theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end comm_semiring section comm_ring variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y end comm_ring end frobenius theorem frobenius_inj (α : Type u) [comm_ring α] [no_zero_divisors α] (p : ℕ) [fact p.prime] [char_p α p] : function.injective (frobenius α p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p α p] (hp : 2 ≤ p) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_two_le α _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime := (char_p.char_is_prime_or_zero α _).resolve_right (pos_iff_ne_zero.1 h) theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain section char_one variables {R : Type*} @[priority 100] -- see Note [lower instance priority] instance [semiring R] [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul lemma false_of_nontrivial_of_char_one [semiring R] [nontrivial R] [char_p R 1] : false := false_of_nontrivial_of_subsingleton R lemma ring_char_ne_one [semiring R] [nontrivial R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } lemma nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) {R : Type*} [semiring R] [hr : char_p R v] : nontrivial R := ⟨⟨(1 : ℕ), 0, λ h, hv $ by rwa [char_p.cast_eq_zero_iff _ v, nat.dvd_one] at h; assumption ⟩⟩ end char_one end char_p section variables (n : ℕ) (R : Type*) [comm_ring R] [fintype R] lemma char_p_of_ne_zero (hn : fintype.card R = n) (hR : ∀ i < n, (i : R) = 0 → i = 0) : char_p R n := { cast_eq_zero_iff := begin have H : (n : R) = 0, by { rw [← hn, char_p.cast_card_eq_zero] }, intro k, split, { intro h, rw [← nat.mod_add_div k n, nat.cast_add, nat.cast_mul, H, zero_mul, add_zero] at h, rw nat.dvd_iff_mod_eq_zero, apply hR _ (nat.mod_lt _ _) h, rw [← hn, fintype.card_pos_iff], exact ⟨0⟩, }, { rintro ⟨k, rfl⟩, rw [nat.cast_mul, H, zero_mul] } end } lemma char_p_of_prime_pow_injective (p : ℕ) [hp : fact p.prime] (n : ℕ) (hn : fintype.card R = p ^ n) (hR : ∀ i ≤ n, (p ^ i : R) = 0 → i = n) : char_p R (p ^ n) := begin obtain ⟨c, hc⟩ := char_p.exists R, resetI, have hcpn : c ∣ p ^ n, { rw [← char_p.cast_eq_zero_iff R c, ← hn, char_p.cast_card_eq_zero], }, obtain ⟨i, hi, hc⟩ : ∃ i ≤ n, c = p ^ i, by rwa nat.dvd_prime_pow hp at hcpn, obtain rfl : i = n, { apply hR i hi, rw [← nat.cast_pow, ← hc, char_p.cast_eq_zero] }, rwa ← hc end end
864aa797f1d6a4d6275dfdc8cb5c21178cc4fad9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/continuous_function/weierstrass.lean
577f15005b606f97f1a6e37129c6a074c3829997
[ "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
5,414
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.algebra.subalgebra import analysis.special_functions.bernstein /-! # The Weierstrass approximation theorem for continuous functions on `[a,b]` We've already proved the Weierstrass approximation theorem in the sense that we've shown that the Bernstein approximations to a continuous function on `[0,1]` converge uniformly. Here we rephrase this more abstractly as `polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤` and then, by precomposing with suitable affine functions, `polynomial_functions_closure_eq_top : (polynomial_functions (set.Icc a b)).topological_closure = ⊤` -/ open continuous_map filter open_locale unit_interval /-- The special case of the Weierstrass approximation theorem for the interval `[0,1]`. This is just a matter of unravelling definitions and using the Bernstein approximations. -/ theorem polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤ := begin apply eq_top_iff.mpr, rintros f -, refine filter.frequently.mem_closure _, refine filter.tendsto.frequently (bernstein_approximation_uniform f) _, apply frequently_of_forall, intro n, simp only [set_like.mem_coe], apply subalgebra.sum_mem, rintro n -, apply subalgebra.smul_mem, dsimp [bernstein, polynomial_functions], simp, end /-- The Weierstrass approximation theorem: polynomials functions on `[a, b] ⊆ ℝ` are dense in `C([a,b],ℝ)` (While we could deduce this as an application of the Stone-Weierstrass theorem, our proof of that relies on the fact that `abs` is in the closure of polynomials on `[-M, M]`, so we may as well get this done first.) -/ theorem polynomial_functions_closure_eq_top (a b : ℝ) : (polynomial_functions (set.Icc a b)).topological_closure = ⊤ := begin by_cases h : a < b, -- (Otherwise it's easy; we'll deal with that later.) { -- We can pullback continuous functions on `[a,b]` to continuous functions on `[0,1]`, -- by precomposing with an affine map. let W : C(set.Icc a b, ℝ) →ₐ[ℝ] C(I, ℝ) := comp_right_alg_hom ℝ (Icc_homeo_I a b h).symm.to_continuous_map, -- This operation is itself a homeomorphism -- (with respect to the norm topologies on continuous functions). let W' : C(set.Icc a b, ℝ) ≃ₜ C(I, ℝ) := comp_right_homeomorph ℝ (Icc_homeo_I a b h).symm, have w : (W : C(set.Icc a b, ℝ) → C(I, ℝ)) = W' := rfl, -- Thus we take the statement of the Weierstrass approximation theorem for `[0,1]`, have p := polynomial_functions_closure_eq_top', -- and pullback both sides, obtaining an equation between subalgebras of `C([a,b], ℝ)`. apply_fun (λ s, s.comap' W) at p, simp only [algebra.comap_top] at p, -- Since the pullback operation is continuous, it commutes with taking `topological_closure`, rw subalgebra.topological_closure_comap'_homeomorph _ W W' w at p, -- and precomposing with an affine map takes polynomial functions to polynomial functions. rw polynomial_functions.comap'_comp_right_alg_hom_Icc_homeo_I at p, -- 🎉 exact p }, { -- Otherwise, `b ≤ a`, and the interval is a subsingleton, -- so all subalgebras are the same anyway. haveI : subsingleton (set.Icc a b) := ⟨λ x y, le_antisymm ((x.2.2.trans (not_lt.mp h)).trans y.2.1) ((y.2.2.trans (not_lt.mp h)).trans x.2.1)⟩, haveI := (continuous_map.subsingleton_subalgebra (set.Icc a b) ℝ), apply subsingleton.elim, } end /-- An alternative statement of Weierstrass' theorem. Every real-valued continuous function on `[a,b]` is a uniform limit of polynomials. -/ theorem continuous_map_mem_polynomial_functions_closure (a b : ℝ) (f : C(set.Icc a b, ℝ)) : f ∈ (polynomial_functions (set.Icc a b)).topological_closure := begin rw polynomial_functions_closure_eq_top _ _, simp, end /-- An alternative statement of Weierstrass' theorem, for those who like their epsilons. Every real-valued continuous function on `[a,b]` is within any `ε > 0` of some polynomial. -/ theorem exists_polynomial_near_continuous_map (a b : ℝ) (f : C(set.Icc a b, ℝ)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : polynomial ℝ), ∥p.to_continuous_map_on _ - f∥ < ε := begin have w := mem_closure_iff_frequently.mp (continuous_map_mem_polynomial_functions_closure _ _ f), rw metric.nhds_basis_ball.frequently_iff at w, obtain ⟨-, H, ⟨m, ⟨-, rfl⟩⟩⟩ := w ε pos, rw [metric.mem_ball, dist_eq_norm] at H, exact ⟨m, H⟩, end /-- Another alternative statement of Weierstrass's theorem, for those who like epsilons, but not bundled continuous functions. Every real-valued function `ℝ → ℝ` which is continuous on `[a,b]` can be approximated to within any `ε > 0` on `[a,b]` by some polynomial. -/ theorem exists_polynomial_near_of_continuous_on (a b : ℝ) (f : ℝ → ℝ) (c : continuous_on f (set.Icc a b)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : polynomial ℝ), ∀ x ∈ set.Icc a b, abs (p.eval x - f x) < ε := begin let f' : C(set.Icc a b, ℝ) := ⟨λ x, f x, continuous_on_iff_continuous_restrict.mp c⟩, obtain ⟨p, b⟩ := exists_polynomial_near_continuous_map a b f' ε pos, use p, rw norm_lt_iff _ pos at b, intros x m, exact b ⟨x, m⟩, end
4a3222e373690ec4a776fa0d06f7ede790c03e2f
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/polynomial/coeff.lean
18df6483a9bf1e9abed4aa9876cdfc7726b8f564
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,985
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.monomial import data.finset.nat_antidiagonal /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} variables [semiring R] {p q r : polynomial R} section coeff lemma coeff_one (n : ℕ) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_monomial @[simp] lemma coeff_add (p q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl lemma coeff_sum [semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply @[simp] lemma coeff_smul (p : polynomial R) (r : R) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply lemma mem_support_iff_coeff_ne_zero : n ∈ p.support ↔ p.coeff n ≠ 0 := by { rw mem_support_to_fun, refl } lemma not_mem_support_iff_coeff_zero : n ∉ p.support ↔ p.coeff n = 0 := by { rw [mem_support_to_fun, not_not], refl, } variable (R) /-- The nth coefficient, as a linear map. -/ def lcoeff (n : ℕ) : polynomial R →ₗ[R] R := finsupp.lapply n variable {R} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial R) : lcoeff R n f = coeff f n := rfl @[simp] lemma finset_sum_coeff {ι : Type*} (s : finset ι) (f : ι → polynomial R) (n : ℕ) : coeff (∑ b in s, f b) n = ∑ b in s, coeff (f b) n := (s.sum_hom (λ q : polynomial R, lcoeff R n q)).symm lemma coeff_mul (p q : polynomial R) (n : ℕ) : coeff (p * q) n = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 := add_monoid_algebra.mul_apply_antidiagonal p q n _ (λ x, nat.mem_antidiagonal) @[simp] lemma mul_coeff_zero (p q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := by simp [coeff_mul] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by simp lemma coeff_X_mul_zero (p : polynomial R) : coeff (X * p) 0 = 0 := by simp lemma coeff_C_mul_X (x : R) (k n : ℕ) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [monomial, single, eq_comm, coeff]; congr @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := add_monoid_algebra.single_zero_mul_apply p a n lemma C_mul' (a : R) (f : polynomial R) : C a * f = a • f := ext $ λ n, coeff_C_mul f @[simp] lemma coeff_mul_C (p : polynomial R) (n : ℕ) (a : R) : coeff (p * C a) n = coeff p n * a := add_monoid_algebra.mul_single_zero_apply p a n lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by { simp only [X_pow_eq_monomial, monomial, single, eq_comm], congr } @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff (X^n : polynomial R) n = 1 := by simp [coeff_X_pow] theorem coeff_mul_X_pow (p : polynomial R) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end @[simp] theorem coeff_mul_X (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) lemma C_mul_X_pow_eq_monomial (c : R) (n : ℕ) : C c * X^n = monomial n c := by { ext1, rw [monomial_eq_smul_X, coeff_smul, coeff_C_mul] } lemma support_mul_X_pow (c : R) (n : ℕ) (H : c ≠ 0) : (C c * X^n).support = singleton n := by rw [C_mul_X_pow_eq_monomial, support_monomial n c H] lemma support_C_mul_X_pow' {c : R} {n : ℕ} : (C c * X^n).support ⊆ singleton n := by { rw [C_mul_X_pow_eq_monomial], exact support_monomial' n c } lemma C_dvd_iff_dvd_coeff (r : R) (φ : polynomial R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : ℕ → R := λ i, if i ∈ φ.support then c i else 0, let ψ : polynomial R := ∑ i in φ.support, monomial i (c' i), use ψ, ext i, simp only [ψ, c', coeff_C_mul, mem_support_iff, coeff_monomial, finset_sum_coeff, finset.sum_ite_eq'], split_ifs with hi hi, { rw hc }, { rw [not_not] at hi, rwa mul_zero } }, end end coeff open submodule polynomial set variables {f : polynomial R} {I : submodule (polynomial R) (polynomial R)} /-- If the coefficients of a polynomial belong to n ideal contains the submodule span of the coefficients of a polynomial. -/ lemma span_le_of_coeff_mem_C_inverse (cf : ∀ (i : ℕ), f.coeff i ∈ (C ⁻¹' I.carrier)) : (span (polynomial R) {g | ∃ i, g = C (f.coeff i)}) ≤ I := begin refine bInter_subset_of_mem _, rintros _ ⟨i, rfl⟩, exact (mem_coe _).mpr (cf i), end lemma mem_span_C_coeff : f ∈ span (polynomial R) {g : polynomial R | ∃ i : ℕ, g = (C (coeff f i))} := begin rw [← f.sum_single] {occs := occurrences.pos [1]}, refine sum_mem _ (λ i hi, _), change monomial i _ ∈ span _ _, rw [← C_mul_X_pow_eq_monomial, ← X_pow_mul], exact smul_mem _ _ (subset_span ⟨i, rfl⟩), end lemma exists_coeff_not_mem_C_inverse : f ∉ I → ∃ i : ℕ , coeff f i ∉ (C ⁻¹' I.carrier) := imp_of_not_imp_not _ _ (λ cf, not_not.mpr ((span_le_of_coeff_mem_C_inverse (not_exists_not.mp cf)) mem_span_C_coeff)) end polynomial
b5f2834590b23177a9d7210214ce27af4f296c1f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/units.lean
6e0ae1f8fa2d111fa91c0c6a0778caac75afaadc
[ "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
12,207
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.specific_limits /-! # The group of units of a complete normed ring This file contains the basic theory for the group of units (invertible elements) of a complete normed ring (Banach algebras being a notable special case). ## Main results The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations of a unit are units. The latter two are not stated in their optimal form; more precise versions would use the spectral radius. The first main result is `is_open`: the group of units of a complete normed ring is an open subset of the ring. The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is a unit and 0 if not. The other major results of this file (notably `inverse_add`, `inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of `inverse (x + t)` as `t → 0`. -/ noncomputable theory open_locale topological_space variables {R : Type*} [normed_ring R] [complete_space R] namespace units /-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1` from `1` is a unit. Here we construct its `units` structure. -/ @[simps coe] def one_sub (t : R) (h : ∥t∥ < 1) : units R := { val := 1 - t, inv := ∑' n : ℕ, t ^ n, val_inv := mul_neg_geom_series t h, inv_val := geom_series_mul_neg t h } /-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def add (x : units R) (t : R) (h : ∥t∥ < ∥(↑x⁻¹ : R)∥⁻¹) : units R := units.copy -- to make `coe_add` true definitionally, for convenience (x * (units.one_sub (-(↑x⁻¹ * t)) begin nontriviality R using [zero_lt_one], have hpos : 0 < ∥(↑x⁻¹ : R)∥ := units.norm_pos x⁻¹, calc ∥-(↑x⁻¹ * t)∥ = ∥↑x⁻¹ * t∥ : by { rw norm_neg } ... ≤ ∥(↑x⁻¹ : R)∥ * ∥t∥ : norm_mul_le ↑x⁻¹ _ ... < ∥(↑x⁻¹ : R)∥ * ∥(↑x⁻¹ : R)∥⁻¹ : by nlinarith only [h, hpos] ... = 1 : mul_inv_cancel (ne_of_gt hpos) end)) (x + t) (by simp [mul_add]) _ rfl /-- In a complete normed ring, an element `y` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def unit_of_nearby (x : units R) (y : R) (h : ∥y - x∥ < ∥(↑x⁻¹ : R)∥⁻¹) : units R := units.copy (x.add (y - x : R) h) y (by simp) _ rfl /-- The group of units of a complete normed ring is an open subset of the ring. -/ protected lemma is_open : is_open {x : R | is_unit x} := begin nontriviality R, apply metric.is_open_iff.mpr, rintros x' ⟨x, rfl⟩, refine ⟨∥(↑x⁻¹ : R)∥⁻¹, inv_pos.mpr (units.norm_pos x⁻¹), _⟩, intros y hy, rw [metric.mem_ball, dist_eq_norm] at hy, exact (x.unit_of_nearby y hy).is_unit end protected lemma nhds (x : units R) : {x : R | is_unit x} ∈ 𝓝 (x : R) := is_open.mem_nhds units.is_open x.is_unit end units namespace normed_ring open_locale classical big_operators open asymptotics filter metric finset ring lemma inverse_one_sub (t : R) (h : ∥t∥ < 1) : inverse (1 - t) = ↑(units.one_sub t h)⁻¹ := by rw [← inverse_unit (units.one_sub t h), units.coe_one_sub] /-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/ lemma inverse_add (x : units R) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = inverse (1 + ↑x⁻¹ * t) * ↑x⁻¹ := begin nontriviality R, rw [eventually_iff, metric.mem_nhds_iff], have hinv : 0 < ∥(↑x⁻¹ : R)∥⁻¹, by cancel_denoms, use [∥(↑x⁻¹ : R)∥⁻¹, hinv], intros t ht, simp only [mem_ball, dist_zero_right] at ht, have ht' : ∥-↑x⁻¹ * t∥ < 1, { refine lt_of_le_of_lt (norm_mul_le _ _) _, rw norm_neg, refine lt_of_lt_of_le (mul_lt_mul_of_pos_left ht x⁻¹.norm_pos) _, cancel_denoms }, have hright := inverse_one_sub (-↑x⁻¹ * t) ht', have hleft := inverse_unit (x.add t ht), simp only [← neg_mul_eq_neg_mul, sub_neg_eq_add] at hright, simp only [units.coe_add] at hleft, simp [hleft, hright, units.add] end lemma inverse_one_sub_nth_order (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((1:R) - t) = (∑ i in range n, t ^ i) + (t ^ n) * inverse (1 - t) := begin simp only [eventually_iff, metric.mem_nhds_iff], use [1, by norm_num], intros t ht, simp only [mem_ball, dist_zero_right] at ht, simp only [inverse_one_sub t ht, set.mem_set_of_eq], have h : 1 = ((range n).sum (λ i, t ^ i)) * (units.one_sub t ht) + t ^ n, { simp only [units.coe_one_sub], rw [← geom_sum, geom_sum_mul_neg], simp }, rw [← one_mul ↑(units.one_sub t ht)⁻¹, h, add_mul], congr, { rw [mul_assoc, (units.one_sub t ht).mul_inv], simp }, { simp only [units.coe_one_sub], rw [← add_mul, ← geom_sum, geom_sum_mul_neg], simp } end /-- The formula `inverse (x + t) = (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹ + (- x⁻¹ * t) ^ n * inverse (x + t)` holds for `t` sufficiently small. -/ lemma inverse_add_nth_order (x : units R) (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹ + (- ↑x⁻¹ * t) ^ n * inverse (x + t) := begin refine (inverse_add x).mp _, have hzero : tendsto (λ (t : R), - ↑x⁻¹ * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (- (↑x⁻¹ : R))).tendsto 0).comp tendsto_id, simp }, refine (hzero.eventually (inverse_one_sub_nth_order n)).mp (eventually_of_forall _), simp only [neg_mul_eq_neg_mul_symm, sub_neg_eq_add], intros t h1 h2, have h := congr_arg (λ (a : R), a * ↑x⁻¹) h1, dsimp at h, convert h, rw [add_mul, mul_assoc], simp [h2.symm] end lemma inverse_one_sub_norm : is_O (λ t, inverse ((1:R) - t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin simp only [is_O, is_O_with, eventually_iff, metric.mem_nhds_iff], refine ⟨∥(1:R)∥ + 1, (2:ℝ)⁻¹, by norm_num, _⟩, intros t ht, simp only [ball, dist_zero_right, set.mem_set_of_eq] at ht, have ht' : ∥t∥ < 1, { have : (2:ℝ)⁻¹ < 1 := by cancel_denoms, linarith }, simp only [inverse_one_sub t ht', norm_one, mul_one, set.mem_set_of_eq], change ∥∑' n : ℕ, t ^ n∥ ≤ _, have := normed_ring.tsum_geometric_of_norm_lt_1 t ht', have : (1 - ∥t∥)⁻¹ ≤ 2, { rw ← inv_inv₀ (2:ℝ), refine inv_le_inv_of_le (by norm_num) _, have : (2:ℝ)⁻¹ + (2:ℝ)⁻¹ = 1 := by ring, linarith }, linarith end /-- The function `λ t, inverse (x + t)` is O(1) as `t → 0`. -/ lemma inverse_add_norm (x : units R) : is_O (λ t, inverse (↑x + t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin nontriviality R, simp only [is_O_iff, norm_one, mul_one], cases is_O_iff.mp (@inverse_one_sub_norm R _ _) with C hC, use C * ∥((x⁻¹:units R):R)∥, have hzero : tendsto (λ t, - (↑x⁻¹ : R) * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (-↑x⁻¹ : R)).tendsto 0).comp tendsto_id, simp }, refine (inverse_add x).mp ((hzero.eventually hC).mp (eventually_of_forall _)), intros t bound iden, rw iden, simp at bound, have hmul := norm_mul_le (inverse (1 + ↑x⁻¹ * t)) ↑x⁻¹, nlinarith [norm_nonneg (↑x⁻¹ : R)] end /-- The function `λ t, inverse (x + t) - (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹` is `O(t ^ n)` as `t → 0`. -/ lemma inverse_add_norm_diff_nth_order (x : units R) (n : ℕ) : is_O (λ (t : R), inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ∥t∥ ^ n) (𝓝 (0:R)) := begin by_cases h : n = 0, { simpa [h] using inverse_add_norm x }, have hn : 0 < n := nat.pos_of_ne_zero h, simp [is_O_iff], cases (is_O_iff.mp (inverse_add_norm x)) with C hC, use C * ∥(1:ℝ)∥ * ∥(↑x⁻¹ : R)∥ ^ n, have h : eventually_eq (𝓝 (0:R)) (λ t, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ((- ↑x⁻¹ * t) ^ n) * inverse (x + t)), { refine (inverse_add_nth_order x n).mp (eventually_of_forall _), intros t ht, convert congr_arg (λ a, a - (range n).sum (pow (-↑x⁻¹ * t)) * ↑x⁻¹) ht, simp }, refine h.mp (hC.mp (eventually_of_forall _)), intros t _ hLHS, simp only [neg_mul_eq_neg_mul_symm] at hLHS, rw hLHS, refine le_trans (norm_mul_le _ _ ) _, have h' : ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { calc ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(-(↑x⁻¹ * t))∥ ^ n : norm_pow_le' _ hn ... = ∥↑x⁻¹ * t∥ ^ n : by rw norm_neg ... ≤ (∥(↑x⁻¹ : R)∥ * ∥t∥) ^ n : _ ... = ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n : mul_pow _ _ n, exact pow_le_pow_of_le_left (norm_nonneg _) (norm_mul_le ↑x⁻¹ t) n }, have h'' : 0 ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { refine mul_nonneg _ _; exact pow_nonneg (norm_nonneg _) n }, nlinarith [norm_nonneg (inverse (↑x + t))], end /-- The function `λ t, inverse (x + t) - x⁻¹` is `O(t)` as `t → 0`. -/ lemma inverse_add_norm_diff_first_order (x : units R) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹) (λ t, ∥t∥) (𝓝 (0:R)) := by { convert inverse_add_norm_diff_nth_order x 1; simp } /-- The function `λ t, inverse (x + t) - x⁻¹ + x⁻¹ * t * x⁻¹` is `O(t ^ 2)` as `t → 0`. -/ lemma inverse_add_norm_diff_second_order (x : units R) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ t, ∥t∥ ^ 2) (𝓝 (0:R)) := begin convert inverse_add_norm_diff_nth_order x 2, ext t, simp only [range_succ, range_one, sum_insert, mem_singleton, sum_singleton, not_false_iff, one_ne_zero, pow_zero, add_mul, pow_one, one_mul, neg_mul_eq_neg_mul_symm, sub_add_eq_sub_sub_swap, sub_neg_eq_add], end /-- The function `inverse` is continuous at each unit of `R`. -/ lemma inverse_continuous_at (x : units R) : continuous_at inverse (x : R) := begin have h_is_o : is_o (λ (t : R), ∥inverse (↑x + t) - ↑x⁻¹∥) (λ (t : R), (1:ℝ)) (𝓝 0), { refine is_o_norm_left.mpr ((inverse_add_norm_diff_first_order x).trans_is_o _), exact is_o_norm_left.mpr (is_o_id_const one_ne_zero) }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [continuous_at], rw [tendsto_iff_norm_tendsto_zero, inverse_unit], convert h_is_o.tendsto_0.comp h_lim, ext, simp end end normed_ring namespace units open opposite filter normed_ring /-- In a normed ring, the coercion from `units R` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open map. -/ lemma is_open_map_coe : is_open_map (coe : units R → R) := begin rw is_open_map_iff_nhds_le, intros x s, rw [mem_map, mem_nhds_induced], rintros ⟨t, ht, hts⟩, obtain ⟨u, hu, v, hv, huvt⟩ : ∃ (u : set R), u ∈ 𝓝 ↑x ∧ ∃ (v : set Rᵒᵖ), v ∈ 𝓝 (opposite.op ↑x⁻¹) ∧ u.prod v ⊆ t, { simpa [embed_product, mem_nhds_prod_iff] using ht }, have : u ∩ (op ∘ ring.inverse) ⁻¹' v ∩ (set.range (coe : units R → R)) ∈ 𝓝 ↑x, { refine inter_mem (inter_mem hu _) (units.nhds x), refine (continuous_op.continuous_at.comp (inverse_continuous_at x)).preimage_mem_nhds _, simpa using hv }, refine mem_of_superset this _, rintros _ ⟨⟨huy, hvy⟩, ⟨y, rfl⟩⟩, have : embed_product R y ∈ u.prod v := ⟨huy, by simpa using hvy⟩, simpa using hts (huvt this) end /-- In a normed ring, the coercion from `units R` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open embedding. -/ lemma open_embedding_coe : open_embedding (coe : units R → R) := open_embedding_of_continuous_injective_open continuous_coe ext is_open_map_coe end units
46c03e2545249a65c9551dc46c5abf9a91642c2e
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/order/jordan_holder.lean
f2942f572ec05241c2975a2607f913f1d394df17
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,872
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import order.lattice import data.fin import data.list.sort import data.equiv.fin import data.equiv.functor /-! # Jordan-Hölder Theorem This file proves the Jordan Hölder theorem for a `jordan_holder_lattice`, a class also defined in this file. Examples of `jordan_holder_lattice` include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. Using this approach the theorem need not be proved seperately for both groups and modules, the proof in this file can be applied to both. ## Main definitions The main definitions in this file are `jordan_holder_lattice` and `composition_series`, and the relation `equivalent` on `composition_series` A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. A `composition_series X` is a finite nonempty series of elements of the lattice `X` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i, s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` ## Main theorems The main theorem is `composition_series.jordan_holder`, which says that if two composition series have the same least element and the same largest element, then they are `equivalent`. ## TODO Provide instances of `jordan_holder_lattice` for both submodules and subgroups, and potentially for modular lattices. It is not entirely clear how this should be done. Possibly there should be no global instances of `jordan_holder_lattice`, and the instances should only be defined locally in order to prove the Jordan-Hölder theorem for modules/groups and the API should be transferred because many of the theorems in this file will have stronger versions for modules. There will also need to be an API for mapping composition series across homomorphisms. It is also probably possible to provide an instance of `jordan_holder_lattice` for any `modular_lattice`, and in this case the Jordan-Hölder theorem will say that there is a well defined notion of length of a modular lattice. However an instance of `jordan_holder_lattice` for a modular lattice will not be able to contain the correct notion of isomorphism for modules, so a separate instance for modules will still be required and this will clash with the instance for modular lattices, and so at least one of these instances should not be a global instance. -/ universe u open set /-- A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. Examples include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. -/ class jordan_holder_lattice (X : Type u) [lattice X] := (is_maximal : X → X → Prop) (lt_of_is_maximal : ∀ {x y}, is_maximal x y → x < y) (sup_eq_of_is_maximal : ∀ {x y z}, is_maximal x z → is_maximal y z → x ≠ y → x ⊔ y = z) (is_maximal_inf_left_of_is_maximal_sup : ∀ {x y}, is_maximal x (x ⊔ y) → is_maximal y (x ⊔ y) → is_maximal (x ⊓ y) x) (iso : (X × X) → (X × X) → Prop) (iso_symm : ∀ {x y}, iso x y → iso y x) (iso_trans : ∀ {x y z}, iso x y → iso y z → iso x z) (second_iso : ∀ {x y}, is_maximal x (x ⊔ y) → iso (x, x ⊔ y) (x ⊓ y, y)) namespace jordan_holder_lattice variables {X : Type u} [lattice X] [jordan_holder_lattice X] lemma is_maximal_inf_right_of_is_maximal_sup {x y : X} (hxz : is_maximal x (x ⊔ y)) (hyz : is_maximal y (x ⊔ y)) : is_maximal (x ⊓ y) y := begin rw [inf_comm], rw [sup_comm] at hxz hyz, exact is_maximal_inf_left_of_is_maximal_sup hyz hxz end lemma is_maximal_of_eq_inf (x b : X) {a y : X} (ha : x ⊓ y = a) (hxy : x ≠ y) (hxb : is_maximal x b) (hyb : is_maximal y b) : is_maximal a y := begin have hb : x ⊔ y = b, from sup_eq_of_is_maximal hxb hyb hxy, substs a b, exact is_maximal_inf_right_of_is_maximal_sup hxb hyb end lemma second_iso_of_eq {x y a b : X} (hm : is_maximal x a) (ha : x ⊔ y = a) (hb : x ⊓ y = b) : iso (x, a) (b, y) := by substs a b; exact second_iso hm lemma is_maximal.iso_refl {x y : X} (h : is_maximal x y) : iso (x, y) (x, y) := second_iso_of_eq h (sup_eq_right.2 (le_of_lt (lt_of_is_maximal h))) (inf_eq_left.2 (le_of_lt (lt_of_is_maximal h))) end jordan_holder_lattice open jordan_holder_lattice attribute [symm] iso_symm attribute [trans] iso_trans /-- A `composition_series X` is a finite nonempty series of elements of a `jordan_holder_lattice` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. -/ structure composition_series (X : Type u) [lattice X] [jordan_holder_lattice X] : Type u := (length : ℕ) (series : fin (length + 1) → X) (step' : ∀ i : fin length, is_maximal (series i.cast_succ) (series i.succ)) namespace composition_series variables {X : Type u} [lattice X] [jordan_holder_lattice X] instance : has_coe_to_fun (composition_series X) := { F := _, coe := composition_series.series } instance [inhabited X] : inhabited (composition_series X) := ⟨{ length := 0, series := λ _, default X, step' := λ x, x.elim0 }⟩ variables {X} lemma step (s : composition_series X) : ∀ i : fin s.length, is_maximal (s i.cast_succ) (s i.succ) := s.step' @[simp] lemma coe_fn_mk (length : ℕ) (series step) : (@composition_series.mk X _ _ length series step : fin length.succ → X) = series := rfl theorem lt_succ (s : composition_series X) (i : fin s.length) : s i.cast_succ < s i.succ := lt_of_is_maximal (s.step _) protected theorem strict_mono (s : composition_series X) : strict_mono s := fin.strict_mono_iff_lt_succ.2 (λ i h, s.lt_succ ⟨i, nat.lt_of_succ_lt_succ h⟩) protected theorem injective (s : composition_series X) : function.injective s := s.strict_mono.injective @[simp] protected theorem inj (s : composition_series X) {i j : fin s.length.succ} : s i = s j ↔ i = j := s.injective.eq_iff instance : has_mem X (composition_series X) := ⟨λ x s, x ∈ set.range s⟩ lemma mem_def {x : X} {s : composition_series X} : x ∈ s ↔ x ∈ set.range s := iff.rfl lemma total {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) : x ≤ y ∨ y ≤ x := begin rcases set.mem_range.1 hx with ⟨i, rfl⟩, rcases set.mem_range.1 hy with ⟨j, rfl⟩, rw [s.strict_mono.le_iff_le, s.strict_mono.le_iff_le], exact le_total i j end /-- The ordered `list X` of elements of a `composition_series X`. -/ def to_list (s : composition_series X) : list X := list.of_fn s /-- Two `composition_series` are equal if they are the same length and have the same `i`th element for every `i` -/ lemma ext_fun {s₁ s₂ : composition_series X} (hl : s₁.length = s₂.length) (h : ∀ i, s₁ i = s₂ (fin.cast (congr_arg nat.succ hl) i)) : s₁ = s₂ := begin cases s₁, cases s₂, dsimp at *, subst hl, simpa [function.funext_iff] using h end @[simp] lemma length_to_list (s : composition_series X) : s.to_list.length = s.length + 1 := by rw [to_list, list.length_of_fn] lemma to_list_ne_nil (s : composition_series X) : s.to_list ≠ [] := by rw [← list.length_pos_iff_ne_nil, length_to_list]; exact nat.succ_pos _ lemma to_list_injective : function.injective (@composition_series.to_list X _ _) := λ s₁ s₂ (h : list.of_fn s₁ = list.of_fn s₂), have h₁ : s₁.length = s₂.length, from nat.succ_injective ((list.length_of_fn s₁).symm.trans $ (congr_arg list.length h).trans $ list.length_of_fn s₂), have h₂ : ∀ i : fin s₁.length.succ, (s₁ i) = s₂ (fin.cast (congr_arg nat.succ h₁) i), begin assume i, rw [← list.nth_le_of_fn s₁ i, ← list.nth_le_of_fn s₂], simp [h] end, begin cases s₁, cases s₂, dsimp at *, subst h₁, simp only [heq_iff_eq, eq_self_iff_true, true_and], simp only [fin.cast_refl] at h₂, exact funext h₂ end lemma chain'_to_list (s : composition_series X) : list.chain' is_maximal s.to_list := list.chain'_iff_nth_le.2 begin assume i hi, simp only [to_list, list.nth_le_of_fn'], rw [length_to_list] at hi, exact s.step ⟨i, hi⟩ end lemma to_list_sorted (s : composition_series X) : s.to_list.sorted (<) := list.pairwise_iff_nth_le.2 (λ i j hi hij, begin dsimp [to_list], rw [list.nth_le_of_fn', list.nth_le_of_fn'], exact s.strict_mono hij end) lemma to_list_nodup (s : composition_series X) : s.to_list.nodup := list.nodup_iff_nth_le_inj.2 (λ i j hi hj, begin delta to_list, rw [list.nth_le_of_fn', list.nth_le_of_fn', s.injective.eq_iff, fin.ext_iff, fin.coe_mk, fin.coe_mk], exact id end) @[simp] lemma mem_to_list {s : composition_series X} {x : X} : x ∈ s.to_list ↔ x ∈ s := by rw [to_list, list.mem_of_fn, mem_def] /-- Make a `composition_series X` from the ordered list of its elements. -/ def of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : composition_series X := { length := l.length - 1, series := λ i, l.nth_le i begin conv_rhs { rw ← nat.sub_add_cancel (list.length_pos_of_ne_nil hl) }, exact i.2 end, step' := λ ⟨i, hi⟩, list.chain'_iff_nth_le.1 hc i hi } lemma length_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : (of_list l hl hc).length = l.length - 1 := rfl lemma of_list_to_list (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := begin refine ext_fun _ _, { rw [length_of_list, length_to_list, nat.succ_sub_one] }, { rintros ⟨i, hi⟩, dsimp [of_list, to_list], rw [list.nth_le_of_fn'] } end @[simp] lemma of_list_to_list' (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := of_list_to_list s @[simp] lemma to_list_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : to_list (of_list l hl hc) = l := begin refine list.ext_le _ _, { rw [length_to_list, length_of_list, nat.sub_add_cancel (list.length_pos_of_ne_nil hl)] }, { assume i hi hi', dsimp [of_list, to_list], rw [list.nth_le_of_fn'], refl } end /-- Two `composition_series` are equal if they have the same elements. See also `ext_fun`. -/ @[ext] lemma ext {s₁ s₂ : composition_series X} (h : ∀ x, x ∈ s₁ ↔ x ∈ s₂) : s₁ = s₂ := to_list_injective $ list.eq_of_perm_of_sorted (by classical; exact list.perm_of_nodup_nodup_to_finset_eq s₁.to_list_nodup s₂.to_list_nodup (finset.ext $ by simp *)) s₁.to_list_sorted s₂.to_list_sorted /-- The largest element of a `composition_series` -/ def top (s : composition_series X) : X := s (fin.last _) lemma top_mem (s : composition_series X) : s.top ∈ s := mem_def.2 (set.mem_range.2 ⟨fin.last _, rfl⟩) @[simp] lemma le_top {s : composition_series X} (i : fin (s.length + 1)) : s i ≤ s.top := s.strict_mono.monotone (fin.le_last _) lemma le_top_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : x ≤ s.top := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ le_top _ /-- The smallest element of a `composition_series` -/ def bot (s : composition_series X) : X := s 0 lemma bot_mem (s : composition_series X) : s.bot ∈ s := mem_def.2 (set.mem_range.2 ⟨0, rfl⟩) @[simp] lemma bot_le {s : composition_series X} (i : fin (s.length + 1)) : s.bot ≤ s i := s.strict_mono.monotone (fin.zero_le _) lemma bot_le_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : s.bot ≤ x := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ bot_le _ lemma length_pos_of_mem_ne {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : 0 < s.length := let ⟨i, hi⟩ := hx, ⟨j, hj⟩ := hy in have hij : i ≠ j, from mt s.inj.2 $ λ h, hxy (hi ▸ hj ▸ h), hij.lt_or_lt.elim (λ hij, (lt_of_le_of_lt (zero_le i) (lt_of_lt_of_le hij (nat.le_of_lt_succ j.2)))) (λ hji, (lt_of_le_of_lt (zero_le j) (lt_of_lt_of_le hji (nat.le_of_lt_succ i.2)))) lemma forall_mem_eq_of_length_eq_zero {s : composition_series X} (hs : s.length = 0) {x y} (hx : x ∈ s) (hy : y ∈ s) : x = y := by_contradiction (λ hxy, pos_iff_ne_zero.1 (length_pos_of_mem_ne hx hy hxy) hs) /-- Remove the largest element from a `composition_series`. If the series `s` has length zero, then `s.erase_top = s` -/ @[simps] def erase_top (s : composition_series X) : composition_series X := { length := s.length - 1, series := λ i, s ⟨i, lt_of_lt_of_le i.2 (nat.succ_le_succ (nat.sub_le_self _ _))⟩, step' := λ i, begin have := s.step ⟨i, lt_of_lt_of_le i.2 (nat.sub_le_self _ _)⟩, cases i, exact this end } lemma top_erase_top (s : composition_series X) : s.erase_top.top = s ⟨s.length - 1, lt_of_le_of_lt (nat.sub_le_self _ _) (nat.lt_succ_self _)⟩ := show s _ = s _, from congr_arg s begin ext, simp only [erase_top_length, fin.coe_last, fin.coe_cast_succ, fin.coe_of_nat_eq_mod, fin.coe_mk, coe_coe] end lemma erase_top_top_le (s : composition_series X) : s.erase_top.top ≤ s.top := by simp [erase_top, top, s.strict_mono.le_iff_le, fin.le_iff_coe_le_coe, nat.sub_le_self] @[simp] lemma bot_erase_top (s : composition_series X) : s.erase_top.bot = s.bot := rfl lemma mem_erase_top_of_ne_of_mem {s : composition_series X} {x : X} (hx : x ≠ s.top) (hxs : x ∈ s) : x ∈ s.erase_top := begin { rcases hxs with ⟨i, rfl⟩, have hi : (i : ℕ) < (s.length - 1).succ, { conv_rhs { rw [← nat.succ_sub (length_pos_of_mem_ne ⟨i, rfl⟩ s.top_mem hx), nat.succ_sub_one] }, exact lt_of_le_of_ne (nat.le_of_lt_succ i.2) (by simpa [top, s.inj, fin.ext_iff] using hx) }, refine ⟨i.cast_succ, _⟩, simp [fin.ext_iff, nat.mod_eq_of_lt hi] } end lemma mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) : x ∈ s.erase_top ↔ x ≠ s.top ∧ x ∈ s := begin simp only [mem_def], dsimp only [erase_top, coe_fn_mk], split, { rintros ⟨i, rfl⟩, have hi : (i : ℕ) < s.length, { conv_rhs { rw [← nat.succ_sub_one s.length, nat.succ_sub h] }, exact i.2 }, simp [top, fin.ext_iff, (ne_of_lt hi)] }, { intro h, exact mem_erase_top_of_ne_of_mem h.1 h.2 } end lemma lt_top_of_mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) (hx : x ∈ s.erase_top) : x < s.top := lt_of_le_of_ne (le_top_of_mem ((mem_erase_top h).1 hx).2) ((mem_erase_top h).1 hx).1 lemma is_maximal_erase_top_top {s : composition_series X} (h : 0 < s.length) : is_maximal s.erase_top.top s.top := have s.length - 1 + 1 = s.length, by conv_rhs { rw [← nat.succ_sub_one s.length] }; rw nat.succ_sub h, begin rw [top_erase_top, top], convert s.step ⟨s.length - 1, nat.sub_lt h zero_lt_one⟩; ext; simp [this] end lemma append_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := by { cases i, simp [fin.append, *] } lemma append_succ_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) (h : s₁ (fin.last _) = s₂ 0) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).succ = s₁ i.succ := begin cases i with i hi, simp only [fin.append, hi, fin.succ_mk, function.comp_app, fin.cast_succ_mk, fin.coe_mk, fin.cast_add_mk], split_ifs, { refl }, { have : i + 1 = s₁.length, from le_antisymm hi (le_of_not_gt h_1), calc s₂ ⟨i + 1 - s₁.length, by simp [this]⟩ = s₂ 0 : congr_arg s₂ (by simp [fin.ext_iff, this]) ... = s₁ (fin.last _) : h.symm ... = _ : congr_arg s₁ (by simp [fin.ext_iff, this]) } end lemma append_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := begin cases i, simp only [fin.append, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, nat.add_sub_cancel_left, dif_neg, fin.cast_succ_mk, not_false_iff, fin.coe_mk] end lemma append_succ_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).succ = s₂ i.succ := begin cases i with i hi, simp only [fin.append, add_assoc, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, nat.add_sub_cancel_left, fin.succ_mk, dif_neg, not_false_iff, fin.coe_mk] end /-- Append two composition series `s₁` and `s₂` such that the least element of `s₁` is the maximum element of `s₂`. -/ @[simps length] def append (s₁ s₂ : composition_series X) (h : s₁.top = s₂.bot) : composition_series X := { length := s₁.length + s₂.length, series := fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂, step' := λ i, begin refine fin.add_cases _ _ i, { intro i, rw [append_succ_cast_add_aux _ h, append_cast_add_aux], exact s₁.step i }, { intro i, rw [append_nat_add_aux, append_succ_nat_add_aux], exact s₂.step i } end } @[simp] lemma append_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := append_cast_add_aux i @[simp] lemma append_succ_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).succ = s₁ i.succ := append_succ_cast_add_aux i h @[simp] lemma append_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := append_nat_add_aux i @[simp] lemma append_succ_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).succ = s₂ i.succ := append_succ_nat_add_aux i /-- Add an element to the top of a `composition_series` -/ @[simps length] def snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : composition_series X := { length := s.length + 1, series := fin.snoc s x, step' := λ i, begin refine fin.last_cases _ _ i, { rwa [fin.snoc_cast_succ, fin.succ_last, fin.snoc_last, ← top] }, { intro i, rw [fin.snoc_cast_succ, ← fin.cast_succ_fin_succ, fin.snoc_cast_succ], exact s.step _ } end } @[simp] lemma top_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).top = x := fin.snoc_last _ _ @[simp] lemma snoc_last (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : snoc s x hsat (fin.last (s.length + 1)) = x := fin.snoc_last _ _ @[simp] lemma snoc_cast_succ (s : composition_series X) (x : X) (hsat : is_maximal s.top x) (i : fin (s.length + 1)) : snoc s x hsat (i.cast_succ) = s i := fin.snoc_cast_succ _ _ _ @[simp] lemma bot_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).bot = s.bot := by rw [bot, bot, ← fin.cast_succ_zero, snoc_cast_succ] lemma mem_snoc {s : composition_series X} {x y: X} {hsat : is_maximal s.top x} : y ∈ snoc s x hsat ↔ y ∈ s ∨ y = x := begin simp only [snoc, mem_def], split, { rintros ⟨i, rfl⟩, refine fin.last_cases _ (λ i, _) i, { right, simp }, { left, simp } }, { intro h, rcases h with ⟨i, rfl⟩ | rfl, { use i.cast_succ, simp }, { use (fin.last _), simp } } end lemma eq_snoc_erase_top {s : composition_series X} (h : 0 < s.length) : s = snoc (erase_top s) s.top (is_maximal_erase_top_top h) := begin ext x, simp [mem_snoc, mem_erase_top h], by_cases h : x = s.top; simp [*, s.top_mem] end @[simp] lemma snoc_erase_top_top {s : composition_series X} (h : is_maximal s.erase_top.top s.top) : s.erase_top.snoc s.top h = s := have h : 0 < s.length, from nat.pos_of_ne_zero begin assume hs, refine ne_of_gt (lt_of_is_maximal h) _, simp [top, fin.ext_iff, hs] end, (eq_snoc_erase_top h).symm /-- Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i) (s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` -/ def equivalent (s₁ s₂ : composition_series X) : Prop := ∃ f : fin s₁.length ≃ fin s₂.length, ∀ i : fin s₁.length, iso (s₁ i.cast_succ, s₁ i.succ) (s₂ (f i).cast_succ, s₂ (f i).succ) namespace equivalent @[refl] lemma refl (s : composition_series X) : equivalent s s := ⟨equiv.refl _, λ _, (s.step _).iso_refl⟩ @[symm] lemma symm {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : equivalent s₂ s₁ := ⟨h.some.symm, λ i, iso_symm (by simpa using h.some_spec (h.some.symm i))⟩ @[trans] lemma trans {s₁ s₂ s₃ : composition_series X} (h₁ : equivalent s₁ s₂) (h₂ : equivalent s₂ s₃) : equivalent s₁ s₃ := ⟨h₁.some.trans h₂.some, λ i, iso_trans (h₁.some_spec i) (h₂.some_spec (h₁.some i))⟩ lemma append {s₁ s₂ t₁ t₂ : composition_series X} (hs : s₁.top = s₂.bot) (ht : t₁.top = t₂.bot) (h₁ : equivalent s₁ t₁) (h₂ : equivalent s₂ t₂) : equivalent (append s₁ s₂ hs) (append t₁ t₂ ht) := let e : fin (s₁.length + s₂.length) ≃ fin (t₁.length + t₂.length) := calc fin (s₁.length + s₂.length) ≃ fin s₁.length ⊕ fin s₂.length : fin_sum_fin_equiv.symm ... ≃ fin t₁.length ⊕ fin t₂.length : equiv.sum_congr h₁.some h₂.some ... ≃ fin (t₁.length + t₂.length) : fin_sum_fin_equiv in ⟨e, begin assume i, refine fin.add_cases _ _ i, { assume i, simpa [top, bot] using h₁.some_spec i }, { assume i, simpa [top, bot] using h₂.some_spec i } end⟩ protected lemma snoc {s₁ s₂ : composition_series X} {x₁ x₂ : X} {hsat₁ : is_maximal s₁.top x₁} {hsat₂ : is_maximal s₂.top x₂} (hequiv : equivalent s₁ s₂) (htop : iso (s₁.top, x₁) (s₂.top, x₂)) : equivalent (s₁.snoc x₁ hsat₁) (s₂.snoc x₂ hsat₂) := let e : fin s₁.length.succ ≃ fin s₂.length.succ := calc fin (s₁.length + 1) ≃ option (fin s₁.length) : fin_succ_equiv_last ... ≃ option (fin s₂.length) : functor.map_equiv option hequiv.some ... ≃ fin (s₂.length + 1) : fin_succ_equiv_last.symm in ⟨e, λ i, begin refine fin.last_cases _ _ i, { simpa [top] using htop }, { assume i, simpa [fin.succ_cast_succ] using hequiv.some_spec i } end⟩ lemma length_eq {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : s₁.length = s₂.length := by simpa using fintype.card_congr h.some lemma snoc_snoc_swap {s : composition_series X} {x₁ x₂ y₁ y₂ : X} {hsat₁ : is_maximal s.top x₁} {hsat₂ : is_maximal s.top x₂} {hsaty₁ : is_maximal (snoc s x₁ hsat₁).top y₁} {hsaty₂ : is_maximal (snoc s x₂ hsat₂).top y₂} (hr₁ : iso (s.top, x₁) (x₂, y₂)) (hr₂ : iso (x₁, y₁) (s.top, x₂)) : equivalent (snoc (snoc s x₁ hsat₁) y₁ hsaty₁) (snoc (snoc s x₂ hsat₂) y₂ hsaty₂) := let e : fin (s.length + 1 + 1) ≃ fin (s.length + 1 + 1) := equiv.swap (fin.last _) (fin.cast_succ (fin.last _)) in have h1 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _).cast_succ, from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), have h2 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _), from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), ⟨e, begin intro i, dsimp only [e], refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_left, snoc_cast_succ, snoc_last, fin.succ_last, snoc_last, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last], exact hr₂ }, { refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_right, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last, snoc_last, fin.succ_last, snoc_last], exact hr₁ }, { erw [equiv.swap_apply_of_ne_of_ne h2 h1, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ], exact (s.step i).iso_refl } } end⟩ end equivalent lemma length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁ : s₁.length = 0) : s₂.length = 0 := begin have : s₁.bot = s₁.top, from congr_arg s₁ (fin.ext (by simp [hs₁])), have : (fin.last s₂.length) = (0 : fin s₂.length.succ), from s₂.injective (hb.symm.trans (this.trans ht)).symm, simpa [fin.ext_iff] end lemma length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : 0 < s₁.length → 0 < s₂.length := not_imp_not.1 begin simp only [pos_iff_ne_zero, ne.def, not_iff_not, not_not], exact length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb.symm ht.symm end lemma eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁0 : s₁.length = 0) : s₁ = s₂ := have ∀ x, x ∈ s₁ ↔ x = s₁.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero hs₁0 hx s₁.top_mem, λ hx, hx.symm ▸ s₁.top_mem⟩, have ∀ x, x ∈ s₂ ↔ x = s₂.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero (length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hs₁0) hx s₂.top_mem, λ hx, hx.symm ▸ s₂.top_mem⟩, by { ext, simp * } /-- Given a `composition_series`, `s`, and an element `x` such that `x` is maximal inside `s.top` there is a series, `t`, such that `t.top = x`, `t.bot = s.bot` and `snoc t s.top _` is equivalent to `s`. -/ lemma exists_top_eq_snoc_equivalant (s : composition_series X) (x : X) (hm : is_maximal x s.top) (hb : s.bot ≤ x) : ∃ t : composition_series X, t.bot = s.bot ∧ t.length + 1 = s.length ∧ ∃ htx : t.top = x, equivalent s (snoc t s.top (htx.symm ▸ hm)) := begin induction hn : s.length with n ih generalizing s x, { exact (ne_of_gt (lt_of_le_of_lt hb (lt_of_is_maximal hm)) (forall_mem_eq_of_length_eq_zero hn s.top_mem s.bot_mem)).elim }, { have h0s : 0 < s.length, from hn.symm ▸ nat.succ_pos _, by_cases hetx : s.erase_top.top = x, { use s.erase_top, simp [← hetx, hn] }, { have imxs : is_maximal (x ⊓ s.erase_top.top) s.erase_top.top, from is_maximal_of_eq_inf x s.top rfl (ne.symm hetx) hm (is_maximal_erase_top_top h0s), have := ih _ _ imxs (le_inf (by simpa) (le_top_of_mem s.erase_top.bot_mem)) (by simp [hn]), rcases this with ⟨t, htb, htl, htt, hteqv⟩, have hmtx : is_maximal t.top x, from is_maximal_of_eq_inf s.erase_top.top s.top (by rw [inf_comm, htt]) hetx (is_maximal_erase_top_top h0s) hm, use snoc t x hmtx, refine ⟨by simp [htb], by simp [htl], by simp, _⟩, have : s.equivalent ((snoc t s.erase_top.top (htt.symm ▸ imxs)).snoc s.top (by simpa using is_maximal_erase_top_top h0s)), { conv_lhs { rw eq_snoc_erase_top h0s }, exact equivalent.snoc hteqv (by simpa using (is_maximal_erase_top_top h0s).iso_refl) }, refine this.trans _, refine equivalent.snoc_snoc_swap _ _, { exact iso_symm (second_iso_of_eq hm (sup_eq_of_is_maximal hm (is_maximal_erase_top_top h0s) (ne.symm hetx)) htt.symm) }, { exact second_iso_of_eq (is_maximal_erase_top_top h0s) (sup_eq_of_is_maximal (is_maximal_erase_top_top h0s) hm hetx) (by rw [inf_comm, htt]) } } } end /-- The **Jordan-Hölder** theorem, stated for any `jordan_holder_lattice`. If two composition series start and finish at the same place, they are equivalent. -/ theorem jordan_holder (s₁ s₂ : composition_series X) (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : equivalent s₁ s₂ := begin induction hle : s₁.length with n ih generalizing s₁ s₂, { rw [eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hle] }, { have h0s₂ : 0 < s₂.length, from length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos hb ht (hle.symm ▸ nat.succ_pos _), rcases exists_top_eq_snoc_equivalant s₁ s₂.erase_top.top (ht.symm ▸ is_maximal_erase_top_top h0s₂) (hb.symm ▸ s₂.bot_erase_top ▸ bot_le_of_mem (top_mem _)) with ⟨t, htb, htl, htt, hteq⟩, have := ih t s₂.erase_top (by simp [htb, ← hb]) htt (nat.succ_inj'.1 (htl.trans hle)), refine hteq.trans _, conv_rhs { rw [eq_snoc_erase_top h0s₂] }, simp only [ht], exact equivalent.snoc this (by simp [htt, (is_maximal_erase_top_top h0s₂).iso_refl]) } end end composition_series
aa9c326acfad13185763398196334203e254d1f2
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Data/Format.lean
f65a5a7ff26457e477ef72ff730c08837657ed1a
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,832
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Data.Options universes u v namespace Lean inductive Format | nil : Format | line : Format | text : String → Format | nest (indent : Nat) : Format → Format | compose (flattened : Bool) : Format → Format → Format | choice : Format → Format → Format namespace Format @[export lean_format_append] protected def append (a b : Format) : Format := compose false a b instance : HasAppend Format := ⟨Format.append⟩ instance : HasCoe String Format := ⟨text⟩ instance : Inhabited Format := ⟨nil⟩ def join (xs : List Format) : Format := xs.foldl HasAppend.append "" def isNil : Format → Bool | nil => true | _ => false def flatten : Format → Format | nil => nil | line => text " " | f@(text _) => f | nest _ f => flatten f | choice f _ => flatten f | f@(compose true _ _) => f | f@(compose false f₁ f₂) => compose true (flatten f₁) (flatten f₂) @[export lean_format_group] def group : Format → Format | nil => nil | f@(text _) => f | f@(compose true _ _) => f | f => choice (flatten f) f structure SpaceResult := (found := false) (exceeded := false) (space := 0) @[inline] private def merge (w : Nat) (r₁ : SpaceResult) (r₂ : Thunk SpaceResult) : SpaceResult := if r₁.exceeded || r₁.found then r₁ else let y := r₂.get; if y.exceeded || y.found then y else let newSpace := r₁.space + y.space; { space := newSpace, exceeded := newSpace > w } def spaceUptoLine : Format → Nat → SpaceResult | nil, w => {} | line, w => { found := true } | text s, w => { space := s.length, exceeded := s.length > w } | compose _ f₁ f₂, w => merge w (spaceUptoLine f₁ w) (spaceUptoLine f₂ w) | nest _ f, w => spaceUptoLine f w | choice f₁ f₂, w => spaceUptoLine f₂ w def spaceUptoLine' : List (Nat × Format) → Nat → SpaceResult | [], w => {} | p::ps, w => merge w (spaceUptoLine p.2 w) (spaceUptoLine' ps w) partial def be : Nat → Nat → String → List (Nat × Format) → String | w, k, out, [] => out | w, k, out, (i, nil)::z => be w k out z | w, k, out, (i, (compose _ f₁ f₂))::z => be w k out ((i, f₁)::(i, f₂)::z) | w, k, out, (i, (nest n f))::z => be w k out ((i+n, f)::z) | w, k, out, (i, text s)::z => be w (k + s.length) (out ++ s) z | w, k, out, (i, line)::z => be w i ((out ++ "\n").pushn ' ' i) z | w, k, out, (i, choice f₁ f₂)::z => let r := merge w (spaceUptoLine f₁ w) (spaceUptoLine' z w); if r.exceeded then be w k out ((i, f₂)::z) else be w k out ((i, f₁)::z) @[inline] def bracket (l : String) (f : Format) (r : String) : Format := group (nest l.length $ l ++ f ++ r) @[inline] def paren (f : Format) : Format := bracket "(" f ")" @[inline] def sbracket (f : Format) : Format := bracket "[" f "]" def defIndent := 2 def defUnicode := true def defWidth := 120 def getWidth (o : Options) : Nat := o.get `format.width defWidth def getIndent (o : Options) : Nat := o.get `format.indent defIndent def getUnicode (o : Options) : Bool := o.get `format.unicode defUnicode @[init] def indentOption : IO Unit := registerOption `format.indent { defValue := defIndent, group := "format", descr := "indentation" } @[init] def unicodeOption : IO Unit := registerOption `format.unicode { defValue := defUnicode, group := "format", descr := "unicode characters" } @[init] def widthOption : IO Unit := registerOption `format.width { defValue := defWidth, group := "format", descr := "line width" } @[export lean_format_pretty] def prettyAux (f : Format) (w : Nat := defWidth) : String := be w 0 "" [(0, f)] def pretty (f : Format) (o : Options := {}) : String := prettyAux f (getWidth o) end Format open Lean.Format class HasFormat (α : Type u) := (format : α → Format) export Lean.HasFormat (format) def fmt {α : Type u} [HasFormat α] : α → Format := format instance toStringToFormat {α : Type u} [HasToString α] : HasFormat α := ⟨text ∘ toString⟩ -- note: must take precendence over the above instance to avoid premature formatting instance formatHasFormat : HasFormat Format := ⟨id⟩ instance stringHasFormat : HasFormat String := ⟨Format.text⟩ def Format.joinSep {α : Type u} [HasFormat α] : List α → Format → Format | [], sep => nil | [a], sep => format a | a::as, sep => format a ++ sep ++ Format.joinSep as sep def Format.prefixJoin {α : Type u} [HasFormat α] (pre : Format) : List α → Format | [] => nil | a::as => pre ++ format a ++ Format.prefixJoin as def Format.joinSuffix {α : Type u} [HasFormat α] : List α → Format → Format | [], suffix => nil | a::as, suffix => format a ++ suffix ++ Format.joinSuffix as suffix def List.format {α : Type u} [HasFormat α] : List α → Format | [] => "[]" | xs => sbracket $ Format.joinSep xs ("," ++ line) instance listHasFormat {α : Type u} [HasFormat α] : HasFormat (List α) := ⟨List.format⟩ instance arrayHasFormat {α : Type u} [HasFormat α] : HasFormat (Array α) := ⟨fun a => "#" ++ fmt a.toList⟩ def Option.format {α : Type u} [HasFormat α] : Option α → Format | none => "none" | some a => "some " ++ fmt a instance optionHasFormat {α : Type u} [HasFormat α] : HasFormat (Option α) := ⟨Option.format⟩ instance prodHasFormat {α : Type u} {β : Type v} [HasFormat α] [HasFormat β] : HasFormat (Prod α β) := ⟨fun ⟨a, b⟩ => paren $ format a ++ "," ++ line ++ format b⟩ def Format.joinArraySep {α : Type u} [HasFormat α] (a : Array α) (sep : Format) : Format := a.iterate nil (fun i a r => if i.val > 0 then r ++ sep ++ format a else r ++ format a) instance natHasFormat : HasFormat Nat := ⟨fun n => toString n⟩ instance uint16HasFormat : HasFormat UInt16 := ⟨fun n => toString n⟩ instance uint32HasFormat : HasFormat UInt32 := ⟨fun n => toString n⟩ instance uint64HasFormat : HasFormat UInt64 := ⟨fun n => toString n⟩ instance usizeHasFormat : HasFormat USize := ⟨fun n => toString n⟩ instance nameHasFormat : HasFormat Name := ⟨fun n => n.toString⟩ protected def Format.repr : Format → Format | nil => "Format.nil" | line => "Format.line" | text s => paren $ "Format.text" ++ line ++ repr s | nest n f => paren $ "Format.nest" ++ line ++ repr n ++ line ++ Format.repr f | compose b f₁ f₂ => paren $ "Format.compose " ++ repr b ++ line ++ Format.repr f₁ ++ line ++ Format.repr f₂ | choice f₁ f₂ => paren $ "Format.choice" ++ line ++ Format.repr f₁ ++ line ++ Format.repr f₂ instance formatHasToString : HasToString Format := ⟨Format.pretty⟩ instance : HasRepr Format := ⟨Format.pretty ∘ Format.repr⟩ def formatDataValue : DataValue → Format | DataValue.ofString v => format (repr v) | DataValue.ofBool v => format v | DataValue.ofName v => "`" ++ format v | DataValue.ofNat v => format v | DataValue.ofInt v => format v instance dataValueHasFormat : HasFormat DataValue := ⟨formatDataValue⟩ def formatEntry : Name × DataValue → Format | (n, v) => format n ++ " := " ++ format v instance entryHasFormat : HasFormat (Name × DataValue) := ⟨formatEntry⟩ def formatKVMap (m : KVMap) : Format := sbracket (Format.joinSep m.entries ", ") instance kvMapHasFormat : HasFormat KVMap := ⟨formatKVMap⟩ end Lean def String.toFormat (s : String) : Lean.Format := Lean.Format.joinSep (s.splitOn "\n") Lean.Format.line
9717a35b21e1767ae5eec44ffa8afdfc1ce3b615
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/category/CommRing/limits.lean
d31664d21a99b600e6ffc6ac28fafccb9ac31d57
[ "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
15,387
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.ring.pi import algebra.category.CommRing.basic import algebra.category.Group.limits import ring_theory.subring /-! # The category of (commutative) rings has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ /- We use the following trick a lot of times in this file.-/ /-- Some definitions may be extremely slow to elaborate, when the target type to be constructed is complicated and when the type of the term given in the definition is also complicated and does not obviously match the target type. In this case, instead of just giving the term, prefixing it with `by apply` may speed up things considerably as the types are not elaborated in the same order. -/ library_note "change elaboration strategy with `by apply`" open category_theory open category_theory.limits universe u noncomputable theory namespace SemiRing variables {J : Type u} [small_category J] instance semiring_obj (F : J ⥤ SemiRing) (j) : semiring ((F ⋙ forget SemiRing).obj j) := by { change semiring (F.obj j), apply_instance } /-- The flat sections of a functor into `SemiRing` form a subsemiring of all sections. -/ def sections_subsemiring (F : J ⥤ SemiRing) : subsemiring (Π j, F.obj j) := { carrier := (F ⋙ forget SemiRing).sections, ..(AddMon.sections_add_submonoid (F ⋙ forget₂ SemiRing AddCommMon ⋙ forget₂ AddCommMon AddMon)), ..(Mon.sections_submonoid (F ⋙ forget₂ SemiRing Mon)) } instance limit_semiring (F : J ⥤ SemiRing) : semiring (types.limit_cone (F ⋙ forget SemiRing.{u})).X := (sections_subsemiring F).to_semiring /-- `limit.π (F ⋙ forget SemiRing) j` as a `ring_hom`. -/ def limit_π_ring_hom (F : J ⥤ SemiRing.{u}) (j) : (types.limit_cone (F ⋙ forget SemiRing)).X →+* (F ⋙ forget SemiRing).obj j := { to_fun := (types.limit_cone (F ⋙ forget SemiRing)).π.app j, ..AddMon.limit_π_add_monoid_hom (F ⋙ forget₂ SemiRing AddCommMon.{u} ⋙ forget₂ AddCommMon AddMon) j, ..Mon.limit_π_monoid_hom (F ⋙ forget₂ SemiRing Mon) j, } namespace has_limits -- The next two definitions are used in the construction of `has_limits SemiRing`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `SemiRing`. (Internal use only; use the limits API.) -/ def limit_cone (F : J ⥤ SemiRing) : cone F := { X := SemiRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := limit_π_ring_hom F, naturality' := λ j j' f, ring_hom.coe_inj ((types.limit_cone (F ⋙ forget _)).π.naturality f) } } /-- Witness that the limit cone in `SemiRing` is a limit cone. (Internal use only; use the limits API.) -/ def limit_cone_is_limit (F : J ⥤ SemiRing) : is_limit (limit_cone F) := begin refine is_limit.of_faithful (forget SemiRing) (types.limit_cone_is_limit _) (λ s, ⟨_, _, _, _, _⟩) (λ s, rfl); tidy end end has_limits open has_limits /-- The category of rings has all limits. -/ @[irreducible] instance has_limits : has_limits SemiRing := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommMon_preserves_limits_aux (F : J ⥤ SemiRing) : is_limit ((forget₂ SemiRing AddCommMon).map_cone (limit_cone F)) := by apply AddCommMon.limit_cone_is_limit (F ⋙ forget₂ SemiRing AddCommMon) /-- The forgetful functor from semirings to additive commutative monoids preserves all limits. -/ instance forget₂_AddCommMon_preserves_limits : preserves_limits (forget₂ SemiRing AddCommMon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommMon_preserves_limits_aux F) } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_Mon_preserves_limits_aux (F : J ⥤ SemiRing) : is_limit ((forget₂ SemiRing Mon).map_cone (limit_cone F)) := by apply Mon.has_limits.limit_cone_is_limit (F ⋙ forget₂ SemiRing Mon) /-- The forgetful functor from semirings to monoids preserves all limits. -/ instance forget₂_Mon_preserves_limits : preserves_limits (forget₂ SemiRing Mon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_Mon_preserves_limits_aux F) } } /-- The forgetful functor from semirings to types preserves all limits. -/ instance forget_preserves_limits : preserves_limits (forget SemiRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (types.limit_cone_is_limit (F ⋙ forget _)) } } end SemiRing namespace CommSemiRing variables {J : Type u} [small_category J] instance comm_semiring_obj (F : J ⥤ CommSemiRing) (j) : comm_semiring ((F ⋙ forget CommSemiRing).obj j) := by { change comm_semiring (F.obj j), apply_instance } instance limit_comm_semiring (F : J ⥤ CommSemiRing) : comm_semiring (types.limit_cone (F ⋙ forget CommSemiRing.{u})).X := @subsemiring.to_comm_semiring (Π j, F.obj j) _ (SemiRing.sections_subsemiring (F ⋙ forget₂ CommSemiRing SemiRing.{u})) /-- We show that the forgetful functor `CommSemiRing ⥤ SemiRing` creates limits. All we need to do is notice that the limit point has a `comm_semiring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ CommSemiRing) : creates_limit F (forget₂ CommSemiRing SemiRing.{u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommSemiRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := by apply SemiRing.limit_π_ring_hom (F ⋙ forget₂ CommSemiRing SemiRing), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ _)).π.naturality, } }, valid_lift := by apply is_limit.unique_up_to_iso (SemiRing.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ CommSemiRing SemiRing.{u}) (by apply SemiRing.has_limits.limit_cone_is_limit _) (λ s, (SemiRing.has_limits.limit_cone_is_limit _).lift ((forget₂ _ SemiRing).map_cone s)) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommSemiRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ CommSemiRing) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommSemiRing SemiRing.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ CommSemiRing) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of rings has all limits. -/ @[irreducible] instance has_limits : has_limits CommSemiRing.{u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommSemiRing SemiRing.{u}) } } /-- The forgetful functor from rings to semirings preserves all limits. -/ instance forget₂_SemiRing_preserves_limits : preserves_limits (forget₂ CommSemiRing SemiRing) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget CommSemiRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommSemiRing SemiRing) (forget SemiRing) } } end CommSemiRing namespace Ring variables {J : Type u} [small_category J] instance ring_obj (F : J ⥤ Ring) (j) : ring ((F ⋙ forget Ring).obj j) := by { change ring (F.obj j), apply_instance } /-- The flat sections of a functor into `Ring` form a subring of all sections. -/ def sections_subring (F : J ⥤ Ring) : subring (Π j, F.obj j) := { carrier := (F ⋙ forget Ring).sections, .. AddGroup.sections_add_subgroup (F ⋙ forget₂ Ring AddCommGroup ⋙ forget₂ AddCommGroup AddGroup), .. SemiRing.sections_subsemiring (F ⋙ forget₂ Ring SemiRing) } instance limit_ring (F : J ⥤ Ring) : ring (types.limit_cone (F ⋙ forget Ring.{u})).X := (sections_subring F).to_ring /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `ring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ Ring) : creates_limit F (forget₂ Ring SemiRing.{u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := Ring.of (types.limit_cone (F ⋙ forget _)).X, π := { app := by apply SemiRing.limit_π_ring_hom (F ⋙ forget₂ Ring SemiRing), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ _)).π.naturality, } }, valid_lift := by apply is_limit.unique_up_to_iso (SemiRing.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ Ring SemiRing.{u}) (by apply SemiRing.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `Ring`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ Ring) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ Ring SemiRing.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ Ring) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of rings has all limits. -/ @[irreducible] instance has_limits : has_limits Ring := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ Ring SemiRing) } } /-- The forgetful functor from rings to semirings preserves all limits. -/ instance forget₂_SemiRing_preserves_limits : preserves_limits (forget₂ Ring SemiRing) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommGroup_preserves_limits_aux (F : J ⥤ Ring) : is_limit ((forget₂ Ring AddCommGroup).map_cone (limit_cone F)) := by apply AddCommGroup.limit_cone_is_limit (F ⋙ forget₂ Ring AddCommGroup) /-- The forgetful functor from rings to additive commutative groups preserves all limits. -/ instance forget₂_AddCommGroup_preserves_limits : preserves_limits (forget₂ Ring AddCommGroup) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommGroup_preserves_limits_aux F) } } /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget Ring) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ Ring SemiRing) (forget SemiRing) } } end Ring namespace CommRing variables {J : Type u} [small_category J] instance comm_ring_obj (F : J ⥤ CommRing) (j) : comm_ring ((F ⋙ forget CommRing).obj j) := by { change comm_ring (F.obj j), apply_instance } instance limit_comm_ring (F : J ⥤ CommRing) : comm_ring (types.limit_cone (F ⋙ forget CommRing.{u})).X := @subring.to_comm_ring (Π j, F.obj j) _ (Ring.sections_subring (F ⋙ forget₂ CommRing Ring.{u})) /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `comm_ring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ CommRing) : creates_limit F (forget₂ CommRing Ring.{u}) := /- A terse solution here would be ``` creates_limit_of_fully_faithful_of_iso (CommRing.of (limit (F ⋙ forget _))) (iso.refl _) ``` but it seems this would introduce additional identity morphisms in `limit.π`. -/ creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := by apply SemiRing.limit_π_ring_hom (F ⋙ forget₂ CommRing Ring.{u} ⋙ forget₂ Ring SemiRing), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ Ring.{u} ⋙ forget₂ _ SemiRing)).π.naturality } }, valid_lift := by apply is_limit.unique_up_to_iso (Ring.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ _ Ring.{u}) (by apply Ring.limit_cone_is_limit (F ⋙ forget₂ CommRing Ring)) (λ s, (Ring.limit_cone_is_limit _).lift ((forget₂ _ Ring.{u}).map_cone s)) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ CommRing) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommRing Ring.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ CommRing) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of commutative rings has all limits. -/ @[irreducible] instance has_limits : has_limits CommRing.{u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommRing Ring.{u}) } } /-- The forgetful functor from commutative rings to rings preserves all limits. (That is, the underlying rings could have been computed instead as limits in the category of rings.) -/ instance forget₂_Ring_preserves_limits : preserves_limits (forget₂ CommRing Ring) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_CommSemiRing_preserves_limits_aux (F : J ⥤ CommRing) : is_limit ((forget₂ CommRing CommSemiRing).map_cone (limit_cone F)) := by apply CommSemiRing.limit_cone_is_limit (F ⋙ forget₂ CommRing CommSemiRing) /-- The forgetful functor from commutative rings to commutative semirings preserves all limits. (That is, the underlying commutative semirings could have been computed instead as limits in the category of commutative semirings.) -/ instance forget₂_CommSemiRing_preserves_limits : preserves_limits (forget₂ CommRing CommSemiRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_CommSemiRing_preserves_limits_aux F) } } /-- The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget CommRing) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommRing Ring) (forget Ring) } } end CommRing
9beef6b889be650be1a506456d72e1141448389f
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/meta3.lean
d36a03fe0e37746a6ee7033f0c13c55ad104080f
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,856
lean
import Lean.Meta new_frontend open Lean open Lean.Meta def dbgOpt : Options := let opt : Options := {}; let opt := opt.setBool `trace.Meta true; -- let opt := opt.setBool `trace.Meta.check false; opt def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def check (x : MetaM Bool) : MetaM Unit := unlessM x $ throwError "check failed" def getAssignment (m : Expr) : MetaM Expr := do let v? ← getExprMVarAssignment? m.mvarId!; (match v? with | some v => pure v | none => throwError "metavariable is not assigned") unsafe def run (mods : List Name) (x : MetaM Unit) (opts : Options := dbgOpt) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do let x : MetaM Unit := do { x; printTraces }; x.toIO { options := opts } { env := env }; pure () def nat := mkConst `Nat def succ := mkConst `Nat.succ def add := mkAppN (mkConst `HasAdd.add [levelZero]) #[nat, mkConst `Nat.HasAdd] def tst1 : MetaM Unit := do let d : DiscrTree Nat := {}; let mvar ← mkFreshExprMVar nat; let d ← d.insert (mkAppN add #[mvar, mkNatLit 10]) 1; let d ← d.insert (mkAppN add #[mkNatLit 0, mkNatLit 10]) 2; let d ← d.insert (mkAppN (mkConst `Nat.add) #[mkNatLit 0, mkNatLit 20]) 3; let d ← d.insert (mkAppN add #[mvar, mkNatLit 20]) 4; let d ← d.insert mvar 5; print (format d); let vs ← d.getMatch (mkAppN add #[mkNatLit 1, mkNatLit 10]); print (format vs); let t := mkAppN add #[mvar, mvar]; print t; let vs ← d.getMatch t; print (format vs); let vs ← d.getUnify t; print (format vs); let vs ← d.getUnify mvar; print (format vs); let vs ← d.getUnify $ mkAppN add #[mkNatLit 0, mvar]; print (format vs); let vs ← d.getUnify $ mkAppN add #[mvar, mkNatLit 20]; print (format vs); pure () #eval run [`Init.Data.Nat] tst1
5753aa7997e07cc939381002ec44e8a2741ec546
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/filter/extr.lean
764807b64c307c98408955eaf4830271d8755c62
[]
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
33,221
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.filter.basic import Mathlib.PostPort universes u v w x u_1 u_2 namespace Mathlib /-! # Minimum and maximum w.r.t. a filter and on a aet ## Main Definitions This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`, and `B` is `filter` or `on`. * `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`; * `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`; * `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`. Similar predicates with `_on` suffix are particular cases for `l = 𝓟 s`. ## Main statements ### Change of the filter (set) argument * `is_*_filter.filter_mono` : replace the filter with a smaller one; * `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`; * `is_*_on.on_subset` : restrict to a smaller set; * `is_*_on.inter` : replace a set `s` wtih `s ∩ t`. ### Composition * `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function, then `x` is an extremum for `g ∘ f`; * `is_*_*.comp_antimono` : similarly for the case of monotonically decreasing `g`; * `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g` and a binary operation `op` is monotone in both arguments, then `x` is an extremum of the same type for `λ x, op (f x) (g x)`. * `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`, then `x` is an extremum for `f ∘ g` w.r.t. `l`. * `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum for `f ∘ g` on `g ⁻¹' s`. ### Algebraic operations * `is_*_*.add` : if `x` is an extremum of the same type for two functions, then it is an extremum of the same type for their sum; * `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum of the opposite type for `-f`; * `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`, then it is a minimum for `f - g` and a maximum for `g - f`; * `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add` for pointwise `max`, `min`, `sup`, `inf`, respectively. ### Miscellaneous definitions * `is_*_*_const` : any point is both a minimum and maximum for a constant function; * `is_min/max_*.is_ext` : any minimum/maximum point is an extremum; * `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`; ## Missing features (TODO) * Multiplication and division; * `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point of view, `is_*_*.bicomp` is a composition * It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono` based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta` list of known (anti)monotone (binary) functions with their names, as well as a list of special types of filters, and define the missing lemmas once one of these two lists grows. -/ /-! ### Definitions -/ /-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/ def is_min_filter {α : Type u} {β : Type v} [preorder β] (f : α → β) (l : filter α) (a : α) := filter.eventually (fun (x : α) => f a ≤ f x) l /-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/ def is_max_filter {α : Type u} {β : Type v} [preorder β] (f : α → β) (l : filter α) (a : α) := filter.eventually (fun (x : α) => f x ≤ f a) l /-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/ def is_extr_filter {α : Type u} {β : Type v} [preorder β] (f : α → β) (l : filter α) (a : α) := is_min_filter f l a ∨ is_max_filter f l a /-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_min_on {α : Type u} {β : Type v} [preorder β] (f : α → β) (s : set α) (a : α) := is_min_filter f (filter.principal s) a /-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_max_on {α : Type u} {β : Type v} [preorder β] (f : α → β) (s : set α) (a : α) := is_max_filter f (filter.principal s) a /-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/ def is_extr_on {α : Type u} {β : Type v} [preorder β] (f : α → β) (s : set α) (a : α) := is_extr_filter f (filter.principal s) a theorem is_extr_on.elim {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} {p : Prop} : is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p := or.elim theorem is_min_on_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_min_on f s a ↔ ∀ (x : α), x ∈ s → f a ≤ f x := iff.rfl theorem is_max_on_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_max_on f s a ↔ ∀ (x : α), x ∈ s → f x ≤ f a := iff.rfl theorem is_min_on_univ_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {a : α} : is_min_on f set.univ a ↔ ∀ (x : α), f a ≤ f x := iff.trans set.univ_subset_iff set.eq_univ_iff_forall theorem is_max_on_univ_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {a : α} : is_max_on f set.univ a ↔ ∀ (x : α), f x ≤ f a := iff.trans set.univ_subset_iff set.eq_univ_iff_forall /-! ### Conversion to `is_extr_*` -/ theorem is_min_filter.is_extr {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_min_filter f l a → is_extr_filter f l a := Or.inl theorem is_max_filter.is_extr {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_max_filter f l a → is_extr_filter f l a := Or.inr theorem is_min_on.is_extr {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} (h : is_min_on f s a) : is_extr_on f s a := is_min_filter.is_extr h theorem is_max_on.is_extr {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} (h : is_max_on f s a) : is_extr_on f s a := is_max_filter.is_extr h /-! ### Constant function -/ theorem is_min_filter_const {α : Type u} {β : Type v} [preorder β] {l : filter α} {a : α} {b : β} : is_min_filter (fun (_x : α) => b) l a := filter.univ_mem_sets' fun (_x : α) => le_refl ((fun (_x : α) => b) a) theorem is_max_filter_const {α : Type u} {β : Type v} [preorder β] {l : filter α} {a : α} {b : β} : is_max_filter (fun (_x : α) => b) l a := filter.univ_mem_sets' fun (_x : α) => le_refl ((fun (_x : α) => b) _x) theorem is_extr_filter_const {α : Type u} {β : Type v} [preorder β] {l : filter α} {a : α} {b : β} : is_extr_filter (fun (_x : α) => b) l a := is_min_filter.is_extr is_min_filter_const theorem is_min_on_const {α : Type u} {β : Type v} [preorder β] {s : set α} {a : α} {b : β} : is_min_on (fun (_x : α) => b) s a := is_min_filter_const theorem is_max_on_const {α : Type u} {β : Type v} [preorder β] {s : set α} {a : α} {b : β} : is_max_on (fun (_x : α) => b) s a := is_max_filter_const theorem is_extr_on_const {α : Type u} {β : Type v} [preorder β] {s : set α} {a : α} {b : β} : is_extr_on (fun (_x : α) => b) s a := is_extr_filter_const /-! ### Order dual -/ theorem is_min_filter_dual_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_min_filter f l a ↔ is_max_filter f l a := iff.rfl theorem is_max_filter_dual_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_max_filter f l a ↔ is_min_filter f l a := iff.rfl theorem is_extr_filter_dual_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_extr_filter f l a ↔ is_extr_filter f l a := or_comm (is_min_filter f l a) (is_max_filter f l a) theorem is_max_filter.dual {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_max_filter f l a → is_min_filter f l a := iff.mpr is_min_filter_dual_iff theorem is_max_filter.undual {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_max_filter f l a → is_min_filter f l a := iff.mp is_max_filter_dual_iff theorem is_extr_filter.dual {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} : is_extr_filter f l a → is_extr_filter f l a := iff.mpr is_extr_filter_dual_iff theorem is_min_on_dual_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_min_on f s a ↔ is_max_on f s a := iff.rfl theorem is_max_on_dual_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_max_on f s a ↔ is_min_on f s a := iff.rfl theorem is_extr_on_dual_iff {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_extr_on f s a ↔ is_extr_on f s a := or_comm (is_min_filter f (filter.principal s) a) (is_max_filter f (filter.principal s) a) theorem is_max_on.dual {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_max_on f s a → is_min_on f s a := iff.mpr is_min_on_dual_iff theorem is_min_on.dual {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_min_on f s a → is_max_on f s a := iff.mpr is_max_on_dual_iff theorem is_extr_on.dual {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} : is_extr_on f s a → is_extr_on f s a := iff.mpr is_extr_on_dual_iff /-! ### Operations on the filter/set -/ theorem is_min_filter.filter_mono {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} {l' : filter α} (h : is_min_filter f l a) (hl : l' ≤ l) : is_min_filter f l' a := hl h theorem is_max_filter.filter_mono {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} {l' : filter α} (h : is_max_filter f l a) (hl : l' ≤ l) : is_max_filter f l' a := hl h theorem is_extr_filter.filter_mono {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} {l' : filter α} (h : is_extr_filter f l a) (hl : l' ≤ l) : is_extr_filter f l' a := or.elim h (fun (h : is_min_filter f l a) => is_min_filter.is_extr (is_min_filter.filter_mono h hl)) fun (h : is_max_filter f l a) => is_max_filter.is_extr (is_max_filter.filter_mono h hl) theorem is_min_filter.filter_inf {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} (h : is_min_filter f l a) (l' : filter α) : is_min_filter f (l ⊓ l') a := is_min_filter.filter_mono h inf_le_left theorem is_max_filter.filter_inf {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} (h : is_max_filter f l a) (l' : filter α) : is_max_filter f (l ⊓ l') a := is_max_filter.filter_mono h inf_le_left theorem is_extr_filter.filter_inf {α : Type u} {β : Type v} [preorder β] {f : α → β} {l : filter α} {a : α} (h : is_extr_filter f l a) (l' : filter α) : is_extr_filter f (l ⊓ l') a := is_extr_filter.filter_mono h inf_le_left theorem is_min_on.on_subset {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} {t : set α} (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a := is_min_filter.filter_mono hf (iff.mpr filter.principal_mono h) theorem is_max_on.on_subset {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} {t : set α} (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a := is_max_filter.filter_mono hf (iff.mpr filter.principal_mono h) theorem is_extr_on.on_subset {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} {t : set α} (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a := is_extr_filter.filter_mono hf (iff.mpr filter.principal_mono h) theorem is_min_on.inter {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} (hf : is_min_on f s a) (t : set α) : is_min_on f (s ∩ t) a := is_min_on.on_subset hf (set.inter_subset_left s t) theorem is_max_on.inter {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} (hf : is_max_on f s a) (t : set α) : is_max_on f (s ∩ t) a := is_max_on.on_subset hf (set.inter_subset_left s t) theorem is_extr_on.inter {α : Type u} {β : Type v} [preorder β] {f : α → β} {s : set α} {a : α} (hf : is_extr_on f s a) (t : set α) : is_extr_on f (s ∩ t) a := is_extr_on.on_subset hf (set.inter_subset_left s t) /-! ### Composition with (anti)monotone functions -/ theorem is_min_filter.comp_mono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) : is_min_filter (g ∘ f) l a := filter.mem_sets_of_superset hf fun (x : α) (hx : x ∈ set_of fun (x : α) => (fun (x : α) => f a ≤ f x) x) => hg hx theorem is_max_filter.comp_mono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) : is_max_filter (g ∘ f) l a := filter.mem_sets_of_superset hf fun (x : α) (hx : x ∈ set_of fun (x : α) => (fun (x : α) => f x ≤ f a) x) => hg hx theorem is_extr_filter.comp_mono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) : is_extr_filter (g ∘ f) l a := or.elim hf (fun (hf : is_min_filter f l a) => is_min_filter.is_extr (is_min_filter.comp_mono hf hg)) fun (hf : is_max_filter f l a) => is_max_filter.is_extr (is_max_filter.comp_mono hf hg) theorem is_min_filter.comp_antimono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} (hf : is_min_filter f l a) {g : β → γ} (hg : ∀ {x y : β}, x ≤ y → g y ≤ g x) : is_max_filter (g ∘ f) l a := is_max_filter.comp_mono (is_min_filter.dual hf) fun (x y : order_dual β) (h : x ≤ y) => hg h theorem is_max_filter.comp_antimono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} (hf : is_max_filter f l a) {g : β → γ} (hg : ∀ {x y : β}, x ≤ y → g y ≤ g x) : is_min_filter (g ∘ f) l a := is_min_filter.comp_mono (is_max_filter.dual hf) fun (x y : order_dual β) (h : x ≤ y) => hg h theorem is_extr_filter.comp_antimono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} (hf : is_extr_filter f l a) {g : β → γ} (hg : ∀ {x y : β}, x ≤ y → g y ≤ g x) : is_extr_filter (g ∘ f) l a := is_extr_filter.comp_mono (is_extr_filter.dual hf) fun (x y : order_dual β) (h : x ≤ y) => hg h theorem is_min_on.comp_mono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) : is_min_on (g ∘ f) s a := is_min_filter.comp_mono hf hg theorem is_max_on.comp_mono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) : is_max_on (g ∘ f) s a := is_max_filter.comp_mono hf hg theorem is_extr_on.comp_mono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) : is_extr_on (g ∘ f) s a := is_extr_filter.comp_mono hf hg theorem is_min_on.comp_antimono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} (hf : is_min_on f s a) {g : β → γ} (hg : ∀ {x y : β}, x ≤ y → g y ≤ g x) : is_max_on (g ∘ f) s a := is_min_filter.comp_antimono hf hg theorem is_max_on.comp_antimono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} (hf : is_max_on f s a) {g : β → γ} (hg : ∀ {x y : β}, x ≤ y → g y ≤ g x) : is_min_on (g ∘ f) s a := is_max_filter.comp_antimono hf hg theorem is_extr_on.comp_antimono {α : Type u} {β : Type v} {γ : Type w} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} (hf : is_extr_on f s a) {g : β → γ} (hg : ∀ {x y : β}, x ≤ y → g y ≤ g x) : is_extr_on (g ∘ f) s a := is_extr_filter.comp_antimono hf hg theorem is_min_filter.bicomp_mono {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} [preorder δ] {op : β → γ → δ} (hop : relator.lift_fun LessEq (LessEq ⇒ LessEq) op op) (hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) : is_min_filter (fun (x : α) => op (f x) (g x)) l a := sorry theorem is_max_filter.bicomp_mono {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [preorder β] [preorder γ] {f : α → β} {l : filter α} {a : α} [preorder δ] {op : β → γ → δ} (hop : relator.lift_fun LessEq (LessEq ⇒ LessEq) op op) (hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) : is_max_filter (fun (x : α) => op (f x) (g x)) l a := sorry -- No `extr` version because we need `hf` and `hg` to be of the same kind theorem is_min_on.bicomp_mono {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} [preorder δ] {op : β → γ → δ} (hop : relator.lift_fun LessEq (LessEq ⇒ LessEq) op op) (hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) : is_min_on (fun (x : α) => op (f x) (g x)) s a := is_min_filter.bicomp_mono hop hf hg theorem is_max_on.bicomp_mono {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [preorder β] [preorder γ] {f : α → β} {s : set α} {a : α} [preorder δ] {op : β → γ → δ} (hop : relator.lift_fun LessEq (LessEq ⇒ LessEq) op op) (hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) : is_max_on (fun (x : α) => op (f x) (g x)) s a := is_max_filter.bicomp_mono hop hf hg /-! ### Composition with `tendsto` -/ theorem is_min_filter.comp_tendsto {α : Type u} {β : Type v} {δ : Type x} [preorder β] {f : α → β} {l : filter α} {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b)) (hg : filter.tendsto g l' l) : is_min_filter (f ∘ g) l' b := hg hf theorem is_max_filter.comp_tendsto {α : Type u} {β : Type v} {δ : Type x} [preorder β] {f : α → β} {l : filter α} {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b)) (hg : filter.tendsto g l' l) : is_max_filter (f ∘ g) l' b := hg hf theorem is_extr_filter.comp_tendsto {α : Type u} {β : Type v} {δ : Type x} [preorder β] {f : α → β} {l : filter α} {g : δ → α} {l' : filter δ} {b : δ} (hf : is_extr_filter f l (g b)) (hg : filter.tendsto g l' l) : is_extr_filter (f ∘ g) l' b := or.elim hf (fun (hf : is_min_filter f l (g b)) => is_min_filter.is_extr (is_min_filter.comp_tendsto hf hg)) fun (hf : is_max_filter f l (g b)) => is_max_filter.is_extr (is_max_filter.comp_tendsto hf hg) theorem is_min_on.on_preimage {α : Type u} {β : Type v} {δ : Type x} [preorder β] {f : α → β} {s : set α} (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) : is_min_on (f ∘ g) (g ⁻¹' s) b := is_min_filter.comp_tendsto hf (iff.mpr filter.tendsto_principal_principal (set.subset.refl (g ⁻¹' s))) theorem is_max_on.on_preimage {α : Type u} {β : Type v} {δ : Type x} [preorder β] {f : α → β} {s : set α} (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) : is_max_on (f ∘ g) (g ⁻¹' s) b := is_max_filter.comp_tendsto hf (iff.mpr filter.tendsto_principal_principal (set.subset.refl (g ⁻¹' s))) theorem is_extr_on.on_preimage {α : Type u} {β : Type v} {δ : Type x} [preorder β] {f : α → β} {s : set α} (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) : is_extr_on (f ∘ g) (g ⁻¹' s) b := is_extr_on.elim hf (fun (hf : is_min_on f s (g b)) => is_min_on.is_extr (is_min_on.on_preimage g hf)) fun (hf : is_max_on f s (g b)) => is_max_on.is_extr (is_max_on.on_preimage g hf) /-! ### Pointwise addition -/ theorem is_min_filter.add {α : Type u} {β : Type v} [ordered_add_comm_monoid β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (fun (x : α) => f x + g x) l a := (fun (this : is_min_filter (fun (x : α) => f x + g x) l a) => this) (is_min_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => add_le_add hx hy) hf hg) theorem is_max_filter.add {α : Type u} {β : Type v} [ordered_add_comm_monoid β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (fun (x : α) => f x + g x) l a := (fun (this : is_max_filter (fun (x : α) => f x + g x) l a) => this) (is_max_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => add_le_add hx hy) hf hg) theorem is_min_on.add {α : Type u} {β : Type v} [ordered_add_comm_monoid β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (fun (x : α) => f x + g x) s a := is_min_filter.add hf hg theorem is_max_on.add {α : Type u} {β : Type v} [ordered_add_comm_monoid β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (fun (x : α) => f x + g x) s a := is_max_filter.add hf hg /-! ### Pointwise negation and subtraction -/ theorem is_min_filter.neg {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) : is_max_filter (fun (x : α) => -f x) l a := is_min_filter.comp_antimono hf fun (x y : β) (hx : x ≤ y) => neg_le_neg hx theorem is_max_filter.neg {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) : is_min_filter (fun (x : α) => -f x) l a := is_max_filter.comp_antimono hf fun (x y : β) (hx : x ≤ y) => neg_le_neg hx theorem is_extr_filter.neg {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {a : α} {l : filter α} (hf : is_extr_filter f l a) : is_extr_filter (fun (x : α) => -f x) l a := or.elim hf (fun (hf : is_min_filter f l a) => is_max_filter.is_extr (is_min_filter.neg hf)) fun (hf : is_max_filter f l a) => is_min_filter.is_extr (is_max_filter.neg hf) theorem is_min_on.neg {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {a : α} {s : set α} (hf : is_min_on f s a) : is_max_on (fun (x : α) => -f x) s a := is_min_on.comp_antimono hf fun (x y : β) (hx : x ≤ y) => neg_le_neg hx theorem is_max_on.neg {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {a : α} {s : set α} (hf : is_max_on f s a) : is_min_on (fun (x : α) => -f x) s a := is_max_on.comp_antimono hf fun (x y : β) (hx : x ≤ y) => neg_le_neg hx theorem is_extr_on.neg {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {a : α} {s : set α} (hf : is_extr_on f s a) : is_extr_on (fun (x : α) => -f x) s a := is_extr_on.elim hf (fun (hf : is_min_on f s a) => is_max_on.is_extr (is_min_on.neg hf)) fun (hf : is_max_on f s a) => is_min_on.is_extr (is_max_on.neg hf) theorem is_min_filter.sub {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) (hg : is_max_filter g l a) : is_min_filter (fun (x : α) => f x - g x) l a := sorry theorem is_max_filter.sub {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) (hg : is_min_filter g l a) : is_max_filter (fun (x : α) => f x - g x) l a := sorry theorem is_min_on.sub {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_min_on f s a) (hg : is_max_on g s a) : is_min_on (fun (x : α) => f x - g x) s a := sorry theorem is_max_on.sub {α : Type u} {β : Type v} [ordered_add_comm_group β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_max_on f s a) (hg : is_min_on g s a) : is_max_on (fun (x : α) => f x - g x) s a := sorry /-! ### Pointwise `sup`/`inf` -/ theorem is_min_filter.sup {α : Type u} {β : Type v} [semilattice_sup β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (fun (x : α) => f x ⊔ g x) l a := (fun (this : is_min_filter (fun (x : α) => f x ⊔ g x) l a) => this) (is_min_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => sup_le_sup hx hy) hf hg) theorem is_max_filter.sup {α : Type u} {β : Type v} [semilattice_sup β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (fun (x : α) => f x ⊔ g x) l a := (fun (this : is_max_filter (fun (x : α) => f x ⊔ g x) l a) => this) (is_max_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => sup_le_sup hx hy) hf hg) theorem is_min_on.sup {α : Type u} {β : Type v} [semilattice_sup β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (fun (x : α) => f x ⊔ g x) s a := is_min_filter.sup hf hg theorem is_max_on.sup {α : Type u} {β : Type v} [semilattice_sup β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (fun (x : α) => f x ⊔ g x) s a := is_max_filter.sup hf hg theorem is_min_filter.inf {α : Type u} {β : Type v} [semilattice_inf β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (fun (x : α) => f x ⊓ g x) l a := (fun (this : is_min_filter (fun (x : α) => f x ⊓ g x) l a) => this) (is_min_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => inf_le_inf hx hy) hf hg) theorem is_max_filter.inf {α : Type u} {β : Type v} [semilattice_inf β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (fun (x : α) => f x ⊓ g x) l a := (fun (this : is_max_filter (fun (x : α) => f x ⊓ g x) l a) => this) (is_max_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => inf_le_inf hx hy) hf hg) theorem is_min_on.inf {α : Type u} {β : Type v} [semilattice_inf β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (fun (x : α) => f x ⊓ g x) s a := is_min_filter.inf hf hg theorem is_max_on.inf {α : Type u} {β : Type v} [semilattice_inf β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (fun (x : α) => f x ⊓ g x) s a := is_max_filter.inf hf hg /-! ### Pointwise `min`/`max` -/ theorem is_min_filter.min {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (fun (x : α) => min (f x) (g x)) l a := (fun (this : is_min_filter (fun (x : α) => min (f x) (g x)) l a) => this) (is_min_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => min_le_min hx hy) hf hg) theorem is_max_filter.min {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (fun (x : α) => min (f x) (g x)) l a := (fun (this : is_max_filter (fun (x : α) => min (f x) (g x)) l a) => this) (is_max_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => min_le_min hx hy) hf hg) theorem is_min_on.min {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (fun (x : α) => min (f x) (g x)) s a := is_min_filter.min hf hg theorem is_max_on.min {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (fun (x : α) => min (f x) (g x)) s a := is_max_filter.min hf hg theorem is_min_filter.max {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (fun (x : α) => max (f x) (g x)) l a := (fun (this : is_min_filter (fun (x : α) => max (f x) (g x)) l a) => this) (is_min_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => max_le_max hx hy) hf hg) theorem is_max_filter.max {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (fun (x : α) => max (f x) (g x)) l a := (fun (this : is_max_filter (fun (x : α) => max (f x) (g x)) l a) => this) (is_max_filter.bicomp_mono (fun (x x' : β) (hx : x ≤ x') (y y' : β) (hy : y ≤ y') => max_le_max hx hy) hf hg) theorem is_min_on.max {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (fun (x : α) => max (f x) (g x)) s a := is_min_filter.max hf hg theorem is_max_on.max {α : Type u} {β : Type v} [linear_order β] {f : α → β} {g : α → β} {a : α} {s : set α} (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (fun (x : α) => max (f x) (g x)) s a := is_max_filter.max hf hg /-! ### Relation with `eventually` comparisons of two functions -/ theorem filter.eventually_le.is_max_filter {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hle : filter.eventually_le l g f) (hfga : f a = g a) (h : is_max_filter f l a) : is_max_filter g l a := sorry theorem is_max_filter.congr {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (h : is_max_filter f l a) (heq : filter.eventually_eq l f g) (hfga : f a = g a) : is_max_filter g l a := filter.eventually_le.is_max_filter (filter.eventually_eq.le (filter.eventually_eq.symm heq)) hfga h theorem filter.eventually_eq.is_max_filter_iff {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (heq : filter.eventually_eq l f g) (hfga : f a = g a) : is_max_filter f l a ↔ is_max_filter g l a := { mp := fun (h : is_max_filter f l a) => is_max_filter.congr h heq hfga, mpr := fun (h : is_max_filter g l a) => is_max_filter.congr h (filter.eventually_eq.symm heq) (Eq.symm hfga) } theorem filter.eventually_le.is_min_filter {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (hle : filter.eventually_le l f g) (hfga : f a = g a) (h : is_min_filter f l a) : is_min_filter g l a := filter.eventually_le.is_max_filter hle hfga h theorem is_min_filter.congr {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (h : is_min_filter f l a) (heq : filter.eventually_eq l f g) (hfga : f a = g a) : is_min_filter g l a := filter.eventually_le.is_min_filter (filter.eventually_eq.le heq) hfga h theorem filter.eventually_eq.is_min_filter_iff {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (heq : filter.eventually_eq l f g) (hfga : f a = g a) : is_min_filter f l a ↔ is_min_filter g l a := { mp := fun (h : is_min_filter f l a) => is_min_filter.congr h heq hfga, mpr := fun (h : is_min_filter g l a) => is_min_filter.congr h (filter.eventually_eq.symm heq) (Eq.symm hfga) } theorem is_extr_filter.congr {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (h : is_extr_filter f l a) (heq : filter.eventually_eq l f g) (hfga : f a = g a) : is_extr_filter g l a := sorry theorem filter.eventually_eq.is_extr_filter_iff {α : Type u_1} {β : Type u_2} [preorder β] {f : α → β} {g : α → β} {a : α} {l : filter α} (heq : filter.eventually_eq l f g) (hfga : f a = g a) : is_extr_filter f l a ↔ is_extr_filter g l a := { mp := fun (h : is_extr_filter f l a) => is_extr_filter.congr h heq hfga, mpr := fun (h : is_extr_filter g l a) => is_extr_filter.congr h (filter.eventually_eq.symm heq) (Eq.symm hfga) }
8b88e885cfec59ed424c2e7988b685231cd2b6c2
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/adjunctions/default.lean
a2a7600826642848c6cbbc87896fa633e607bf8f
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
3,266
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.natural_transformation import category_theory.opposites import category_theory.types import category_theory.tactics.obviously open category_theory namespace category_theory.adjunctions universes u₁ v₁ u₂ v₂ variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 -- TODO think again about whether we should specify the conditions here in terms of natural transformations or components structure Adjunction (L : C ⥤ D) (R : D ⥤ C) := (unit : functor.id _ ⟹ (L ⋙ R)) (counit : (R ⋙ L) ⟹ functor.id _) (triangle_1 : ∀ X : D, (unit (R X)) ≫ (R.map (counit X)) = 𝟙 (R X)) (triangle_2 : ∀ X : C, (L.map (unit X)) ≫ (counit (L X)) = 𝟙 (L X)) -- (Triangle_1 : (whisker_on_left R unit) ⊟ (whisker_on_right counit R) = 1) -- we'd need unitors and associators here attribute [simp,search] Adjunction.triangle_1 Adjunction.triangle_2 infix ` ⊣ `:50 := Adjunction @[extensionality] lemma Adjunctions_pointwise_equal (L : C ⥤ D) (R : D ⥤ C) (A B : L ⊣ R) (w1 : A.unit = B.unit) (w2 : A.counit = B.counit) : A = B := begin induction A, induction B, tidy end -- PROJECT: from an adjunction construct the triangles as equations between natural transformations. -- def Triangle_1 -- {C D : Category} -- {L : Functor C D} -- {R : Functor D C} -- (unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R)) -- (counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D)) := -- @vertical_composition_of_NaturalTransformations D C R (FunctorComposition (FunctorComposition R L) R) R ⟦ whisker_on_left R unit ⟧ ⟦ whisker_on_right counit R ⟧ -- = IdentityNaturalTransformation R -- def Triangle_2 -- {C D : Category} -- {L : Functor C D} -- {R : Functor D C} -- (unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R)) -- (counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D)) := -- @vertical_composition_of_NaturalTransformations C D L (FunctorComposition (FunctorComposition L R) L) L ⟦ whisker_on_right unit L ⟧ ⟦ whisker_on_left L counit ⟧ -- = IdentityNaturalTransformation L @[simp,search] lemma Adjunction.unit_naturality {L : C ⥤ D} {R : D ⥤ C} (A : L ⊣ R) {X Y : C} (f : X ⟶ Y) : (A.unit X) ≫ (R.map (L.map f)) = f ≫ (A.unit Y) := by obviously @[simp,search] lemma Adjunction.counit_naturality {L : C ⥤ D} {R : D ⥤ C} (A : L ⊣ R) {X Y : D} (f : X ⟶ Y) : (L.map (R.map f)) ≫ (A.counit Y) = (A.counit X) ≫ f := by obviously -- PROJECT examples -- PROJECT existence in terms of initial objects in comma categories -- PROJECT adjoints for functors between functor categories -- PROJECT adjoints are unique -- PROJECT equivalences can be lifted to adjoint equivalences -- PROJECT universal properties of adjunctions -- PROJECT show these are a special case of a duality in a 2-category. -- PROJECT adjoints of monoidal functors are (op)lax end category_theory.adjunctions
e99a392f735723fc38782009b8957d87ce3dc0fb
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/core.lean
cccea3a2b609282a31cf39057d6f4455cb2ba075
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
91,634
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic import logic.function.basic import control.basic import meta.expr import meta.rb_map import data.bool import tactic.binder_matching import tactic.lean_core_docs import tactic.interactive_expr import system.io universe variable u attribute [derive [has_reflect, decidable_eq]] tactic.transparency instance : has_lt pos := { lt := λ x y, (x.line, x.column) < (y.line, y.column) } namespace expr open tactic /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Constructs a list of `tactic expr` given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list. We need to return a list of `tactic expr`, rather than just `expr`, because these expressions will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. -/ meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr)) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n), -- We reverse the list of lemmas marked with an attribute, -- on the assumption that lemmas proved earlier are more often applicable -- than lemmas proved later. This is a performance optimization. build_list_expr_for_apply (m.reverse ++ t)) <|> return ((i_to_expr_for_apply h) :: tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit := do l ← lock_tactic_state $ build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorrry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end 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 /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s 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 `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := do e ← get_env, s ← e.decl_olean `tactic.reset_instance_cache, return $ s.popn_back 17 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← types.with_ident_list <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute, as long as the user attribute has no parameter. If a user attribute with a parameter (that is not `unit`) is set, this function will raise an error. -/ -- possible enhancement if needed: use default value for a user attribute with parameter. meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name () %%persistent) <|> fail!"Cannot set attribute @[{attr_name}]. The corresponding user attribute {user_attr_nm} has a parameter.", tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
de9462c431f6ff9f158dff7cd728807fdfc59dee
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/field_theory/minimal_polynomial.lean
a9ab3809211bafe3b09a901b53048c304bce1e4b
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,464
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import ring_theory.integral_closure import data.polynomial.field_division import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials This file defines the minimal polynomial of an element x of an A-algebra B, under the assumption that x is integral over A. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ universes u v w open_locale classical open polynomial set function variables {α : Type u} {β : Type v} section min_poly_def variables [comm_ring α] [ring β] [algebra α β] /-- Let `B` be an `A`-algebra, and `x` an element of `B` that is integral over `A` so we have some term `hx : is_integral A x`. The minimal polynomial `minimal_polynomial hx` of `x` is a monic polynomial of smallest degree that has `x` as its root. For instance, if `V` is a `K`-vector space for some field `K`, and `f : V →ₗ[K] V` then the minimal polynomial of `f` is `minimal_polynomial f.is_integral`. -/ noncomputable def minimal_polynomial {x : β} (hx : is_integral α x) : polynomial α := well_founded.min degree_lt_wf _ hx end min_poly_def namespace minimal_polynomial section ring variables [comm_ring α] [ring β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is monic.-/ lemma monic : monic (minimal_polynomial hx) := (well_founded.min_mem degree_lt_wf _ hx).1 /--An element is a root of its minimal polynomial.-/ @[simp] lemma aeval : aeval x (minimal_polynomial hx) = 0 := (well_founded.min_mem degree_lt_wf _ hx).2 /--The defining property of the minimal polynomial of an element x: it is the monic polynomial with smallest degree that has x as its root.-/ lemma min {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minimal_polynomial hx) ≤ degree p := le_of_not_lt $ well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩ /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial α] : (minimal_polynomial hx) ≠ 0 := ne_zero_of_monic (monic hx) end ring section integral_domain variables [integral_domain α] section ring variables [ring β] [algebra α β] [nontrivial β] variables {x : β} (hx : is_integral α x) /--The degree of a minimal polynomial is positive. -/ lemma degree_pos [nontrivial α] : 0 < degree (minimal_polynomial hx) := begin apply lt_of_le_of_ne, { simpa only [zero_le_degree_iff] using ne_zero hx }, assume deg_eq_zero, rw eq_comm at deg_eq_zero, have ndeg_eq_zero : nat_degree (minimal_polynomial hx) = 0, { simpa using congr_arg nat_degree (eq_C_of_degree_eq_zero deg_eq_zero) }, have eq_one : minimal_polynomial hx = 1, { rw eq_C_of_degree_eq_zero deg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval hx end /--A minimal polynomial is not a unit.-/ lemma not_is_unit : ¬ is_unit (minimal_polynomial hx) := assume H, (ne_of_lt (degree_pos hx)).symm $ degree_eq_zero_of_is_unit H end ring section domain variables [domain β] [algebra α β] variables {x : β} (hx : is_integral α x) /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minimal_polynomial {a : polynomial α} (hamonic : a.monic) (hdvd : dvd_not_unit a (minimal_polynomial hx)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minimal_polynomial.min hx hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end /--A minimal polynomial is irreducible.-/ lemma irreducible : irreducible (minimal_polynomial hx) := begin cases irreducible_or_factor (minimal_polynomial hx) (not_is_unit hx) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minimal_polynomial hx = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minimal_polynomial hx : hab_eq }, have hzero := aeval hx, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minimal_polynomial hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minimal_polynomial hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end domain end integral_domain section field variables [field α] section ring variables [ring β] [algebra α β] variables {x : β} (hx : is_integral α x) /--If an element x is a root of a nonzero polynomial p, then the degree of p is at least the degree of the minimal polynomial of x.-/ lemma degree_le_of_ne_zero {p : polynomial α} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minimal_polynomial hx) ≤ degree p := calc degree (minimal_polynomial hx) ≤ degree (p * C (leading_coeff p)⁻¹) : min _ (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz /--The minimal polynomial of an element x is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has x as a root, then this polynomial is equal to the minimal polynomial of x.-/ lemma unique {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : polynomial α, q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minimal_polynomial hx := begin symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero hx hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min hx pmonic hp) (pmin (minimal_polynomial hx) (monic hx) (aeval hx)) }, end /--If an element x is a root of a polynomial p, then the minimal polynomial of x divides p.-/ lemma dvd {p : polynomial α} (hp : polynomial.aeval x p = 0) : minimal_polynomial hx ∣ p := begin rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero hx hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower {α γ : Type*} (β : Type*) [comm_ring α] [field β] [comm_ring γ] [algebra α β] [algebra α γ] [algebra β γ] [is_scalar_tower α β γ] {x : γ} (hx : is_integral α x) : minimal_polynomial (is_integral_of_is_scalar_tower x hx) ∣ (minimal_polynomial hx).map (algebra_map α β) := by { apply minimal_polynomial.dvd, rw [← is_scalar_tower.aeval_apply, minimal_polynomial.aeval] } variables [nontrivial β] theorem unique' {p : polynomial α} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minimal_polynomial hx := let ⟨q, hq⟩ := dvd hx hp2 in eq_of_monic_of_associated hp3 (monic hx) $ mul_one (minimal_polynomial hx) ▸ hq.symm ▸ associated_mul_mul (associated.refl _) $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit hx lemma gcd_domain_eq_field_fractions {α : Type u} {β : Type v} {γ : Type v} [integral_domain α] [gcd_monoid α] [field β] [integral_domain γ] (f : fraction_map α β) [algebra f.codomain γ] [algebra α γ] [is_scalar_tower α f.codomain γ] {x : γ} (hx : is_integral α x) : minimal_polynomial (@is_integral_of_is_scalar_tower α f.codomain γ _ _ _ _ _ _ _ x hx) = ((minimal_polynomial hx).map (localization_map.to_ring_hom f)) := begin refine (unique' (@is_integral_of_is_scalar_tower α f.codomain γ _ _ _ _ _ _ _ x hx) _ _ _).symm, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map f (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply α f.codomain γ x (minimal_polynomial hx), simp only [localization_map.algebra_map_eq, aeval] at htower, exact htower.symm }, { exact monic_map _ (monic hx) } end /--If L/K is a field extension, and x is an element of L in the image of K, then the minimal polynomial of x is X - C x.-/ @[simp] protected lemma algebra_map (a : α) (ha : is_integral α (algebra_map α β a)) : minimal_polynomial ha = X - C a := eq.symm $ unique' ha (irreducible_X_sub_C a) (by rw [alg_hom.map_sub, aeval_X, aeval_C, sub_self]) (monic_X_sub_C a) variable (β) /--If L/K is a field extension, and x is an element of L in the image of K, then the minimal polynomial of x is X - C x.-/ lemma algebra_map' (a : α) : minimal_polynomial (@is_integral_algebra_map α β _ _ _ a) = X - C a := minimal_polynomial.algebra_map _ _ variable {β} /--The minimal polynomial of 0 is X.-/ @[simp] lemma zero {h₀ : is_integral α (0:β)} : minimal_polynomial h₀ = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using algebra_map' β (0:α) /--The minimal polynomial of 1 is X - 1.-/ @[simp] lemma one {h₁ : is_integral α (1:β)} : minimal_polynomial h₁ = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using algebra_map' β (1:α) end ring section domain variables [domain β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is prime.-/ lemma prime : prime (minimal_polynomial hx) := begin refine ⟨ne_zero hx, not_is_unit hx, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval hx], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd hx) (dvd hx) this end /--If L/K is a field extension and an element y of K is a root of the minimal polynomial of an element x ∈ L, then y maps to x under the field embedding.-/ lemma root {x : β} (hx : is_integral α x) {y : α} (h : is_root (minimal_polynomial hx) y) : algebra_map α β y = x := have key : minimal_polynomial hx = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd (dvd_symm_of_irreducible (irreducible_X_sub_C y) (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval hx, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /--The constant coefficient of the minimal polynomial of x is 0 if and only if x = 0.-/ @[simp] lemma coeff_zero_eq_zero : coeff (minimal_polynomial hx) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /--The minimal polynomial of a nonzero element has nonzero constant coefficient.-/ lemma coeff_zero_ne_zero (h : x ≠ 0) : coeff (minimal_polynomial hx) 0 ≠ 0 := by { contrapose! h, simpa using h } end domain end field end minimal_polynomial
09dc5e499cc6cfc0aa91cd6b9f0d4da5ab3d774f
d8820d2c92be8052d13f9c8f8c483a6e15c5f566
/src/Exercises/Exercies1.lean
b728aef15a2738dd059b5fc47998b1b443ad122b
[]
no_license
JasonKYi/M4000x_LEAN_formalisation
4a19b84f6d0fe2e214485b8532e21cd34996c4b1
6e99793f2fcbe88596e27644f430e46aa2a464df
refs/heads/master
1,599,755,414,708
1,589,494,604,000
1,589,494,604,000
221,759,483
8
1
null
1,589,494,605,000
1,573,755,201,000
Lean
UTF-8
Lean
false
false
309
lean
/- Exercise 1. Try to prove that ¬ P ↔ (P → false) without using automation! Here are some basic tactics that might help : http://wwwf.imperial.ac.uk/~buzzard/xena/html/source/tactics/guide.html -/ example (P : Prop) : ¬ P ↔ (P → false) := begin sorry -- Replace the sorry with your proof! end
035ecac65738b02726c9dd4fff288b3b84f1a039
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/uniform_space/uniform_convergence.lean
3ea85237b0a6e0f43868b7148a276119bec65a48
[ "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
16,639
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.uniform_space.basic /-! # Uniform convergence A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality `dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit, most notably continuity. We prove this in the file, defining the notion of uniform convergence in the more general setting of uniform spaces, and with respect to an arbitrary indexing set endowed with a filter (instead of just `ℕ` with `at_top`). ## Main results Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β` (where the index `n` belongs to an indexing type `ι` endowed with a filter `p`). * `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has `(f y, Fₙ y) ∈ u` for all `y ∈ s`. * `tendsto_uniformly F f p`: same notion with `s = univ`. * `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous on this set is itself continuous on this set. * `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous. * `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. * `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. We also define notions where the convergence is locally uniform, called `tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems all have corresponding versions under locally uniform convergence. ## Implementation notes Most results hold under weaker assumptions of locally uniform approximation. In a first section, we prove the results under these weaker assumptions. Then, we derive the results on uniform convergence from them. ## Tags Uniform limit, uniform convergence, tends uniformly to -/ noncomputable theory open_locale topological_space classical uniformity open set filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-! ### Different notions of uniform convergence We define uniform convergence and locally uniform convergence, on a set or in the whole space. -/ variables {ι : Type*} [uniform_space β] {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α} /-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/ def tendsto_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x ∈ s, (f x, F n x) ∈ u /-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x`. -/ def tendsto_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x, (f x, F n x) ∈ u lemma tendsto_uniformly_on_univ : tendsto_uniformly_on F f p univ ↔ tendsto_uniformly F f p := by simp [tendsto_uniformly_on, tendsto_uniformly] lemma tendsto_uniformly_on.mono {s' : set α} (h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' := λ u hu, (h u hu).mono (λ n hn x hx, hn x (h' hx)) lemma tendsto_uniformly.tendsto_uniformly_on (h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s := (tendsto_uniformly_on_univ.2 h).mono (subset_univ s) /-- Composing on the right by a function preserves uniform convergence on a set -/ lemma tendsto_uniformly_on.comp (h : tendsto_uniformly_on F f p s) (g : γ → α) : tendsto_uniformly_on (λ n, F n ∘ g) (f ∘ g) p (g ⁻¹' s) := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x hx, hn _ hx end /-- Composing on the right by a function preserves uniform convergence -/ lemma tendsto_uniformly.comp (h : tendsto_uniformly F f p) (g : γ → α) : tendsto_uniformly (λ n, F n ∘ g) (f ∘ g) p := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x, hn _ end variable [topological_space α] /-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/ def tendsto_locally_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u /-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x`. -/ def tendsto_locally_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ (x : α), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u lemma tendsto_uniformly_on.tendsto_locally_uniformly_on (h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s := λ u hu x hx, ⟨s, self_mem_nhds_within, h u hu⟩ lemma tendsto_uniformly.tendsto_locally_uniformly (h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p := λ u hu x, ⟨univ, univ_mem, by simpa using h u hu⟩ lemma tendsto_locally_uniformly_on.mono (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_locally_uniformly_on F f p s' := begin assume u hu x hx, rcases h u hu x (h' hx) with ⟨t, ht, H⟩, exact ⟨t, nhds_within_mono x h' ht, H.mono (λ n, id)⟩ end lemma tendsto_locally_uniformly_on_univ : tendsto_locally_uniformly_on F f p univ ↔ tendsto_locally_uniformly F f p := by simp [tendsto_locally_uniformly_on, tendsto_locally_uniformly, nhds_within_univ] lemma tendsto_locally_uniformly_on.comp [topological_space γ] {t : set γ} (h : tendsto_locally_uniformly_on F f p s) (g : γ → α) (hg : maps_to g t s) (cg : continuous_on g t) : tendsto_locally_uniformly_on (λ n, (F n) ∘ g) (f ∘ g) p t := begin assume u hu x hx, rcases h u hu (g x) (hg hx) with ⟨a, ha, H⟩, have : g⁻¹' a ∈ 𝓝[t] x := ((cg x hx).preimage_mem_nhds_within' (nhds_within_mono (g x) hg.image_subset ha)), exact ⟨g ⁻¹' a, this, H.mono (λ n hn y hy, hn _ hy)⟩ end lemma tendsto_locally_uniformly.comp [topological_space γ] (h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) : tendsto_locally_uniformly (λ n, (F n) ∘ g) (f ∘ g) p := begin rw ← tendsto_locally_uniformly_on_univ at h ⊢, rw continuous_iff_continuous_on_univ at cg, exact h.comp _ (maps_to_univ _ _) cg end /-! ### Uniform approximation In this section, we give lemmas ensuring that a function is continuous if it can be approximated uniformly by continuous functions. We give various versions, within a set or the whole space, at a single point or at all points, with locally uniform approximation or uniform approximation. All the statements are derived from a statement about locally uniform approximation within a set at a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/ /-- A function which can be locally uniformly approximated by functions which are continuous within a set at a point is continuous within this set at this point. -/ lemma continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (hx : x ∈ s) (L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝[s] x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_within_at (F n) s x) : continuous_within_at f s x := begin apply uniform.continuous_within_at_iff'_left.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, obtain ⟨u₂, h₂, hsymm, u₂₁⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), (∀{a b}, (a, b) ∈ u → (b, a) ∈ u) ∧ comp_rel u u ⊆ u₁ := comp_symm_of_uniformity h₁, rcases L u₂ h₂ with ⟨t, tx, n, ht⟩, have A : ∀ᶠ y in 𝓝[s] x, (f y, F n y) ∈ u₂ := eventually.mono tx ht, have B : ∀ᶠ y in 𝓝[s] x, (F n y, F n x) ∈ u₂ := uniform.continuous_within_at_iff'_left.1 (C n) h₂, have C : ∀ᶠ y in 𝓝[s] x, (f y, F n x) ∈ u₁ := (A.and B).mono (λ y hy, u₂₁ (prod_mk_mem_comp_rel hy.1 hy.2)), have : (F n x, f x) ∈ u₁ := u₂₁ (prod_mk_mem_comp_rel (refl_mem_uniformity h₂) (hsymm (A.self_of_nhds_within hx))), exact C.mono (λ y hy, u₁₀ (prod_mk_mem_comp_rel hy this)) end /-- A function which can be locally uniformly approximated by functions which are continuous at a point is continuous at this point. -/ lemma continuous_at_of_locally_uniform_approx_of_continuous_at (L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_at (F n) x) : continuous_at f x := begin simp only [← continuous_within_at_univ] at C ⊢, apply continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (mem_univ _) _ C, simpa [nhds_within_univ] using L end /-- A function which can be locally uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_locally_uniform_approx_of_continuous_on (L : ∀ (x ∈ s) (u ∈ 𝓤 β), ∃t ∈ 𝓝[s] x, ∃n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_on (F n) s) : continuous_on f s := λ x hx, continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx (L x hx) (λ n, C n x hx) /-- A function which can be uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_uniform_approx_of_continuous_on (L : ∀ u ∈ 𝓤 β, ∃ n, ∀ y ∈ s, (f y, F n y) ∈ u) : (∀ n, continuous_on (F n) s) → continuous_on f s := continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, ⟨s, self_mem_nhds_within, L u hu⟩) /-- A function which can be locally uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_locally_uniform_approx_of_continuous (L : ∀ (x : α), ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous (F n)) : continuous f := begin simp only [continuous_iff_continuous_on_univ] at ⊢ C, apply continuous_on_of_locally_uniform_approx_of_continuous_on _ C, simpa [nhds_within_univ] using L end /-- A function which can be uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_uniform_approx_of_continuous (L : ∀ u ∈ 𝓤 β, ∃ N, ∀ y, (f y, F N y) ∈ u) : (∀ n, continuous (F n)) → continuous f := continuous_of_locally_uniform_approx_of_continuous $ λx u hu, ⟨univ, by simpa [filter.univ_mem] using L u hu⟩ /-! ### Uniform limits From the previous statements on uniform approximation, we deduce continuity results for uniform limits. -/ /-- A locally uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_locally_uniformly_on.continuous_on (h : tendsto_locally_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) [ne_bot p] : continuous_on f s := begin apply continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, _) hc, rcases h u hu x hx with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists⟩ end /-- A uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_uniformly_on.continuous_on (h : tendsto_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) [ne_bot p] : continuous_on f s := h.tendsto_locally_uniformly_on.continuous_on hc /-- A locally uniform limit of continuous functions is continuous. -/ lemma tendsto_locally_uniformly.continuous (h : tendsto_locally_uniformly F f p) (hc : ∀ n, continuous (F n)) [ne_bot p] : continuous f := begin apply continuous_of_locally_uniform_approx_of_continuous (λ x u hu, _) hc, rcases h u hu x with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists⟩ end /-- A uniform limit of continuous functions is continuous. -/ lemma tendsto_uniformly.continuous (h : tendsto_uniformly F f p) (hc : ∀ n, continuous (F n)) [ne_bot p] : continuous f := h.tendsto_locally_uniformly.continuous hc /-! ### Composing limits under uniform convergence In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In this paragraph, we prove variations around this statement. -/ /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f` which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit_within (h : continuous_within_at f s x) (hg : tendsto g p (𝓝[s] x)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin apply uniform.tendsto_nhds_right.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, rcases hunif u₁ h₁ with ⟨s, sx, hs⟩, have A : ∀ᶠ n in p, g n ∈ s := hg sx, have B : ∀ᶠ n in p, (f x, f (g n)) ∈ u₁ := hg (uniform.continuous_within_at_iff'_right.1 h h₁), refine ((hs.and A).and B).mono (λ y hy, _), rcases hy with ⟨⟨H1, H2⟩, H3⟩, exact u₁₀ (prod_mk_mem_comp_rel H3 (H1 _ H2)) end /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit (h : continuous_at f x) (hg : tendsto g p (𝓝 x)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin rw ← continuous_within_at_univ at h, rw ← nhds_within_univ at hunif hg, exact tendsto_comp_of_locally_uniform_limit_within h hg hunif end /-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/ lemma tendsto_locally_uniformly_on.tendsto_comp (h : tendsto_locally_uniformly_on F f p s) (hf : continuous_within_at f s x) (hx : x ∈ s) (hg : tendsto g p (𝓝[s] x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, h u hu x hx) /-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. -/ lemma tendsto_uniformly_on.tendsto_comp (h : tendsto_uniformly_on F f p s) (hf : continuous_within_at f s x) (hg : tendsto g p (𝓝[s] x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, ⟨s, self_mem_nhds_within, h u hu⟩) /-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_locally_uniformly.tendsto_comp (h : tendsto_locally_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit hf hg (λ u hu, h u hu x) /-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_uniformly.tendsto_comp (h : tendsto_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := h.tendsto_locally_uniformly.tendsto_comp hf hg
e8c40229559cbb9df897e59a30d6fadd687e3d65
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/complex/exponential.lean
8f3bf876f75e2ed16e4ae71630282bbb149b1a09
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
58,838
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose.sum import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators nat section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := have h₁ : ∑ a in (range n).sigma (range ∘ nat.succ), f (a.2) (a.1 - a.2) = ∑ m in range n, ∑ k in range (m + 1), f k (m - k) := sum_sigma, have h₂ : ∑ a in (range n).sigma (λ m, range (n - m)), f (a.1) (a.2) = ∑ m in range n, ∑ k in range (n - m), f m k := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), abv (a n)) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / m!)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw conj.map_sum, refine sum_congr rfl (λ n hn, _), rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div, conj_bit0, conj.map_one] end @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, pow_two, pow_two] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_square], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_square], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div] lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, pow_two], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_square'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] /-- De Moivre's formula -/ theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw ← of_real_inj; simp [cos_two_mul'] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp [cosh_add_sinh] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw ← of_real_inj; simp [sinh_add_cosh] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_square] lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_square] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) @[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ * (n! * n)⁻¹ := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev', h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.factorial_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : abs' x ≤ 1) {n : ℕ} (hn : 0 < n) : abs' (exp x - ∑ m in range n, x ^ m / m!) ≤ abs' x ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by { simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ], field_simp [mul_assoc, mul_left_comm] } theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : abs' x ≤ 1) : abs' (exp x - exp_near m x 0) ≤ abs' x ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : abs' (1 + x / m * a₂ - a₁) ≤ b₁ - abs' x / m * b₂) (h : abs' (exp x - exp_near m x a₂) ≤ abs' x ^ m / m! * b₂) : abs' (exp x - exp_near n x a₁) ≤ abs' x ^ n / n! * b₁ := begin refine le_trans (_root_.abs_sub_le _ _ _) (le_trans (add_le_add_right h _) _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', _root_.abs_div, ← pow_abs], field_simp [mul_assoc] }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs' x ≤ 1) (e : abs' (1 - a) ≤ b - abs' x / rm * ((rm+1)/rm)) : abs' (exp x - exp_near n x a) ≤ abs' x ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : abs' (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs' 1 ^ m / m! * (b₁ * rm)) : abs' (exp 1 - exp_near n 1 a₁) ≤ abs' 1 ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : abs' (exp x - exp_near 0 x a) ≤ abs' x ^ 0 / 0! * b) : abs' (exp x - a) ≤ b := by simpa using h lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
67e04299d1e080ffdeb6b846875b406aba3acf20
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/separation.lean
c5fc7532ce7e7be1abb45818eeea830c550ec72d
[ "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
93,076
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.subset_properties import topology.connected import topology.nhds_set import topology.inseparable /-! # Separation properties of topological spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the predicate `separated_nhds`, and common separation axioms (under the Kolmogorov classification). ## Main definitions * `separated_nhds`: Two `set`s are separated by neighbourhoods if they are contained in disjoint open sets. * `t0_space`: A T₀/Kolmogorov space is a space where, for every two points `x ≠ y`, there is an open set that contains one, but not the other. * `t1_space`: A T₁/Fréchet space is a space where every singleton set is closed. This is equivalent to, for every pair `x ≠ y`, there existing an open set containing `x` but not `y` (`t1_space_iff_exists_open` shows that these conditions are equivalent.) * `t2_space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`, there is two disjoint open sets, one containing `x`, and the other `y`. * `t2_5_space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`, there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint. * `t3_space`: A T₃ space, is one where given any closed `C` and `x ∉ C`, there is disjoint open sets containing `x` and `C` respectively. In `mathlib`, T₃ implies T₂.₅. * `normal_space`: A T₄ space (sometimes referred to as normal, but authors vary on whether this includes T₂; `mathlib` does), is one where given two disjoint closed sets, we can find two open sets that separate them. In `mathlib`, T₄ implies T₃. * `t5_space`: A T₅ space, also known as a *completely normal Hausdorff space* ## Main results ### T₀ spaces * `is_closed.exists_closed_singleton` Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. * `exists_open_singleton_of_open_finset` Given an open `finset` `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. ### T₁ spaces * `is_closed_map_const`: The constant map is a closed map. * `discrete_of_t1_of_finite`: A finite T₁ space must have the discrete topology. ### T₂ spaces * `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. * `t2_iff_is_closed_diagonal`: A space is T₂ iff the `diagonal` of `α` (that is, the set of all points of the form `(a, a) : α × α`) is closed under the product topology. * `finset_disjoint_finset_opens_of_t2`: Any two disjoint finsets are `separated_nhds`. * Most topological constructions preserve Hausdorffness; these results are part of the typeclass inference system (e.g. `embedding.t2_space`) * `set.eq_on.closure`: If two functions are equal on some set `s`, they are equal on its closure. * `is_compact.is_closed`: All compact sets are closed. * `locally_compact_of_compact_nhds`: If every point has a compact neighbourhood, then the space is locally compact. * `totally_separated_space_of_t1_of_basis_clopen`: If `α` has a clopen basis, then it is a `totally_separated_space`. * `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff it is totally separated. If the space is also compact: * `normal_of_compact_t2`: A compact T₂ space is a `normal_space`. * `connected_components_eq_Inter_clopen`: The connected component of a point is the intersection of all its clopen neighbourhoods. * `compact_t2_tot_disc_iff_tot_sep`: Being a `totally_disconnected_space` is equivalent to being a `totally_separated_space`. * `connected_components.t2`: `connected_components α` is T₂ for `α` T₂ and compact. ### T₃ spaces * `disjoint_nested_nhds`: Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. ## References https://en.wikipedia.org/wiki/Separation_axiom -/ open function set filter topological_space open_locale topology filter classical universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- `separated_nhds` is a predicate on pairs of sub`set`s of a topological space. It holds if the two sub`set`s are contained in disjoint open sets. -/ def separated_nhds : set α → set α → Prop := λ (s t : set α), ∃ U V : (set α), (is_open U) ∧ is_open V ∧ (s ⊆ U) ∧ (t ⊆ V) ∧ disjoint U V lemma separated_nhds_iff_disjoint {s t : set α} : separated_nhds s t ↔ disjoint (𝓝ˢ s) (𝓝ˢ t) := by simp only [(has_basis_nhds_set s).disjoint_iff (has_basis_nhds_set t), separated_nhds, exists_prop, ← exists_and_distrib_left, and.assoc, and.comm, and.left_comm] namespace separated_nhds variables {s s₁ s₂ t t₁ t₂ u : set α} @[symm] lemma symm : separated_nhds s t → separated_nhds t s := λ ⟨U, V, oU, oV, aU, bV, UV⟩, ⟨V, U, oV, oU, bV, aU, disjoint.symm UV⟩ lemma comm (s t : set α) : separated_nhds s t ↔ separated_nhds t s := ⟨symm, symm⟩ lemma preimage [topological_space β] {f : α → β} {s t : set β} (h : separated_nhds s t) (hf : continuous f) : separated_nhds (f ⁻¹' s) (f ⁻¹' t) := let ⟨U, V, oU, oV, sU, tV, UV⟩ := h in ⟨f ⁻¹' U, f ⁻¹' V, oU.preimage hf, oV.preimage hf, preimage_mono sU, preimage_mono tV, UV.preimage f⟩ protected lemma disjoint (h : separated_nhds s t) : disjoint s t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in hd.mono hsU htV lemma disjoint_closure_left (h : separated_nhds s t) : disjoint (closure s) t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in (hd.closure_left hV).mono (closure_mono hsU) htV lemma disjoint_closure_right (h : separated_nhds s t) : disjoint s (closure t) := h.symm.disjoint_closure_left.symm lemma empty_right (s : set α) : separated_nhds s ∅ := ⟨_, _, is_open_univ, is_open_empty, λ a h, mem_univ a, λ a h, by cases h, disjoint_empty _⟩ lemma empty_left (s : set α) : separated_nhds ∅ s := (empty_right _).symm lemma mono (h : separated_nhds s₂ t₂) (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : separated_nhds s₁ t₁ := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in ⟨U, V, hU, hV, hs.trans hsU, ht.trans htV, hd⟩ lemma union_left : separated_nhds s u → separated_nhds t u → separated_nhds (s ∪ t) u := by simpa only [separated_nhds_iff_disjoint, nhds_set_union, disjoint_sup_left] using and.intro lemma union_right (ht : separated_nhds s t) (hu : separated_nhds s u) : separated_nhds s (t ∪ u) := (ht.symm.union_left hu.symm).symm end separated_nhds /-- A T₀ space, also known as a Kolmogorov space, is a topological space such that for every pair `x ≠ y`, there is an open set containing one but not the other. We formulate the definition in terms of the `inseparable` relation. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ ⦃x y : α⦄, inseparable x y → x = y) lemma t0_space_iff_inseparable (α : Type u) [topological_space α] : t0_space α ↔ ∀ (x y : α), inseparable x y → x = y := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma t0_space_iff_not_inseparable (α : Type u) [topological_space α] : t0_space α ↔ ∀ (x y : α), x ≠ y → ¬inseparable x y := by simp only [t0_space_iff_inseparable, ne.def, not_imp_not] lemma inseparable.eq [t0_space α] {x y : α} (h : inseparable x y) : x = y := t0_space.t0 h protected lemma inducing.injective [topological_space β] [t0_space α] {f : α → β} (hf : inducing f) : injective f := λ x y h, inseparable.eq $ hf.inseparable_iff.1 $ h ▸ inseparable.refl _ protected lemma inducing.embedding [topological_space β] [t0_space α] {f : α → β} (hf : inducing f) : embedding f := ⟨hf, hf.injective⟩ lemma embedding_iff_inducing [topological_space β] [t0_space α] {f : α → β} : embedding f ↔ inducing f := ⟨embedding.to_inducing, inducing.embedding⟩ lemma t0_space_iff_nhds_injective (α : Type u) [topological_space α] : t0_space α ↔ injective (𝓝 : α → filter α) := t0_space_iff_inseparable α lemma nhds_injective [t0_space α] : injective (𝓝 : α → filter α) := (t0_space_iff_nhds_injective α).1 ‹_› lemma inseparable_iff_eq [t0_space α] {x y : α} : inseparable x y ↔ x = y := nhds_injective.eq_iff @[simp] lemma nhds_eq_nhds_iff [t0_space α] {a b : α} : 𝓝 a = 𝓝 b ↔ a = b := nhds_injective.eq_iff @[simp] lemma inseparable_eq_eq [t0_space α] : inseparable = @eq α := funext₂ $ λ x y, propext inseparable_iff_eq lemma t0_space_iff_exists_is_open_xor_mem (α : Type u) [topological_space α] : t0_space α ↔ ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)) := by simp only [t0_space_iff_not_inseparable, xor_iff_not_iff, not_forall, exists_prop, inseparable_iff_forall_open] lemma exists_is_open_xor_mem [t0_space α] {x y : α} (h : x ≠ y) : ∃ U : set α, is_open U ∧ xor (x ∈ U) (y ∈ U) := (t0_space_iff_exists_is_open_xor_mem α).1 ‹_› x y h /-- Specialization forms a partial order on a t0 topological space. -/ def specialization_order (α : Type*) [topological_space α] [t0_space α] : partial_order α := { .. specialization_preorder α, .. partial_order.lift (order_dual.to_dual ∘ 𝓝) nhds_injective } instance : t0_space (separation_quotient α) := ⟨λ x' y', quotient.induction_on₂' x' y' $ λ x y h, separation_quotient.mk_eq_mk.2 $ separation_quotient.inducing_mk.inseparable_iff.1 h⟩ theorem minimal_nonempty_closed_subsingleton [t0_space α] {s : set α} (hs : is_closed s) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) : s.subsingleton := begin refine λ x hx y hy, of_not_not (λ hxy, _), rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩, wlog h : x ∈ U ∧ y ∉ U, { exact this hmin y hy x hx (ne.symm hxy) U hUo hU.symm (hU.resolve_left h), }, cases h with hxU hyU, have : s \ U = s := hmin (s \ U) (diff_subset _ _) ⟨y, hy, hyU⟩ (hs.sdiff hUo), exact (this.symm.subset hx).2 hxU end theorem minimal_nonempty_closed_eq_singleton [t0_space α] {s : set α} (hs : is_closed s) (hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_closed_subsingleton hs hmin⟩ /-- Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. -/ theorem is_closed.exists_closed_singleton {α : Type*} [topological_space α] [t0_space α] [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (x : α), x ∈ S ∧ is_closed ({x} : set α) := begin obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne, rcases minimal_nonempty_closed_eq_singleton Vcls Vne hV with ⟨x, rfl⟩, exact ⟨x, Vsub (mem_singleton x), Vcls⟩ end theorem minimal_nonempty_open_subsingleton [t0_space α] {s : set α} (hs : is_open s) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) : s.subsingleton := begin refine λ x hx y hy, of_not_not (λ hxy, _), rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩, wlog h : x ∈ U ∧ y ∉ U, { exact this hs hmin y hy x hx (ne.symm hxy) U hUo hU.symm (hU.resolve_left h), }, cases h with hxU hyU, have : s ∩ U = s := hmin (s ∩ U) (inter_subset_left _ _) ⟨x, hx, hxU⟩ (hs.inter hUo), exact hyU (this.symm.subset hy).2 end theorem minimal_nonempty_open_eq_singleton [t0_space α] {s : set α} (hs : is_open s) (hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_open_subsingleton hs hmin⟩ /-- Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/ theorem exists_open_singleton_of_open_finite [t0_space α] {s : set α} (hfin : s.finite) (hne : s.nonempty) (ho : is_open s) : ∃ x ∈ s, is_open ({x} : set α) := begin lift s to finset α using hfin, induction s using finset.strong_induction_on with s ihs, rcases em (∃ t ⊂ s, t.nonempty ∧ is_open (t : set α)) with ⟨t, hts, htne, hto⟩|ht, { rcases ihs t hts htne hto with ⟨x, hxt, hxo⟩, exact ⟨x, hts.1 hxt, hxo⟩ }, { rcases minimal_nonempty_open_eq_singleton ho hne _ with ⟨x, hx⟩, { exact ⟨x, hx.symm ▸ rfl, hx ▸ ho⟩ }, refine λ t hts htne hto, of_not_not (λ hts', ht _), lift t to finset α using s.finite_to_set.subset hts, exact ⟨t, ssubset_iff_subset_ne.2 ⟨hts, mt finset.coe_inj.2 hts'⟩, htne, hto⟩ } end theorem exists_open_singleton_of_fintype [t0_space α] [finite α] [nonempty α] : ∃ x : α, is_open ({x} : set α) := let ⟨x, _, h⟩ := exists_open_singleton_of_open_finite (set.to_finite _) univ_nonempty is_open_univ in ⟨x, h⟩ lemma t0_space_of_injective_of_continuous [topological_space β] {f : α → β} (hf : function.injective f) (hf' : continuous f) [t0_space β] : t0_space α := ⟨λ x y h, hf $ (h.map hf').eq⟩ protected lemma embedding.t0_space [topological_space β] [t0_space β] {f : α → β} (hf : embedding f) : t0_space α := t0_space_of_injective_of_continuous hf.inj hf.continuous instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) := embedding_subtype_coe.t0_space theorem t0_space_iff_or_not_mem_closure (α : Type u) [topological_space α] : t0_space α ↔ (∀ a b : α, a ≠ b → (a ∉ closure ({b} : set α) ∨ b ∉ closure ({a} : set α))) := by simp only [t0_space_iff_not_inseparable, inseparable_iff_mem_closure, not_and_distrib] instance [topological_space β] [t0_space α] [t0_space β] : t0_space (α × β) := ⟨λ x y h, prod.ext (h.map continuous_fst).eq (h.map continuous_snd).eq⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t0_space (π i)] : t0_space (Π i, π i) := ⟨λ x y h, funext $ λ i, (h.map (continuous_apply i)).eq⟩ lemma t0_space.of_cover (h : ∀ x y, inseparable x y → ∃ s : set α, x ∈ s ∧ y ∈ s ∧ t0_space s) : t0_space α := begin refine ⟨λ x y hxy, _⟩, rcases h x y hxy with ⟨s, hxs, hys, hs⟩, resetI, lift x to s using hxs, lift y to s using hys, rw ← subtype_inseparable_iff at hxy, exact congr_arg coe hxy.eq end lemma t0_space.of_open_cover (h : ∀ x, ∃ s : set α, x ∈ s ∧ is_open s ∧ t0_space s) : t0_space α := t0_space.of_cover $ λ x y hxy, let ⟨s, hxs, hso, hs⟩ := h x in ⟨s, hxs, (hxy.mem_open_iff hso).1 hxs, hs⟩ /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_compl_singleton [t1_space α] {x : α} : is_open ({x}ᶜ : set α) := is_closed_singleton.is_open_compl lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := is_open_compl_singleton @[to_additive] lemma continuous.is_open_mul_support [t1_space α] [has_one α] [topological_space β] {f : β → α} (hf : continuous f) : is_open (mul_support f) := is_open_ne.preimage hf lemma ne.nhds_within_compl_singleton [t1_space α] {x y : α} (h : x ≠ y) : 𝓝[{y}ᶜ] x = 𝓝 x := is_open_ne.nhds_within_eq h lemma ne.nhds_within_diff_singleton [t1_space α] {x y : α} (h : x ≠ y) (s : set α) : 𝓝[s \ {y}] x = 𝓝[s] x := begin rw [diff_eq, inter_comm, nhds_within_inter_of_mem], exact mem_nhds_within_of_mem_nhds (is_open_ne.mem_nhds h) end lemma is_open_set_of_eventually_nhds_within [t1_space α] {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝[≠] x, p y} := begin refine is_open_iff_mem_nhds.mpr (λ a ha, _), filter_upwards [eventually_nhds_nhds_within.mpr ha] with b hb, by_cases a = b, { subst h, exact hb }, { rw (ne.symm h).nhds_within_compl_singleton at hb, exact hb.filter_mono nhds_within_le_nhds } end protected lemma set.finite.is_closed [t1_space α] {s : set α} (hs : set.finite s) : is_closed s := begin rw ← bUnion_of_singleton s, exact is_closed_bUnion hs (λ i hi, is_closed_singleton) end lemma topological_space.is_topological_basis.exists_mem_of_ne [t1_space α] {b : set (set α)} (hb : is_topological_basis b) {x y : α} (h : x ≠ y) : ∃ a ∈ b, x ∈ a ∧ y ∉ a := begin rcases hb.is_open_iff.1 is_open_ne x h with ⟨a, ab, xa, ha⟩, exact ⟨a, ab, xa, λ h, ha h rfl⟩, end lemma filter.coclosed_compact_le_cofinite [t1_space α] : filter.coclosed_compact α ≤ filter.cofinite := λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_coclosed_compact_of_is_closed hs.is_closed variable (α) /-- In a `t1_space`, relatively compact sets form a bornology. Its cobounded filter is `filter.coclosed_compact`. See also `bornology.in_compact` the bornology of sets contained in a compact set. -/ def bornology.relatively_compact [t1_space α] : bornology α := { cobounded := filter.coclosed_compact α, le_cofinite := filter.coclosed_compact_le_cofinite } variable {α} lemma bornology.relatively_compact.is_bounded_iff [t1_space α] {s : set α} : @bornology.is_bounded _ (bornology.relatively_compact α) s ↔ is_compact (closure s) := begin change sᶜ ∈ filter.coclosed_compact α ↔ _, rw filter.mem_coclosed_compact, split, { rintros ⟨t, ht₁, ht₂, hst⟩, rw compl_subset_compl at hst, exact is_compact_of_is_closed_subset ht₂ is_closed_closure (closure_minimal hst ht₁) }, { intros h, exact ⟨closure s, is_closed_closure, h, compl_subset_compl.mpr subset_closure⟩ } end protected lemma finset.is_closed [t1_space α] (s : finset α) : is_closed (s : set α) := s.finite_to_set.is_closed lemma t1_space_tfae (α : Type u) [topological_space α] : tfae [t1_space α, ∀ x, is_closed ({x} : set α), ∀ x, is_open ({x}ᶜ : set α), continuous (@cofinite_topology.of α), ∀ ⦃x y : α⦄, x ≠ y → {y}ᶜ ∈ 𝓝 x, ∀ ⦃x y : α⦄, x ≠ y → ∃ s ∈ 𝓝 x, y ∉ s, ∀ ⦃x y : α⦄, x ≠ y → ∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U, ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y), ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y), ∀ ⦃x y : α⦄, x ⤳ y → x = y] := begin tfae_have : 1 ↔ 2, from ⟨λ h, h.1, λ h, ⟨h⟩⟩, tfae_have : 2 ↔ 3, by simp only [is_open_compl_iff], tfae_have : 5 ↔ 3, { refine forall_swap.trans _, simp only [is_open_iff_mem_nhds, mem_compl_iff, mem_singleton_iff] }, tfae_have : 5 ↔ 6, by simp only [← subset_compl_singleton_iff, exists_mem_subset_iff], tfae_have : 5 ↔ 7, by simp only [(nhds_basis_opens _).mem_iff, subset_compl_singleton_iff, exists_prop, and.assoc, and.left_comm], tfae_have : 5 ↔ 8, by simp only [← principal_singleton, disjoint_principal_right], tfae_have : 8 ↔ 9, from forall_swap.trans (by simp only [disjoint.comm, ne_comm]), tfae_have : 1 → 4, { simp only [continuous_def, cofinite_topology.is_open_iff'], rintro H s (rfl|hs), exacts [is_open_empty, compl_compl s ▸ (@set.finite.is_closed _ _ H _ hs).is_open_compl] }, tfae_have : 4 → 2, from λ h x, (cofinite_topology.is_closed_iff.2 $ or.inr (finite_singleton _)).preimage h, tfae_have : 2 ↔ 10, { simp only [← closure_subset_iff_is_closed, specializes_iff_mem_closure, subset_def, mem_singleton_iff, eq_comm] }, tfae_finish end lemma t1_space_iff_continuous_cofinite_of {α : Type*} [topological_space α] : t1_space α ↔ continuous (@cofinite_topology.of α) := (t1_space_tfae α).out 0 3 lemma cofinite_topology.continuous_of [t1_space α] : continuous (@cofinite_topology.of α) := t1_space_iff_continuous_cofinite_of.mp ‹_› lemma t1_space_iff_exists_open : t1_space α ↔ ∀ (x y), x ≠ y → (∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U) := (t1_space_tfae α).out 0 6 lemma t1_space_iff_disjoint_pure_nhds : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y) := (t1_space_tfae α).out 0 8 lemma t1_space_iff_disjoint_nhds_pure : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y) := (t1_space_tfae α).out 0 7 lemma t1_space_iff_specializes_imp_eq : t1_space α ↔ ∀ ⦃x y : α⦄, x ⤳ y → x = y := (t1_space_tfae α).out 0 9 lemma disjoint_pure_nhds [t1_space α] {x y : α} (h : x ≠ y) : disjoint (pure x) (𝓝 y) := t1_space_iff_disjoint_pure_nhds.mp ‹_› h lemma disjoint_nhds_pure [t1_space α] {x y : α} (h : x ≠ y) : disjoint (𝓝 x) (pure y) := t1_space_iff_disjoint_nhds_pure.mp ‹_› h lemma specializes.eq [t1_space α] {x y : α} (h : x ⤳ y) : x = y := t1_space_iff_specializes_imp_eq.1 ‹_› h lemma specializes_iff_eq [t1_space α] {x y : α} : x ⤳ y ↔ x = y := ⟨specializes.eq, λ h, h ▸ specializes_rfl⟩ @[simp] lemma specializes_eq_eq [t1_space α] : (⤳) = @eq α := funext₂ $ λ x y, propext specializes_iff_eq @[simp] lemma pure_le_nhds_iff [t1_space α] {a b : α} : pure a ≤ 𝓝 b ↔ a = b := specializes_iff_pure.symm.trans specializes_iff_eq @[simp] lemma nhds_le_nhds_iff [t1_space α] {a b : α} : 𝓝 a ≤ 𝓝 b ↔ a = b := specializes_iff_eq instance {α : Type*} : t1_space (cofinite_topology α) := t1_space_iff_continuous_cofinite_of.mpr continuous_id lemma t1_space_antitone {α : Type*} : antitone (@t1_space α) := begin simp only [antitone, t1_space_iff_continuous_cofinite_of, continuous_iff_le_induced], exact λ t₁ t₂ h, h.trans end lemma continuous_within_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {s : set α} {x y : α} {z : β} (hne : y ≠ x) : continuous_within_at (function.update f x z) s y ↔ continuous_within_at f s y := eventually_eq.congr_continuous_within_at (mem_nhds_within_of_mem_nhds $ mem_of_superset (is_open_ne.mem_nhds hne) $ λ y' hy', function.update_noteq hy' _ _) (function.update_noteq hne _ _) lemma continuous_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {x y : α} {z : β} (hne : y ≠ x) : continuous_at (function.update f x z) y ↔ continuous_at f y := by simp only [← continuous_within_at_univ, continuous_within_at_update_of_ne hne] lemma continuous_on_update_iff [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {s : set α} {x : α} {y : β} : continuous_on (function.update f x y) s ↔ continuous_on f (s \ {x}) ∧ (x ∈ s → tendsto f (𝓝[s \ {x}] x) (𝓝 y)) := begin rw [continuous_on, ← and_forall_ne x, and_comm], refine and_congr ⟨λ H z hz, _, λ H z hzx hzs, _⟩ (forall_congr $ λ hxs, _), { specialize H z hz.2 hz.1, rw continuous_within_at_update_of_ne hz.2 at H, exact H.mono (diff_subset _ _) }, { rw continuous_within_at_update_of_ne hzx, refine (H z ⟨hzs, hzx⟩).mono_of_mem (inter_mem_nhds_within _ _), exact is_open_ne.mem_nhds hzx }, { exact continuous_within_at_update_same } end lemma t1_space_of_injective_of_continuous [topological_space β] {f : α → β} (hf : function.injective f) (hf' : continuous f) [t1_space β] : t1_space α := t1_space_iff_specializes_imp_eq.2 $ λ x y h, hf (h.map hf').eq protected lemma embedding.t1_space [topological_space β] [t1_space β] {f : α → β} (hf : embedding f) : t1_space α := t1_space_of_injective_of_continuous hf.inj hf.continuous instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} : t1_space (subtype p) := embedding_subtype_coe.t1_space instance [topological_space β] [t1_space α] [t1_space β] : t1_space (α × β) := ⟨λ ⟨a, b⟩, @singleton_prod_singleton _ _ a b ▸ is_closed_singleton.prod is_closed_singleton⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t1_space (π i)] : t1_space (Π i, π i) := ⟨λ f, univ_pi_singleton f ▸ is_closed_set_pi (λ i hi, is_closed_singleton)⟩ @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, h.specializes.eq⟩ @[simp] lemma compl_singleton_mem_nhds_iff [t1_space α] {x y : α} : {x}ᶜ ∈ 𝓝 y ↔ y ≠ x := is_open_compl_singleton.mem_nhds_iff lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := compl_singleton_mem_nhds_iff.mpr h @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := is_closed_singleton.closure_eq lemma set.subsingleton.closure [t1_space α] {s : set α} (hs : s.subsingleton) : (closure s).subsingleton := hs.induction_on (by simp) $ λ x, by simp @[simp] lemma subsingleton_closure [t1_space α] {s : set α} : (closure s).subsingleton ↔ s.subsingleton := ⟨λ h, h.anti subset_closure, λ h, h.closure⟩ lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} : is_closed_map (function.const α y) := is_closed_map.of_nonempty $ λ s hs h2s, by simp_rw [h2s.image_const, is_closed_singleton] lemma nhds_within_insert_of_ne [t1_space α] {x y : α} {s : set α} (hxy : x ≠ y) : 𝓝[insert y s] x = 𝓝[s] x := begin refine le_antisymm (λ t ht, _) (nhds_within_mono x $ subset_insert y s), obtain ⟨o, ho, hxo, host⟩ := mem_nhds_within.mp ht, refine mem_nhds_within.mpr ⟨o \ {y}, ho.sdiff is_closed_singleton, ⟨hxo, hxy⟩, _⟩, rw [inter_insert_of_not_mem $ not_mem_diff_of_mem (mem_singleton y)], exact (inter_subset_inter (diff_subset _ _) subset.rfl).trans host end /-- If `t` is a subset of `s`, except for one point, then `insert x s` is a neighborhood of `x` within `t`. -/ lemma insert_mem_nhds_within_of_subset_insert [t1_space α] {x y : α} {s t : set α} (hu : t ⊆ insert y s) : insert x s ∈ 𝓝[t] x := begin rcases eq_or_ne x y with rfl|h, { exact mem_of_superset self_mem_nhds_within hu }, refine nhds_within_mono x hu _, rw [nhds_within_insert_of_ne h], exact mem_of_superset self_mem_nhds_within (subset_insert x s) end lemma bInter_basis_nhds [t1_space α] {ι : Sort*} {p : ι → Prop} {s : ι → set α} {x : α} (h : (𝓝 x).has_basis p s) : (⋂ i (h : p i), s i) = {x} := begin simp only [eq_singleton_iff_unique_mem, mem_Inter], refine ⟨λ i hi, mem_of_mem_nhds $ h.mem_of_mem hi, λ y hy, _⟩, contrapose! hy, rcases h.mem_iff.1 (compl_singleton_mem_nhds hy.symm) with ⟨i, hi, hsub⟩, exact ⟨i, hi, λ h, hsub h rfl⟩ end @[simp] lemma compl_singleton_mem_nhds_set_iff [t1_space α] {x : α} {s : set α} : {x}ᶜ ∈ 𝓝ˢ s ↔ x ∉ s := by rwa [is_open_compl_singleton.mem_nhds_set, subset_compl_singleton_iff] @[simp] lemma nhds_set_le_iff [t1_space α] {s t : set α} : 𝓝ˢ s ≤ 𝓝ˢ t ↔ s ⊆ t := begin refine ⟨_, λ h, monotone_nhds_set h⟩, simp_rw [filter.le_def], intros h x hx, specialize h {x}ᶜ, simp_rw [compl_singleton_mem_nhds_set_iff] at h, by_contra hxt, exact h hxt hx, end @[simp] lemma nhds_set_inj_iff [t1_space α] {s t : set α} : 𝓝ˢ s = 𝓝ˢ t ↔ s = t := by { simp_rw [le_antisymm_iff], exact and_congr nhds_set_le_iff nhds_set_le_iff } lemma injective_nhds_set [t1_space α] : function.injective (𝓝ˢ : set α → filter α) := λ s t hst, nhds_set_inj_iff.mp hst lemma strict_mono_nhds_set [t1_space α] : strict_mono (𝓝ˢ : set α → filter α) := monotone_nhds_set.strict_mono_of_injective injective_nhds_set @[simp] lemma nhds_le_nhds_set_iff [t1_space α] {s : set α} {x : α} : 𝓝 x ≤ 𝓝ˢ s ↔ x ∈ s := by rw [← nhds_set_singleton, nhds_set_le_iff, singleton_subset_iff] /-- Removing a non-isolated point from a dense set, one still obtains a dense set. -/ lemma dense.diff_singleton [t1_space α] {s : set α} (hs : dense s) (x : α) [ne_bot (𝓝[≠] x)] : dense (s \ {x}) := hs.inter_of_open_right (dense_compl_singleton x) is_open_compl_singleton /-- Removing a finset from a dense set in a space without isolated points, one still obtains a dense set. -/ lemma dense.diff_finset [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)] {s : set α} (hs : dense s) (t : finset α) : dense (s \ t) := begin induction t using finset.induction_on with x s hxs ih hd, { simpa using hs }, { rw [finset.coe_insert, ← union_singleton, ← diff_diff], exact ih.diff_singleton _, } end /-- Removing a finite set from a dense set in a space without isolated points, one still obtains a dense set. -/ lemma dense.diff_finite [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)] {s : set α} (hs : dense s) {t : set α} (ht : t.finite) : dense (s \ t) := begin convert hs.diff_finset ht.to_finset, exact (finite.coe_to_finset _).symm, end /-- If a function to a `t1_space` tends to some limit `b` at some point `a`, then necessarily `b = f a`. -/ lemma eq_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β} (h : tendsto f (𝓝 a) (𝓝 b)) : f a = b := by_contra $ assume (hfa : f a ≠ b), have fact₁ : {f a}ᶜ ∈ 𝓝 b := compl_singleton_mem_nhds hfa.symm, have fact₂ : tendsto f (pure a) (𝓝 b) := h.comp (tendsto_id'.2 $ pure_le_nhds a), fact₂ fact₁ (eq.refl $ f a) lemma filter.tendsto.eventually_ne [topological_space β] [t1_space β] {α : Type*} {g : α → β} {l : filter α} {b₁ b₂ : β} (hg : tendsto g l (𝓝 b₁)) (hb : b₁ ≠ b₂) : ∀ᶠ z in l, g z ≠ b₂ := hg.eventually (is_open_compl_singleton.eventually_mem hb) lemma continuous_at.eventually_ne [topological_space β] [t1_space β] {g : α → β} {a : α} {b : β} (hg1 : continuous_at g a) (hg2 : g a ≠ b) : ∀ᶠ z in 𝓝 a, g z ≠ b := hg1.tendsto.eventually_ne hg2 /-- To prove a function to a `t1_space` is continuous at some point `a`, it suffices to prove that `f` admits *some* limit at `a`. -/ lemma continuous_at_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β} (h : tendsto f (𝓝 a) (𝓝 b)) : continuous_at f a := show tendsto f (𝓝 a) (𝓝 $ f a), by rwa eq_of_tendsto_nhds h @[simp] lemma tendsto_const_nhds_iff [t1_space α] {l : filter β} [ne_bot l] {c d : α} : tendsto (λ x, c) l (𝓝 d) ↔ c = d := by simp_rw [tendsto, filter.map_const, pure_le_nhds_iff] /-- A point with a finite neighborhood has to be isolated. -/ lemma is_open_singleton_of_finite_mem_nhds {α : Type*} [topological_space α] [t1_space α] (x : α) {s : set α} (hs : s ∈ 𝓝 x) (hsf : s.finite) : is_open ({x} : set α) := begin have A : {x} ⊆ s, by simp only [singleton_subset_iff, mem_of_mem_nhds hs], have B : is_closed (s \ {x}) := (hsf.subset (diff_subset _ _)).is_closed, have C : (s \ {x})ᶜ ∈ 𝓝 x, from B.is_open_compl.mem_nhds (λ h, h.2 rfl), have D : {x} ∈ 𝓝 x, by simpa only [← diff_eq, diff_diff_cancel_left A] using inter_mem hs C, rwa [← mem_interior_iff_mem_nhds, ← singleton_subset_iff, subset_interior_iff_is_open] at D end /-- If the punctured neighborhoods of a point form a nontrivial filter, then any neighborhood is infinite. -/ lemma infinite_of_mem_nhds {α} [topological_space α] [t1_space α] (x : α) [hx : ne_bot (𝓝[≠] x)] {s : set α} (hs : s ∈ 𝓝 x) : set.infinite s := begin refine λ hsf, hx.1 _, rw [← is_open_singleton_iff_punctured_nhds], exact is_open_singleton_of_finite_mem_nhds x hs hsf end lemma discrete_of_t1_of_finite {X : Type*} [topological_space X] [t1_space X] [finite X] : discrete_topology X := begin apply singletons_open_iff_discrete.mp, intros x, rw [← is_closed_compl_iff], exact (set.to_finite _).is_closed end lemma preconnected_space.trivial_of_discrete [preconnected_space α] [discrete_topology α] : subsingleton α := begin rw ←not_nontrivial_iff_subsingleton, rintro ⟨x, y, hxy⟩, rw [ne.def, ←mem_singleton_iff, (is_clopen_discrete _).eq_univ $ singleton_nonempty y] at hxy, exact hxy (mem_univ x) end lemma is_preconnected.infinite_of_nontrivial [t1_space α] {s : set α} (h : is_preconnected s) (hs : s.nontrivial) : s.infinite := begin refine mt (λ hf, (subsingleton_coe s).mp _) (not_subsingleton_iff.mpr hs), haveI := @discrete_of_t1_of_finite s _ _ hf.to_subtype, exact @preconnected_space.trivial_of_discrete _ _ (subtype.preconnected_space h) _ end lemma connected_space.infinite [connected_space α] [nontrivial α] [t1_space α] : infinite α := infinite_univ_iff.mp $ is_preconnected_univ.infinite_of_nontrivial nontrivial_univ lemma singleton_mem_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : {x} ∈ 𝓝[s] x := begin have : ({⟨x, hx⟩} : set s) ∈ 𝓝 (⟨x, hx⟩ : s), by simp [nhds_discrete], simpa only [nhds_within_eq_map_subtype_coe hx, image_singleton] using @image_mem_map _ _ _ (coe : s → α) _ this end /-- The neighbourhoods filter of `x` within `s`, under the discrete topology, is equal to the pure `x` filter (which is the principal filter at the singleton `{x}`.) -/ lemma nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : 𝓝[s] x = pure x := le_antisymm (le_pure_iff.2 $ singleton_mem_nhds_within_of_mem_discrete hx) (pure_le_nhds_within hx) lemma filter.has_basis.exists_inter_eq_singleton_of_mem_discrete {ι : Type*} {p : ι → Prop} {t : ι → set α} {s : set α} [discrete_topology s] {x : α} (hb : (𝓝 x).has_basis p t) (hx : x ∈ s) : ∃ i (hi : p i), t i ∩ s = {x} := begin rcases (nhds_within_has_basis hb s).mem_iff.1 (singleton_mem_nhds_within_of_mem_discrete hx) with ⟨i, hi, hix⟩, exact ⟨i, hi, subset.antisymm hix $ singleton_subset_iff.2 ⟨mem_of_mem_nhds $ hb.mem_of_mem hi, hx⟩⟩ end /-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood that only meets `s` at `x`. -/ lemma nhds_inter_eq_singleton_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝 x, U ∩ s = {x} := by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx /-- For point `x` in a discrete subset `s` of a topological space, there is a set `U` such that 1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`), 2. `U` is disjoint from `s`. -/ lemma disjoint_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝[≠] x, disjoint U s := let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx in ⟨{x}ᶜ ∩ V, inter_mem_nhds_within _ h, (disjoint_iff_inter_eq_empty.mpr (by { rw [inter_assoc, h', compl_inter_self] }))⟩ /-- Let `X` be a topological space and let `s, t ⊆ X` be two subsets. If there is an inclusion `t ⊆ s`, then the topological space structure on `t` induced by `X` is the same as the one obtained by the induced topological space structure on `s`. -/ lemma topological_space.subset_trans {X : Type*} [tX : topological_space X] {s t : set X} (ts : t ⊆ s) : (subtype.topological_space : topological_space t) = (subtype.topological_space : topological_space s).induced (set.inclusion ts) := begin change tX.induced ((coe : s → X) ∘ (set.inclusion ts)) = topological_space.induced (set.inclusion ts) (tX.induced _), rw ← induced_compose, end /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ @[mk_iff] class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀ x y, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v) /-- Two different points can be separated by open sets. -/ lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v := t2_space.t2 x y h lemma t2_space_iff_disjoint_nhds : t2_space α ↔ ∀ x y : α, x ≠ y → disjoint (𝓝 x) (𝓝 y) := begin refine (t2_space_iff α).trans (forall₃_congr $ λ x y hne, _), simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), exists_prop, ← exists_and_distrib_left, and.assoc, and_comm, and.left_comm] end @[simp] lemma disjoint_nhds_nhds [t2_space α] {x y : α} : disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y := ⟨λ hd he, by simpa [he, nhds_ne_bot.ne] using hd, t2_space_iff_disjoint_nhds.mp ‹_› x y⟩ lemma pairwise_disjoint_nhds [t2_space α] : pairwise (disjoint on (𝓝 : α → filter α)) := λ x y, disjoint_nhds_nhds.2 protected lemma set.pairwise_disjoint_nhds [t2_space α] (s : set α) : s.pairwise_disjoint 𝓝 := pairwise_disjoint_nhds.set_pairwise s /-- Points of a finite set can be separated by open sets from each other. -/ lemma set.finite.t2_separation [t2_space α] {s : set α} (hs : s.finite) : ∃ U : α → set α, (∀ x, x ∈ U x ∧ is_open (U x)) ∧ s.pairwise_disjoint U := s.pairwise_disjoint_nhds.exists_mem_filter_basis hs nhds_basis_opens lemma is_open_set_of_disjoint_nhds_nhds : is_open {p : α × α | disjoint (𝓝 p.1) (𝓝 p.2)} := begin simp only [is_open_iff_mem_nhds, prod.forall, mem_set_of_eq], intros x y h, obtain ⟨U, hU, V, hV, hd⟩ := ((nhds_basis_opens x).disjoint_iff (nhds_basis_opens y)).mp h, exact mem_nhds_prod_iff.mpr ⟨U, hU.2.mem_nhds hU.1, V, hV.2.mem_nhds hV.1, λ ⟨x', y'⟩ ⟨hx', hy'⟩, disjoint_of_disjoint_of_mem hd (hU.2.mem_nhds hx') (hV.2.mem_nhds hy')⟩ end @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := t1_space_iff_disjoint_pure_nhds.mpr $ λ x y hne, (disjoint_nhds_nhds.2 hne).mono_left $ pure_le_nhds _ /-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/ lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y := by simp only [t2_space_iff_disjoint_nhds, disjoint_iff, ne_bot_iff, ne.def, not_imp_comm] lemma eq_of_nhds_ne_bot [t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y := t2_iff_nhds.mp ‹_› h lemma t2_space_iff_nhds : t2_space α ↔ ∀ {x y : α}, x ≠ y → ∃ (U ∈ 𝓝 x) (V ∈ 𝓝 y), disjoint U V := by simp only [t2_space_iff_disjoint_nhds, filter.disjoint_iff] lemma t2_separation_nhds [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ disjoint u v := let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h in ⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩ lemma t2_separation_compact_nhds [locally_compact_space α] [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ is_compact u ∧ is_compact v ∧ disjoint u v := by simpa only [exists_prop, ← exists_and_distrib_left, and_comm, and.assoc, and.left_comm] using ((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h) lemma t2_iff_ultrafilter : t2_space α ↔ ∀ {x y : α} (f : ultrafilter α), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y := t2_iff_nhds.trans $ by simp only [←exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp_distrib] lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) := by simp only [t2_space_iff_disjoint_nhds, ← is_open_compl_iff, is_open_iff_mem_nhds, prod.forall, nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff] lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) := t2_iff_is_closed_diagonal.mp ‹_› section separated open separated_nhds finset lemma finset_disjoint_finset_opens_of_t2 [t2_space α] : ∀ (s t : finset α), disjoint s t → separated_nhds (s : set α) t := begin refine induction_on_union _ (λ a b hi d, (hi d.symm).symm) (λ a d, empty_right a) (λ a b ab, _) _, { obtain ⟨U, V, oU, oV, aU, bV, UV⟩ := t2_separation (finset.disjoint_singleton.1 ab), refine ⟨U, V, oU, oV, _, _, UV⟩; exact singleton_subset_set_iff.mpr ‹_› }, { intros a b c ac bc d, apply_mod_cast union_left (ac (disjoint_of_subset_left (a.subset_union_left b) d)) (bc _), exact disjoint_of_subset_left (a.subset_union_right b) d }, end lemma point_disjoint_finset_opens_of_t2 [t2_space α] {x : α} {s : finset α} (h : x ∉ s) : separated_nhds ({x} : set α) s := by exact_mod_cast finset_disjoint_finset_opens_of_t2 {x} s (finset.disjoint_singleton_left.mpr h) end separated lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique_of_eventually_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) : a = b := tendsto_nhds_unique (ha.congr' hfg) hb lemma tendsto_nhds_unique_of_frequently_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α} (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) : a = b := have ∃ᶠ z : α × α in 𝓝 (a, b), z.1 = z.2 := (ha.prod_mk_nhds hb).frequently hfg, not_not.1 $ λ hne, this (is_closed_diagonal.is_open_compl.mem_nhds hne) /-- A T₂.₅ space, also known as a Urysohn space, is a topological space where for every pair `x ≠ y`, there are two open sets, with the intersection of closures empty, one containing `x` and the other `y` . -/ class t2_5_space (α : Type u) [topological_space α]: Prop := (t2_5 : ∀ ⦃x y : α⦄ (h : x ≠ y), disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure)) @[simp] lemma disjoint_lift'_closure_nhds [t2_5_space α] {x y : α} : disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) ↔ x ≠ y := ⟨λ h hxy, by simpa [hxy, nhds_ne_bot.ne] using h, λ h, t2_5_space.t2_5 h⟩ @[priority 100] -- see Note [lower instance priority] instance t2_5_space.t2_space [t2_5_space α] : t2_space α := t2_space_iff_disjoint_nhds.2 $ λ x y hne, (disjoint_lift'_closure_nhds.2 hne).mono (le_lift'_closure _) (le_lift'_closure _) lemma exists_nhds_disjoint_closure [t2_5_space α] {x y : α} (h : x ≠ y) : ∃ (s ∈ 𝓝 x) (t ∈ 𝓝 y), disjoint (closure s) (closure t) := ((𝓝 x).basis_sets.lift'_closure.disjoint_iff (𝓝 y).basis_sets.lift'_closure).1 $ disjoint_lift'_closure_nhds.2 h lemma exists_open_nhds_disjoint_closure [t2_5_space α] {x y : α} (h : x ≠ y) : ∃ u : set α, x ∈ u ∧ is_open u ∧ ∃ v : set α, y ∈ v ∧ is_open v ∧ disjoint (closure u) (closure v) := by simpa only [exists_prop, and.assoc] using ((nhds_basis_opens x).lift'_closure.disjoint_iff (nhds_basis_opens y).lift'_closure).1 (disjoint_lift'_closure_nhds.2 h) section lim variables [t2_space α] {f : filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : @Lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (le_nhds_Lim ⟨a, h⟩) h lemma Lim_eq_iff [ne_bot f] (h : ∃ (a : α), f ≤ nhds a) {a} : @Lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a := ⟨λ c, c ▸ le_nhds_Lim h, Lim_eq⟩ lemma ultrafilter.Lim_eq_iff_le_nhds [compact_space α] {x : α} {F : ultrafilter α} : F.Lim = x ↔ ↑F ≤ 𝓝 x := ⟨λ h, h ▸ F.le_nhds_Lim, Lim_eq⟩ lemma is_open_iff_ultrafilter' [compact_space α] (U : set α) : is_open U ↔ (∀ F : ultrafilter α, F.Lim ∈ U → U ∈ F.1) := begin rw is_open_iff_ultrafilter, refine ⟨λ h F hF, h F.Lim hF F F.le_nhds_Lim, _⟩, intros cond x hx f h, rw [← (ultrafilter.Lim_eq_iff_le_nhds.2 h)] at hx, exact cond _ hx end lemma filter.tendsto.lim_eq {a : α} {f : filter β} [ne_bot f] {g : β → α} (h : tendsto g f (𝓝 a)) : @lim _ _ _ ⟨a⟩ f g = a := Lim_eq h lemma filter.lim_eq_iff {f : filter β} [ne_bot f] {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) {a} : @lim _ _ _ ⟨a⟩ f g = a ↔ tendsto g f (𝓝 a) := ⟨λ c, c ▸ tendsto_nhds_lim h, filter.tendsto.lim_eq⟩ lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) : @lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.tendsto a).lim_eq @[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a := Lim_eq le_rfl @[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a := Lim_nhds a @[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) : @Lim _ _ ⟨a⟩ (𝓝[s] a) = a := by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h; exact Lim_eq inf_le_left @[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) : @lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a := Lim_nhds_within h end lim /-! ### `t2_space` constructions We use two lemmas to prove that various standard constructions generate Hausdorff spaces from Hausdorff spaces: * `separated_by_continuous` says that two points `x y : α` can be separated by open neighborhoods provided that there exists a continuous map `f : α → β` with a Hausdorff codomain such that `f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are Hausdorff spaces. * `separated_by_open_embedding` says that for an open embedding `f : α → β` of a Hausdorff space `α`, the images of two distinct points `x y : α`, `x ≠ y` can be separated by open neighborhoods. We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces. -/ @[priority 100] -- see Note [lower instance priority] instance discrete_topology.to_t2_space {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := ⟨λ x y h, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩ lemma separated_by_continuous {α : Type*} {β : Type*} [topological_space α] [topological_space β] [t2_space β] {f : α → β} (hf : continuous f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, uv.preimage _⟩ lemma separated_by_open_embedding {α β : Type*} [topological_space α] [topological_space β] [t2_space α] {f : α → β} (hf : open_embedding f) {x y : α} (h : x ≠ y) : ∃ u v : set β, is_open u ∧ is_open v ∧ f x ∈ u ∧ f y ∈ v ∧ disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f '' u, f '' v, hf.is_open_map _ uo, hf.is_open_map _ vo, mem_image_of_mem _ xu, mem_image_of_mem _ yv, disjoint_image_of_injective hf.inj uv⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_continuous continuous_subtype_val (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_continuous continuous_fst h₁) (λ h₂, separated_by_continuous continuous_snd h₂)⟩ lemma embedding.t2_space [topological_space β] [t2_space β] {f : α → β} (hf : embedding f) : t2_space α := ⟨λ x y h, separated_by_continuous hf.continuous (hf.inj.ne h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α ⊕ β) := begin constructor, rintros (x|x) (y|y) h, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inl h }, { exact ⟨_, _, is_open_range_inl, is_open_range_inr, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint⟩ }, { exact ⟨_, _, is_open_range_inr, is_open_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint.symm⟩ }, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inr h } end instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [∀a, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_continuous (continuous_apply i) hi⟩ instance sigma.t2_space {ι : Type*} {α : ι → Type*} [Πi, topological_space (α i)] [∀a, t2_space (α a)] : t2_space (Σi, α i) := begin constructor, rintros ⟨i, x⟩ ⟨j, y⟩ neq, rcases em (i = j) with (rfl|h), { replace neq : x ≠ y := λ c, (c.subst neq) rfl, exact separated_by_open_embedding open_embedding_sigma_mk neq }, { exact ⟨_, _, is_open_range_sigma_mk, is_open_range_sigma_mk, ⟨x, rfl⟩, ⟨y, rfl⟩, set.disjoint_left.mpr $ by tidy⟩ } end variables {γ : Type*} [topological_space β] [topological_space γ] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma is_open_ne_fun [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {x:β | f x ≠ g x} := is_open_compl_iff.mpr $ is_closed_eq hf hg /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also `set.eq_on.of_subset_closure` for a more general version. -/ lemma set.eq_on.closure [t2_space α] {s : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous f) (hg : continuous g) : eq_on f g (closure s) := closure_minimal h (is_closed_eq hf hg) /-- If two continuous functions are equal on a dense set, then they are equal. -/ lemma continuous.ext_on [t2_space α] {s : set β} (hs : dense s) {f g : β → α} (hf : continuous f) (hg : continuous g) (h : eq_on f g s) : f = g := funext $ λ x, h.closure hf hg (hs x) lemma eq_on_closure₂' [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α} (h : ∀ (x ∈ s) (y ∈ t), f x y = g x y) (hf₁ : ∀ x, continuous (f x)) (hf₂ : ∀ y, continuous (λ x, f x y)) (hg₁ : ∀ x, continuous (g x)) (hg₂ : ∀ y, continuous (λ x, g x y)) : ∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y := suffices closure s ⊆ ⋂ y ∈ closure t, {x | f x y = g x y}, by simpa only [subset_def, mem_Inter], closure_minimal (λ x hx, mem_Inter₂.2 $ set.eq_on.closure (h x hx) (hf₁ _) (hg₁ _)) $ is_closed_bInter $ λ y hy, is_closed_eq (hf₂ _) (hg₂ _) lemma eq_on_closure₂ [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α} (h : ∀ (x ∈ s) (y ∈ t), f x y = g x y) (hf : continuous (uncurry f)) (hg : continuous (uncurry g)) : ∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y := eq_on_closure₂' h (λ x, continuous_uncurry_left x hf) (λ x, continuous_uncurry_right x hf) (λ y, continuous_uncurry_left y hg) (λ y, continuous_uncurry_right y hg) /-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then `f x = g x` for all `x ∈ t`. See also `set.eq_on.closure`. -/ lemma set.eq_on.of_subset_closure [t2_space α] {s t : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous_on f t) (hg : continuous_on g t) (hst : s ⊆ t) (hts : t ⊆ closure s) : eq_on f g t := begin intros x hx, haveI : (𝓝[s] x).ne_bot, from mem_closure_iff_cluster_pt.mp (hts hx), exact tendsto_nhds_unique_of_eventually_eq ((hf x hx).mono_left $ nhds_within_mono _ hst) ((hg x hx).mono_left $ nhds_within_mono _ hst) (h.eventually_eq_of_mem self_mem_nhds_within) end lemma function.left_inverse.closed_range [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : is_closed (range g) := have eq_on (g ∘ f) id (closure $ range g), from h.right_inv_on_range.eq_on.closure (hg.comp hf) continuous_id, is_closed_of_closure_subset $ λ x hx, calc x = g (f x) : (this hx).symm ... ∈ _ : mem_range_self _ lemma function.left_inverse.closed_embedding [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : closed_embedding g := ⟨h.embedding hf hg, h.closed_range hf hg⟩ lemma is_compact_is_compact_separated [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) (hst : disjoint s t) : separated_nhds s t := by simp only [separated_nhds, prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal.is_open_compl hst /-- In a `t2_space`, every compact set is closed. -/ lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s := is_open_compl_iff.1 $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := is_compact_is_compact_separated hs is_compact_singleton (disjoint_singleton_right.2 hx) in ⟨v, (uv.mono_left $ show s ≤ u, from su).subset_compl_left, vo, by simpa using xv⟩ @[simp] lemma filter.coclosed_compact_eq_cocompact [t2_space α] : coclosed_compact α = cocompact α := by simp [coclosed_compact, cocompact, infi_and', and_iff_right_of_imp is_compact.is_closed] @[simp] lemma bornology.relatively_compact_eq_in_compact [t2_space α] : bornology.relatively_compact α = bornology.in_compact α := by rw bornology.ext_iff; exact filter.coclosed_compact_eq_cocompact /-- If `V : ι → set α` is a decreasing family of compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhd_of_compact'` where we don't need to assume each `V i` closed because it follows from compactness since `α` is assumed to be Hausdorff. -/ lemma exists_subset_nhds_of_is_compact [t2_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhds_of_is_compact' hV hV_cpct (λ i, (hV_cpct i).is_closed) hU lemma compact_exhaustion.is_closed [t2_space α] (K : compact_exhaustion α) (n : ℕ) : is_closed (K n) := (K.is_compact n).is_closed lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∩ t) := hs.inter_right $ ht.is_closed lemma is_compact_closure_of_subset_compact [t2_space α] {s t : set α} (ht : is_compact t) (h : s ⊆ t) : is_compact (closure s) := is_compact_of_is_closed_subset ht is_closed_closure (closure_minimal h ht.is_closed) @[simp] lemma exists_compact_superset_iff [t2_space α] {s : set α} : (∃ K, is_compact K ∧ s ⊆ K) ↔ is_compact (closure s) := ⟨λ ⟨K, hK, hsK⟩, is_compact_closure_of_subset_compact hK hsK, λ h, ⟨closure s, h, subset_closure⟩⟩ lemma image_closure_of_is_compact [t2_space β] {s : set α} (hs : is_compact (closure s)) {f : α → β} (hf : continuous_on f (closure s)) : f '' closure s = closure (f '' s) := subset.antisymm hf.image_closure $ closure_minimal (image_subset f subset_closure) (hs.image_of_continuous_on hf).is_closed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K) (hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := begin obtain ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩ := is_compact_is_compact_separated (hK.diff hU) (hK.diff hV) (by rwa [disjoint_iff_inter_eq_empty, diff_inter_diff, diff_eq_empty]), exact ⟨_, _, hK.diff h1O₁, hK.diff h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO.inter_eq, diff_empty]⟩ end /-- A continuous map from a compact space to a Hausdorff space is a closed map. -/ protected lemma continuous.is_closed_map [compact_space α] [t2_space β] {f : α → β} (h : continuous f) : is_closed_map f := λ s hs, (hs.is_compact.image h).is_closed /-- An injective continuous map from a compact space to a Hausdorff space is a closed embedding. -/ lemma continuous.closed_embedding [compact_space α] [t2_space β] {f : α → β} (h : continuous f) (hf : function.injective f) : closed_embedding f := closed_embedding_of_continuous_injective_closed h hf h.is_closed_map /-- A surjective continuous map from a compact space to a Hausdorff space is a quotient map. -/ lemma quotient_map.of_surjective_continuous [compact_space α] [t2_space β] {f : α → β} (hsurj : surjective f) (hcont : continuous f) : quotient_map f := hcont.is_closed_map.to_quotient_map hcont hsurj section open finset function /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s) {ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := begin classical, induction t using finset.induction with x t hx ih generalizing U hU s hs hsC, { refine ⟨λ _, ∅, λ i, is_compact_empty, λ i, empty_subset _, _⟩, simpa only [subset_empty_iff, Union_false, Union_empty] using hsC }, simp only [finset.set_bUnion_insert] at hsC, simp only [finset.mem_insert] at hU, have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi), rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩, rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩, refine ⟨update K x K₁, _, _, _⟩, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h1K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }}, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h2K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }}, { simp only [set_bUnion_insert_update _ hx, hK, h3K] } end end lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := is_compact_is_compact_separated is_compact_singleton (kc.diff uo) (disjoint_singleton_left.2 $ λ h, h.2 xu) in have wn : wᶜ ∈ 𝓝 x, from mem_nhds_iff.mpr ⟨v, vw.subset_compl_right, vo, singleton_subset_iff.mp xv⟩, ⟨k \ w, filter.inter_mem kx wn, subset.trans (diff_subset_comm.mp kuw) un, kc.diff wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, is_open_univ.mem_nhds trivial, is_compact_univ⟩) /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) := begin rcases exists_compact_mem_nhds x with ⟨K, hKc, hxK⟩, rcases mem_nhds_iff.1 hxK with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h2t, h3t, is_compact_closure_of_subset_compact hKc h1t⟩ end /-- In a locally compact T₂ space, every compact set has an open neighborhood with compact closure. -/ lemma exists_open_superset_and_is_compact_closure [locally_compact_space α] [t2_space α] {K : set α} (hK : is_compact K) : ∃ V, is_open V ∧ K ⊆ V ∧ is_compact (closure V) := begin rcases exists_compact_superset hK with ⟨K', hK', hKK'⟩, refine ⟨interior K', is_open_interior, hKK', is_compact_closure_of_subset_compact hK' interior_subset⟩, end /-- In a locally compact T₂ space, given a compact set `K` inside an open set `U`, we can find a open set `V` between these sets with compact closure: `K ⊆ V` and the closure of `V` is inside `U`. -/ lemma exists_open_between_and_is_compact_closure [locally_compact_space α] [t2_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V, is_open V ∧ K ⊆ V ∧ closure V ⊆ U ∧ is_compact (closure V) := begin rcases exists_compact_between hK hU hKU with ⟨V, hV, hKV, hVU⟩, exact ⟨interior V, is_open_interior, hKV, (closure_minimal interior_subset hV.is_closed).trans hVU, is_compact_closure_of_subset_compact hV interior_subset⟩, end lemma is_preirreducible_iff_subsingleton [t2_space α] {S : set α} : is_preirreducible S ↔ S.subsingleton := begin refine ⟨λ h x hx y hy, _, set.subsingleton.is_preirreducible⟩, by_contradiction e, obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e, exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono $ inter_subset_right _ _).not_disjoint h', end alias is_preirreducible_iff_subsingleton ↔ is_preirreducible.subsingleton _ attribute [protected] is_preirreducible.subsingleton lemma is_irreducible_iff_singleton [t2_space α] {S : set α} : is_irreducible S ↔ ∃ x, S = {x} := by rw [is_irreducible, is_preirreducible_iff_subsingleton, exists_eq_singleton_iff_nonempty_subsingleton] /-- There does not exist a nontrivial preirreducible T₂ space. -/ lemma not_preirreducible_nontrivial_t2 (α) [topological_space α] [preirreducible_space α] [nontrivial α] [t2_space α] : false := (preirreducible_space.is_preirreducible_univ α).subsingleton.not_nontrivial nontrivial_univ end separation section regular_space /-- A topological space is called a *regular space* if for any closed set `s` and `a ∉ s`, there exist disjoint open sets `U ⊇ s` and `V ∋ a`. We formulate this condition in terms of `disjoint`ness of filters `𝓝ˢ s` and `𝓝 a`. -/ @[mk_iff] class regular_space (X : Type u) [topological_space X] : Prop := (regular : ∀ {s : set X} {a}, is_closed s → a ∉ s → disjoint (𝓝ˢ s) (𝓝 a)) lemma regular_space_tfae (X : Type u) [topological_space X] : tfae [regular_space X, ∀ (s : set X) (a ∉ closure s), disjoint (𝓝ˢ s) (𝓝 a), ∀ (a : X) (s : set X), disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s, ∀ (a : X) (s ∈ 𝓝 a), ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s, ∀ a : X, (𝓝 a).lift' closure ≤ 𝓝 a, ∀ a : X, (𝓝 a).lift' closure = 𝓝 a] := begin tfae_have : 1 ↔ 5, { rw [regular_space_iff, (@compl_surjective (set X) _).forall, forall_swap], simp only [is_closed_compl_iff, mem_compl_iff, not_not, @and_comm (_ ∈ _), (nhds_basis_opens _).lift'_closure.le_basis_iff (nhds_basis_opens _), and_imp, (nhds_basis_opens _).disjoint_iff_right, exists_prop, ← subset_interior_iff_mem_nhds_set, interior_compl, compl_subset_compl] }, tfae_have : 5 → 6, from λ h a, (h a).antisymm (𝓝 _).le_lift'_closure, tfae_have : 6 → 4, { intros H a s hs, rw [← H] at hs, rcases (𝓝 a).basis_sets.lift'_closure.mem_iff.mp hs with ⟨U, hU, hUs⟩, exact ⟨closure U, mem_of_superset hU subset_closure, is_closed_closure, hUs⟩ }, tfae_have : 4 → 2, { intros H s a ha, have ha' : sᶜ ∈ 𝓝 a, by rwa [← mem_interior_iff_mem_nhds, interior_compl], rcases H _ _ ha' with ⟨U, hU, hUc, hUs⟩, refine disjoint_of_disjoint_of_mem disjoint_compl_left _ hU, rwa [← subset_interior_iff_mem_nhds_set, hUc.is_open_compl.interior_eq, subset_compl_comm] }, tfae_have : 2 → 3, { refine λ H a s, ⟨λ hd has, mem_closure_iff_nhds_ne_bot.mp has _, H s a⟩, exact (hd.symm.mono_right $ @principal_le_nhds_set _ _ s).eq_bot }, tfae_have : 3 → 1, from λ H, ⟨λ s a hs ha, (H _ _).mpr $ hs.closure_eq.symm ▸ ha⟩, tfae_finish end lemma regular_space.of_lift'_closure (h : ∀ a : α, (𝓝 a).lift' closure = 𝓝 a) : regular_space α := iff.mpr ((regular_space_tfae α).out 0 5) h lemma regular_space.of_basis {ι : α → Sort*} {p : Π a, ι a → Prop} {s : Π a, ι a → set α} (h₁ : ∀ a, (𝓝 a).has_basis (p a) (s a)) (h₂ : ∀ a i, p a i → is_closed (s a i)) : regular_space α := regular_space.of_lift'_closure $ λ a, (h₁ a).lift'_closure_eq_self (h₂ a) lemma regular_space.of_exists_mem_nhds_is_closed_subset (h : ∀ (a : α) (s ∈ 𝓝 a), ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s) : regular_space α := iff.mpr ((regular_space_tfae α).out 0 3) h variables [regular_space α] {a : α} {s : set α} lemma disjoint_nhds_set_nhds : disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s := iff.mp ((regular_space_tfae α).out 0 2) ‹_› _ _ lemma disjoint_nhds_nhds_set : disjoint (𝓝 a) (𝓝ˢ s) ↔ a ∉ closure s := disjoint.comm.trans disjoint_nhds_set_nhds lemma exists_mem_nhds_is_closed_subset {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s := iff.mp ((regular_space_tfae α).out 0 3) ‹_› _ _ h lemma closed_nhds_basis (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id := has_basis_self.2 (λ _, exists_mem_nhds_is_closed_subset) lemma lift'_nhds_closure (a : α) : (𝓝 a).lift' closure = 𝓝 a := (closed_nhds_basis a).lift'_closure_eq_self (λ s hs, hs.2) lemma filter.has_basis.nhds_closure {ι : Sort*} {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) : (𝓝 a).has_basis p (λ i, closure (s i)) := lift'_nhds_closure a ▸ h.lift'_closure lemma has_basis_nhds_closure (a : α) : (𝓝 a).has_basis (λ s, s ∈ 𝓝 a) closure := (𝓝 a).basis_sets.nhds_closure lemma has_basis_opens_closure (a : α) : (𝓝 a).has_basis (λ s, a ∈ s ∧ is_open s) closure := (nhds_basis_opens a).nhds_closure lemma topological_space.is_topological_basis.nhds_basis_closure {B : set (set α)} (hB : topological_space.is_topological_basis B) (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ s ∈ B) closure := by simpa only [and_comm] using hB.nhds_has_basis.nhds_closure lemma topological_space.is_topological_basis.exists_closure_subset {B : set (set α)} (hB : topological_space.is_topological_basis B) {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ B, a ∈ t ∧ closure t ⊆ s := by simpa only [exists_prop, and.assoc] using hB.nhds_has_basis.nhds_closure.mem_iff.mp h lemma disjoint_nhds_nhds_iff_not_specializes {a b : α} : disjoint (𝓝 a) (𝓝 b) ↔ ¬a ⤳ b := by rw [← nhds_set_singleton, disjoint_nhds_set_nhds, specializes_iff_mem_closure] lemma specializes_comm {a b : α} : a ⤳ b ↔ b ⤳ a := by simp only [← disjoint_nhds_nhds_iff_not_specializes.not_left, disjoint.comm] alias specializes_comm ↔ specializes.symm _ lemma specializes_iff_inseparable {a b : α} : a ⤳ b ↔ inseparable a b := ⟨λ h, h.antisymm h.symm, le_of_eq⟩ lemma is_closed_set_of_specializes : is_closed {p : α × α | p.1 ⤳ p.2} := by simp only [← is_open_compl_iff, compl_set_of, ← disjoint_nhds_nhds_iff_not_specializes, is_open_set_of_disjoint_nhds_nhds] lemma is_closed_set_of_inseparable : is_closed {p : α × α | inseparable p.1 p.2} := by simp only [← specializes_iff_inseparable, is_closed_set_of_specializes] protected lemma inducing.regular_space [topological_space β] {f : β → α} (hf : inducing f) : regular_space β := regular_space.of_basis (λ b, by { rw [hf.nhds_eq_comap b], exact (closed_nhds_basis _).comap _ }) $ λ b s hs, hs.2.preimage hf.continuous lemma regular_space_induced (f : β → α) : @regular_space β (induced f ‹_›) := by { letI := induced f ‹_›, exact inducing.regular_space ⟨rfl⟩ } lemma regular_space_Inf {X} {T : set (topological_space X)} (h : ∀ t ∈ T, @regular_space X t) : @regular_space X (Inf T) := begin letI := Inf T, have : ∀ a, (𝓝 a).has_basis (λ If : Σ I : set T, I → set X, If.1.finite ∧ ∀ i : If.1, If.2 i ∈ @nhds X i a ∧ is_closed[↑i] (If.2 i)) (λ If, ⋂ i : If.1, If.snd i), { intro a, rw [nhds_Inf, ← infi_subtype''], exact has_basis_infi (λ t : T, @closed_nhds_basis X t (h t t.2) a) }, refine regular_space.of_basis this (λ a If hIf, is_closed_Inter $ λ i, _), exact (hIf.2 i).2.mono (Inf_le (i : T).2) end lemma regular_space_infi {ι X} {t : ι → topological_space X} (h : ∀ i, @regular_space X (t i)) : @regular_space X (infi t) := regular_space_Inf $ forall_range_iff.mpr h lemma regular_space.inf {X} {t₁ t₂ : topological_space X} (h₁ : @regular_space X t₁) (h₂ : @regular_space X t₂) : @regular_space X (t₁ ⊓ t₂) := by { rw [inf_eq_infi], exact regular_space_infi (bool.forall_bool.2 ⟨h₂, h₁⟩) } instance {p : α → Prop} : regular_space (subtype p) := embedding_subtype_coe.to_inducing.regular_space instance [topological_space β] [regular_space β] : regular_space (α × β) := (regular_space_induced prod.fst).inf (regular_space_induced prod.snd) instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [∀ i, regular_space (π i)] : regular_space (Π i, π i) := regular_space_infi $ λ i, regular_space_induced _ end regular_space section t3 /-- A T₃ space is a T₀ space which is a regular space. Any T₃ space is a T₁ space, a T₂ space, and a T₂.₅ space. -/ class t3_space (α : Type u) [topological_space α] extends t0_space α, regular_space α : Prop @[priority 100] -- see Note [lower instance priority] instance t3_space.t2_5_space [t3_space α] : t2_5_space α := begin refine ⟨λ x y hne, _⟩, rw [lift'_nhds_closure, lift'_nhds_closure], have aux : x ∉ closure {y} ∨ y ∉ closure {x}, from (t0_space_iff_or_not_mem_closure α).mp infer_instance x y hne, wlog H : x ∉ closure ({y} : set α), { refine (this y x hne.symm aux.symm (aux.resolve_left H)).symm }, { rwa [← disjoint_nhds_nhds_set, nhds_set_singleton] at H }, end protected lemma embedding.t3_space [topological_space β] [t3_space β] {f : α → β} (hf : embedding f) : t3_space α := { to_t0_space := hf.t0_space, to_regular_space := hf.to_inducing.regular_space } instance subtype.t3_space [t3_space α] {p : α → Prop} : t3_space (subtype p) := embedding_subtype_coe.t3_space instance [topological_space β] [t3_space α] [t3_space β] : t3_space (α × β) := ⟨⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t3_space (π i)] : t3_space (Π i, π i) := ⟨⟩ /-- Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. -/ lemma disjoint_nested_nhds [t3_space α] {x y : α} (h : x ≠ y) : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ disjoint U₁ U₂ := begin rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩, rcases exists_mem_nhds_is_closed_subset (U₁_op.mem_nhds x_in) with ⟨V₁, V₁_in, V₁_closed, h₁⟩, rcases exists_mem_nhds_is_closed_subset (U₂_op.mem_nhds y_in) with ⟨V₂, V₂_in, V₂_closed, h₂⟩, exact ⟨U₁, mem_of_superset V₁_in h₁, V₁, V₁_in, U₂, mem_of_superset V₂_in h₂, V₂, V₂_in, V₁_closed, V₂_closed, U₁_op, U₂_op, h₁, h₂, H⟩ end open separation_quotient /-- The `separation_quotient` of a regular space is a T₃ space. -/ instance [regular_space α] : t3_space (separation_quotient α) := { regular := λ s, surjective_mk.forall.2 $ λ a hs ha, by { rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk, comap_mk_nhds_set], exact regular_space.regular (hs.preimage continuous_mk) ha } } end t3 section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → separated_nhds s t) theorem normal_separation [normal_space α] {s t : set α} (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : separated_nhds s t := normal_space.normal s t H1 H2 H3 theorem normal_exists_closure_subset [normal_space α] {s t : set α} (hs : is_closed s) (ht : is_open t) (hst : s ⊆ t) : ∃ u, is_open u ∧ s ⊆ u ∧ closure u ⊆ t := begin have : disjoint s tᶜ, from set.disjoint_left.mpr (λ x hxs hxt, hxt (hst hxs)), rcases normal_separation hs (is_closed_compl_iff.2 ht) this with ⟨s', t', hs', ht', hss', htt', hs't'⟩, refine ⟨s', hs', hss', subset.trans (closure_minimal _ (is_closed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩, exact λ x hxs hxt, hs't'.le_bot ⟨hxs, hxt⟩ end @[priority 100] -- see Note [lower instance priority] instance normal_space.t3_space [normal_space α] : t3_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation hs is_closed_singleton (disjoint_singleton_right.mpr hxs) in disjoint_of_disjoint_of_mem huv (hu.mem_nhds_set.2 hsu) (hv.mem_nhds $ hxv rfl) } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := ⟨λ s t hs ht, is_compact_is_compact_separated hs.is_compact ht.is_compact⟩ protected lemma closed_embedding.normal_space [topological_space β] [normal_space β] {f : α → β} (hf : closed_embedding f) : normal_space α := { to_t1_space := hf.to_embedding.t1_space, normal := begin intros s t hs ht hst, have H : separated_nhds (f '' s) (f '' t), from normal_space.normal (f '' s) (f '' t) (hf.is_closed_map s hs) (hf.is_closed_map t ht) (disjoint_image_of_injective hf.inj hst), exact (H.preimage hf.continuous).mono (subset_preimage_image _ _) (subset_preimage_image _ _) end } namespace separation_quotient /-- The `separation_quotient` of a normal space is a T₄ space. We don't have separate typeclasses for normal spaces (without T₁ assumption) and T₄ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [normal_space α] : normal_space (separation_quotient α) := { normal := λ s t hs ht hd, separated_nhds_iff_disjoint.2 $ begin rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set], exact separated_nhds_iff_disjoint.1 (normal_separation (hs.preimage continuous_mk) (ht.preimage continuous_mk) (hd.preimage mk)) end } end separation_quotient variable (α) /-- A T₃ topological space with second countable topology is a normal space. This lemma is not an instance to avoid a loop. -/ lemma normal_space_of_t3_second_countable [second_countable_topology α] [t3_space α] : normal_space α := begin have key : ∀ {s t : set α}, is_closed t → disjoint s t → ∃ U : set (countable_basis α), (s ⊆ ⋃ u ∈ U, ↑u) ∧ (∀ u ∈ U, disjoint (closure ↑u) t) ∧ ∀ n : ℕ, is_closed (⋃ (u ∈ U) (h : encodable.encode u ≤ n), closure (u : set α)), { intros s t hc hd, rw disjoint_left at hd, have : ∀ x ∈ s, ∃ U ∈ countable_basis α, x ∈ U ∧ disjoint (closure U) t, { intros x hx, rcases (is_basis_countable_basis α).exists_closure_subset (hc.is_open_compl.mem_nhds (hd hx)) with ⟨u, hu, hxu, hut⟩, exact ⟨u, hu, hxu, disjoint_left.2 hut⟩ }, choose! U hu hxu hd, set V : s → countable_basis α := maps_to.restrict _ _ _ hu, refine ⟨range V, _, forall_range_iff.2 $ subtype.forall.2 hd, λ n, _⟩, { rw bUnion_range, exact λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu x hx⟩ }, { simp only [← supr_eq_Union, supr_and'], exact is_closed_bUnion (((finite_le_nat n).preimage_embedding (encodable.encode' _)).subset $ inter_subset_right _ _) (λ u hu, is_closed_closure) } }, refine ⟨λ s t hs ht hd, _⟩, rcases key ht hd with ⟨U, hsU, hUd, hUc⟩, rcases key hs hd.symm with ⟨V, htV, hVd, hVc⟩, refine ⟨⋃ u ∈ U, ↑u \ ⋃ (v ∈ V) (hv : encodable.encode v ≤ encodable.encode u), closure ↑v, ⋃ v ∈ V, ↑v \ ⋃ (u ∈ U) (hu : encodable.encode u ≤ encodable.encode v), closure ↑u, is_open_bUnion $ λ u hu, (is_open_of_mem_countable_basis u.2).sdiff (hVc _), is_open_bUnion $ λ v hv, (is_open_of_mem_countable_basis v.2).sdiff (hUc _), λ x hx, _, λ x hx, _, _⟩, { rcases mem_Union₂.1 (hsU hx) with ⟨u, huU, hxu⟩, refine mem_bUnion huU ⟨hxu, _⟩, simp only [mem_Union], rintro ⟨v, hvV, -, hxv⟩, exact (hVd v hvV).le_bot ⟨hxv, hx⟩ }, { rcases mem_Union₂.1 (htV hx) with ⟨v, hvV, hxv⟩, refine mem_bUnion hvV ⟨hxv, _⟩, simp only [mem_Union], rintro ⟨u, huU, -, hxu⟩, exact (hUd u huU).le_bot ⟨hxu, hx⟩ }, { simp only [disjoint_left, mem_Union, mem_diff, not_exists, not_and, not_forall, not_not], rintro a ⟨u, huU, hau, haV⟩ v hvV hav, cases le_total (encodable.encode u) (encodable.encode v) with hle hle, exacts [⟨u, huU, hle, subset_closure hau⟩, (haV _ hvV hle $ subset_closure hav).elim] } end end normality section completely_normal /-- A topological space `α` is a *completely normal Hausdorff space* if each subspace `s : set α` is a normal Hausdorff space. Equivalently, `α` is a `T₁` space and for any two sets `s`, `t` such that `closure s` is disjoint with `t` and `s` is disjoint with `closure t`, there exist disjoint neighbourhoods of `s` and `t`. -/ class t5_space (α : Type u) [topological_space α] extends t1_space α : Prop := (completely_normal : ∀ ⦃s t : set α⦄, disjoint (closure s) t → disjoint s (closure t) → disjoint (𝓝ˢ s) (𝓝ˢ t)) export t5_space (completely_normal) lemma embedding.t5_space [topological_space β] [t5_space β] {e : α → β} (he : embedding e) : t5_space α := begin haveI := he.t1_space, refine ⟨λ s t hd₁ hd₂, _⟩, simp only [he.to_inducing.nhds_set_eq_comap], refine disjoint_comap (completely_normal _ _), { rwa [← subset_compl_iff_disjoint_left, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_left] }, { rwa [← subset_compl_iff_disjoint_right, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_right] } end /-- A subspace of a `T₅` space is a `T₅` space. -/ instance [t5_space α] {p : α → Prop} : t5_space {x // p x} := embedding_subtype_coe.t5_space /-- A `T₅` space is a `T₄` space. -/ @[priority 100] -- see Note [lower instance priority] instance t5_space.to_normal_space [t5_space α] : normal_space α := ⟨λ s t hs ht hd, separated_nhds_iff_disjoint.2 $ completely_normal (by rwa [hs.closure_eq]) (by rwa [ht.closure_eq])⟩ open separation_quotient /-- The `separation_quotient` of a completely normal space is a T₅ space. We don't have separate typeclasses for completely normal spaces (without T₁ assumption) and T₅ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [t5_space α] : t5_space (separation_quotient α) := { completely_normal := λ s t hd₁ hd₂, begin rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set], apply t5_space.completely_normal; rw [← preimage_mk_closure], exacts [hd₁.preimage mk, hd₂.preimage mk] end } end completely_normal /-- In a compact t2 space, the connected component of a point equals the intersection of all its clopen neighbourhoods. -/ lemma connected_component_eq_Inter_clopen [t2_space α] [compact_space α] (x : α) : connected_component x = ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := begin apply eq_of_subset_of_subset connected_component_subset_Inter_clopen, -- Reduce to showing that the clopen intersection is connected. refine is_preconnected.subset_connected_component _ (mem_Inter.2 (λ Z, Z.2.2)), -- We do this by showing that any disjoint cover by two closed sets implies -- that one of these closed sets must contain our whole thing. -- To reduce to the case where the cover is disjoint on all of `α` we need that `s` is closed have hs : is_closed (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), Z : set α) := is_closed_Inter (λ Z, Z.2.1.2), rw (is_preconnected_iff_subset_of_fully_disjoint_closed hs), intros a b ha hb hab ab_disj, haveI := @normal_of_compact_t2 α _ _ _, -- Since our space is normal, we get two larger disjoint open sets containing the disjoint -- closed sets. If we can show that our intersection is a subset of any of these we can then -- "descend" this to show that it is a subset of either a or b. rcases normal_separation ha hb ab_disj with ⟨u, v, hu, hv, hau, hbv, huv⟩, -- If we can find a clopen set around x, contained in u ∪ v, we get a disjoint decomposition -- Z = Z ∩ u ∪ Z ∩ v of clopen sets. The intersection of all clopen neighbourhoods will then lie -- in whichever of u or v x lies in and hence will be a subset of either a or b. rsuffices ⟨Z, H⟩ : ∃ (Z : set α), is_clopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v, { have H1 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv, rw [union_comm] at H, have H2 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu huv.symm, by_cases (x ∈ u), -- The x ∈ u case. { left, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ u, { replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab, replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ u := this, exact disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) }, { apply subset.trans _ (inter_subset_right Z u), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ u, H1, mem_inter H.2.1 h⟩ } }, -- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case. have h1 : x ∈ v, { cases (mem_union x u v).1 (mem_of_subset_of_mem (subset.trans hab (union_subset_union hau hbv)) (mem_Inter.2 (λ i, i.2.2))) with h1 h1, { exfalso, exact h h1}, { exact h1} }, right, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ v, { replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ v := this, exact (huv.symm.mono this hau).left_le_of_le_sup_left hab }, { apply subset.trans _ (inter_subset_right Z v), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ v, H2, mem_inter H.2.1 h1⟩ } }, -- Now we find the required Z. We utilize the fact that X \ u ∪ v will be compact, -- so there must be some finite intersection of clopen neighbourhoods of X disjoint to it, -- but a finite intersection of clopen sets is clopen so we let this be our Z. have H1 := (hu.union hv).is_closed_compl.is_compact.inter_Inter_nonempty (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z) (λ Z, Z.2.1.2), rw [←not_disjoint_iff_nonempty_inter, imp_not_comm, not_forall] at H1, cases H1 (disjoint_compl_left_iff_subset.2 $ hab.trans $ union_subset_union hau hbv) with Zi H2, refine ⟨(⋂ (U ∈ Zi), subtype.val U), _, _, _⟩, { exact is_clopen_bInter_finset (λ Z hZ, Z.2.1) }, { exact mem_Inter₂.2 (λ Z hZ, Z.2.2) }, { rwa [←disjoint_compl_left_iff_subset, disjoint_iff_inter_eq_empty, ←not_nonempty_iff_eq_empty] } end section profinite /-- A T1 space with a clopen basis is totally separated. -/ lemma totally_separated_space_of_t1_of_basis_clopen [t1_space α] (h : is_topological_basis {s : set α | is_clopen s}) : totally_separated_space α := begin constructor, rintros x - y - hxy, rcases h.mem_nhds_iff.mp (is_open_ne.mem_nhds hxy) with ⟨U, hU, hxU, hyU⟩, exact ⟨U, Uᶜ, hU.is_open, hU.compl.is_open, hxU, λ h, hyU h rfl, (union_compl_self U).superset, disjoint_compl_right⟩ end variables [t2_space α] [compact_space α] /-- A compact Hausdorff space is totally disconnected if and only if it is totally separated, this is also true for locally compact spaces. -/ theorem compact_t2_tot_disc_iff_tot_sep : totally_disconnected_space α ↔ totally_separated_space α := begin split, { intro h, constructor, rintros x - y -, contrapose!, intros hyp, suffices : x ∈ connected_component y, by simpa [totally_disconnected_space_iff_connected_component_singleton.1 h y, mem_singleton_iff], rw [connected_component_eq_Inter_clopen, mem_Inter], rintro ⟨w : set α, hw : is_clopen w, hy : y ∈ w⟩, by_contra hx, exact hyp wᶜ w hw.2.is_open_compl hw.1 hx hy (@is_compl_compl _ w _).symm.codisjoint.top_le disjoint_compl_left }, apply totally_separated_space.totally_disconnected_space, end variables [totally_disconnected_space α] lemma nhds_basis_clopen (x : α) : (𝓝 x).has_basis (λ s : set α, x ∈ s ∧ is_clopen s) id := ⟨λ U, begin split, { have : connected_component x = {x}, from totally_disconnected_space_iff_connected_component_singleton.mp ‹_› x, rw connected_component_eq_Inter_clopen at this, intros hU, let N := {Z // is_clopen Z ∧ x ∈ Z}, rsuffices ⟨⟨s, hs, hs'⟩, hs''⟩ : ∃ Z : N, Z.val ⊆ U, { exact ⟨s, ⟨hs', hs⟩, hs''⟩ }, haveI : nonempty N := ⟨⟨univ, is_clopen_univ, mem_univ x⟩⟩, have hNcl : ∀ Z : N, is_closed Z.val := (λ Z, Z.property.1.2), have hdir : directed superset (λ Z : N, Z.val), { rintros ⟨s, hs, hxs⟩ ⟨t, ht, hxt⟩, exact ⟨⟨s ∩ t, hs.inter ht, ⟨hxs, hxt⟩⟩, inter_subset_left s t, inter_subset_right s t⟩ }, have h_nhd: ∀ y ∈ (⋂ Z : N, Z.val), U ∈ 𝓝 y, { intros y y_in, erw [this, mem_singleton_iff] at y_in, rwa y_in }, exact exists_subset_nhds_of_compact_space hdir hNcl h_nhd }, { rintro ⟨V, ⟨hxV, V_op, -⟩, hUV : V ⊆ U⟩, rw mem_nhds_iff, exact ⟨V, hUV, V_op, hxV⟩ } end⟩ lemma is_topological_basis_clopen : is_topological_basis {s : set α | is_clopen s} := begin apply is_topological_basis_of_open_of_nhds (λ U (hU : is_clopen U), hU.1), intros x U hxU U_op, have : U ∈ 𝓝 x, from is_open.mem_nhds U_op hxU, rcases (nhds_basis_clopen x).mem_iff.mp this with ⟨V, ⟨hxV, hV⟩, hVU : V ⊆ U⟩, use V, tauto end /-- Every member of an open set in a compact Hausdorff totally disconnected space is contained in a clopen set contained in the open set. -/ lemma compact_exists_clopen_in_open {x : α} {U : set α} (is_open : is_open U) (memU : x ∈ U) : ∃ (V : set α) (hV : is_clopen V), x ∈ V ∧ V ⊆ U := (is_topological_basis.mem_nhds_iff is_topological_basis_clopen).1 (is_open.mem_nhds memU) end profinite section locally_compact variables {H : Type*} [topological_space H] [locally_compact_space H] [t2_space H] /-- A locally compact Hausdorff totally disconnected space has a basis with clopen elements. -/ lemma loc_compact_Haus_tot_disc_of_zero_dim [totally_disconnected_space H] : is_topological_basis {s : set H | is_clopen s} := begin refine is_topological_basis_of_open_of_nhds (λ u hu, hu.1) _, rintros x U memU hU, obtain ⟨s, comp, xs, sU⟩ := exists_compact_subset hU memU, obtain ⟨t, h, ht, xt⟩ := mem_interior.1 xs, let u : set s := (coe : s → H)⁻¹' (interior s), have u_open_in_s : is_open u := is_open_interior.preimage continuous_subtype_coe, let X : s := ⟨x, h xt⟩, have Xu : X ∈ u := xs, haveI : compact_space s := is_compact_iff_compact_space.1 comp, obtain ⟨V : set s, clopen_in_s, Vx, V_sub⟩ := compact_exists_clopen_in_open u_open_in_s Xu, have V_clopen : is_clopen ((coe : s → H) '' V), { refine ⟨_, (comp.is_closed.closed_embedding_subtype_coe.closed_iff_image_closed).1 clopen_in_s.2⟩, let v : set u := (coe : u → s)⁻¹' V, have : (coe : u → H) = (coe : s → H) ∘ (coe : u → s) := rfl, have f0 : embedding (coe : u → H) := embedding_subtype_coe.comp embedding_subtype_coe, have f1 : open_embedding (coe : u → H), { refine ⟨f0, _⟩, { have : set.range (coe : u → H) = interior s, { rw [this, set.range_comp, subtype.range_coe, subtype.image_preimage_coe], apply set.inter_eq_self_of_subset_left interior_subset, }, rw this, apply is_open_interior } }, have f2 : is_open v := clopen_in_s.1.preimage continuous_subtype_coe, have f3 : (coe : s → H) '' V = (coe : u → H) '' v, { rw [this, image_comp coe coe, subtype.image_preimage_coe, inter_eq_self_of_subset_left V_sub] }, rw f3, apply f1.is_open_map v f2 }, refine ⟨coe '' V, V_clopen, by simp [Vx, h xt], _⟩, transitivity s, { simp }, assumption end /-- A locally compact Hausdorff space is totally disconnected if and only if it is totally separated. -/ theorem loc_compact_t2_tot_disc_iff_tot_sep : totally_disconnected_space H ↔ totally_separated_space H := begin split, { introI h, exact totally_separated_space_of_t1_of_basis_clopen loc_compact_Haus_tot_disc_of_zero_dim }, apply totally_separated_space.totally_disconnected_space, end end locally_compact /-- `connected_components α` is Hausdorff when `α` is Hausdorff and compact -/ instance connected_components.t2 [t2_space α] [compact_space α] : t2_space (connected_components α) := begin -- Proof follows that of: https://stacks.math.columbia.edu/tag/0900 -- Fix 2 distinct connected components, with points a and b refine ⟨connected_components.surjective_coe.forall₂.2 $ λ a b ne, _⟩, rw connected_components.coe_ne_coe at ne, have h := connected_component_disjoint ne, -- write ↑b as the intersection of all clopen subsets containing it rw [connected_component_eq_Inter_clopen b, disjoint_iff_inter_eq_empty] at h, -- Now we show that this can be reduced to some clopen containing `↑b` being disjoint to `↑a` obtain ⟨U, V, hU, ha, hb, rfl⟩ : ∃ (U : set α) (V : set (connected_components α)), is_clopen U ∧ connected_component a ∩ U = ∅ ∧ connected_component b ⊆ U ∧ coe ⁻¹' V = U, { cases is_closed_connected_component.is_compact.elim_finite_subfamily_closed _ _ h with fin_a ha, swap, { exact λ Z, Z.2.1.2 }, -- This clopen and its complement will separate the connected components of `a` and `b` set U : set α := (⋂ (i : {Z // is_clopen Z ∧ b ∈ Z}) (H : i ∈ fin_a), i), have hU : is_clopen U := is_clopen_bInter_finset (λ i j, i.2.1), exact ⟨U, coe '' U, hU, ha, subset_Inter₂ (λ Z _, Z.2.1.connected_component_subset Z.2.2), (connected_components_preimage_image U).symm ▸ hU.bUnion_connected_component_eq⟩ }, rw connected_components.quotient_map_coe.is_clopen_preimage at hU, refine ⟨Vᶜ, V, hU.compl.is_open, hU.is_open, _, hb mem_connected_component, disjoint_compl_left⟩, exact λ h, flip set.nonempty.ne_empty ha ⟨a, mem_connected_component, h⟩, end
1a929c0818f8899c589e709a2203427b1dc5fcd3
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/linear_algebra/bilinear_form.lean
abf02c746a125c58340d25f0cf0ea232e28265d3
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
9,120
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import linear_algebra.tensor_product /-! # Bilinear form This file defines a bilinear form over a module. Basic ideas such as orthogonality are also introduced, as well as reflexivive, symmetric and alternating bilinear forms. A bilinear form on an R-module V, is a function from V x V to R, that is linear in both arguments ## Notations Given any term B of type bilin_form, due to a coercion, can use the notation B x y to refer to the function field, ie. B x y = B.bilin x y. ## References * https://en.wikipedia.org/wiki/Bilinear_form ## Tags Bilinear form, -/ universes u v /-- A bilinear form over a module -/ structure bilin_form (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] := (bilin : β → β → α) (bilin_add_left : ∀ (x y z : β), bilin (x + y) z = bilin x z + bilin y z) (bilin_smul_left : ∀ (a : α) (x y : β), bilin (a • x) y = a * (bilin x y)) (bilin_add_right : ∀ (x y z : β), bilin x (y + z) = bilin x y + bilin x z) (bilin_smul_right : ∀ (a : α) (x y : β), bilin x (a • y) = a * (bilin x y)) def linear_map.to_bilin {χ : Type u} {β : Type v} [comm_ring χ] [add_comm_group β] [module χ β] (f : β →ₗ[χ] β →ₗ[χ] χ) : bilin_form χ β := { bilin := λ x y, f x y, bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z, bilin_smul_left := λ a x y, by {rw linear_map.map_smul, rw linear_map.smul_apply, rw smul_eq_mul}, bilin_add_right := λ x y z, linear_map.map_add (f x) y z, bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y } namespace bilin_form variables {α : Type u} {β : Type v} [ring α] [add_comm_group β] [module α β] {B : bilin_form α β} instance : has_coe_to_fun (bilin_form α β) := ⟨_, λ B, B.bilin⟩ lemma add_left (x y z : β) : B (x + y) z = B x z + B y z := bilin_add_left B x y z lemma smul_left (a : α) (x y : β) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y lemma add_right (x y z : β) : B x (y + z) = B x y + B x z := bilin_add_right B x y z lemma smul_right (a : α) (x y : β) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y lemma zero_left (x : β) : B 0 x = 0 := by {rw [←@zero_smul α _ _ _ _ (0 : β), smul_left, zero_mul]} lemma zero_right (x : β) : B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : β), smul_right, ring.zero_mul] lemma neg_left (x y : β) : B (-x) y = -(B x y) := by rw [←@neg_one_smul α _ _, smul_left, neg_one_mul] lemma neg_right (x y : β) : B x (-y) = -(B x y) := by rw [←@neg_one_smul α _ _, smul_right, neg_one_mul] lemma sub_left (x y z : β) : B (x - y) z = B x z - B y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl lemma sub_right (x y z : β) : B x (y - z) = B x y - B x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl variable {D : bilin_form α β} @[extensionality] lemma ext (H : ∀ (x y : β), B x y = D x y) : B = D := by {cases B, cases D, congr, funext, exact H _ _} instance : add_comm_group (bilin_form α β) := { add := λ B D, { bilin := λ x y, B x y + D x y, bilin_add_left := λ x y z, by {rw add_left, rw add_left, simp}, bilin_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]}, bilin_add_right := λ x y z, by {rw add_right, rw add_right, simp}, bilin_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }, add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc}, zero := { bilin := λ x y, 0, bilin_add_left := λ x y z, (add_zero 0).symm, bilin_smul_left := λ a x y, (mul_zero a).symm, bilin_add_right := λ x y z, (zero_add 0).symm, bilin_smul_right := λ a x y, (mul_zero a).symm }, zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add}, add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero}, neg := λ B, { bilin := λ x y, - (B.1 x y), bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add], bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm], bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add], bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] }, add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self}, add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm} } section variables {χ : Type*} [comm_ring χ] [module χ β] (F : bilin_form χ β) (f : β → β) instance to_module : module χ (bilin_form χ β) := { smul := λ c B, { bilin := λ x y, c * B x y, bilin_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, left_distrib]}, bilin_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_left, ←mul_assoc, mul_comm c, mul_assoc]}, bilin_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_right, left_distrib]}, bilin_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_right, ←mul_assoc, mul_comm c, mul_assoc]} }, smul_add := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw left_distrib}, add_smul := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw right_distrib}, mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_assoc}, one_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_mul}, zero_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_mul}, smul_zero := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_zero} } def to_linear_map : β →ₗ[χ] β →ₗ[χ] χ := linear_map.mk₂ χ F.1 (bilin_add_left F) (bilin_smul_left F) (bilin_add_right F) (bilin_smul_right F) def bilin_linear_map_equiv : (bilin_form χ β) ≃ₗ[χ] (β →ₗ[χ] β →ₗ[χ] χ) := { to_fun := to_linear_map, add := λ B D, rfl, smul := λ a B, rfl, inv_fun := linear_map.to_bilin, left_inv := λ B, by {ext, refl}, right_inv := λ B, by {ext, refl} } end /-- The proposition that two elements of a bilinear form space are orthogonal -/ def is_ortho (B : bilin_form α β) (x y : β) : Prop := B x y = 0 lemma ortho_zero (x : β) : is_ortho B (0 : β) x := zero_left x section variables {γ : Type*} [domain γ] [module γ β] {G : bilin_form γ β} theorem ortho_smul_left {x y : β} {a : γ} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [smul_left, H, ring.mul_zero] }, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end theorem ortho_smul_right {x y : β} {a : γ} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [smul_right, H, ring.mul_zero] }, { rw [smul_right, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end end end bilin_form namespace refl_bilin_form open refl_bilin_form bilin_form variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] {B : bilin_form α β} /-- The proposition that a bilinear form is reflexive -/ def is_refl (B : bilin_form α β) : Prop := ∀ (x y : β), B x y = 0 → B y x = 0 variable (H : is_refl B) lemma eq_zero : ∀ {x y : β}, B x y = 0 → B y x = 0 := λ x y, H x y lemma ortho_sym {x y : β} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩ end refl_bilin_form namespace sym_bilin_form open sym_bilin_form bilin_form variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] {B : bilin_form α β} /-- The proposition that a bilinear form is symmetric -/ def is_sym (B : bilin_form α β) : Prop := ∀ (x y : β), B x y = B y x variable (H : is_sym B) lemma sym (x y : β) : B x y = B y x := H x y lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1 lemma ortho_sym {x y : β} : is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H) end sym_bilin_form namespace alt_bilin_form open alt_bilin_form bilin_form variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] {B : bilin_form α β} /-- The proposition that a bilinear form is alternating -/ def is_alt (B : bilin_form α β) : Prop := ∀ (x : β), B x x = 0 variable (H : is_alt B) include H lemma self_eq_zero (x : β) : B x x = 0 := H x lemma neg (x y : β) : - B x y = B y x := begin have H1 : B (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end end alt_bilin_form
86a5ca6300616210c58e7ec7fe613d7db84b6a90
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/793b.lean
391c4504c7e10ceab22ac54e9b24c1e4a408a55b
[ "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
41
lean
import data.rat open rat check (1.2:rat)
512e3dbbc73c0c74bd8b15f77ca5d699f2553c9e
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/constructions.lean
8bfb4a98bea1f0feaa1c2d385a33c0751563bff8
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,342
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U], have V_op : is_open V := U_op, obtain ⟨w, w_in_V, w_in_range⟩ : (V ∩ s).nonempty := mem_closure_iff.1 (H y) V V_op y_in_V, exact ⟨_, w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := (hf.comp continuous_fst).prod_mk (hg.comp continuous_snd) lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), set.prod u v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { rw nhds_prod_eq, exact ha.prod hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := (hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at) lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := have hf : continuous_at f (x, y).fst, from hf, have hg : continuous_at g (x, y).snd, from hg, hf.prod_map hg lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := begin rw is_open_map_iff_nhds_le, rintro ⟨x, y⟩ s hs, rcases mem_nhds_prod_iff.1 hs with ⟨tx, htx, ty, hty, ht⟩, simp only [subset_def, prod.forall, mem_prod] at ht, exact mem_sets_of_superset htx (λ x hx, ht x y ⟨hx, mem_of_nhds hty⟩) end /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ rw is_open_map_iff_nhds_le, rintro ⟨x, y⟩ s hs, rcases mem_nhds_prod_iff.1 hs with ⟨tx, htx, ty, hty, ht⟩, simp only [subset_def, prod.forall, mem_prod] at ht, exact mem_sets_of_superset hty (λ y hy, ht x y ⟨mem_of_nhds htx, hy⟩) end /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) := have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩ lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, have : inl ⁻¹' (@inl α β '' u) = u := preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this, have : inr ⁻¹' (@inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, have : inl ⁻¹' (@inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this, have : inr ⁻¹' (@inr α β '' u) = u := preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := begin rw is_open_sum_iff, convert and.intro is_open_univ is_open_empty; { ext, simp } end, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := begin rw is_open_sum_iff, convert and.intro is_open_empty is_open_univ; { ext, simp } end, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_eq $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_coe (by simp [subtype.range_coe]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced $ assume x y, subtype.eq end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom /-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is continuous. -/ @[continuity] lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} : continuous (λ x : π i, function.update f i x) := begin refine continuous_pi (λj, _), by_cases h : j = i, { rw h, simpa using continuous_id }, { simpa [h] using continuous_const } end lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by simp [nhds_pi, filter.tendsto_comap_iff] lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
b27c908bae616015bed14ba512fb6376e8078f45
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/archive/imo/imo1988_q6.lean
aebb4e890a51227c7db740d409a35d40e0d0303d
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
13,855
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.nat.prime import data.rat.basic import order.well_founded import tactic.linarith import tactic.omega /-! # IMO1988 Q6 and constant descent Vieta jumping Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers could not tackle the question within the given time limit. The problem lead to the introduction of a new proof technique, so called “Vieta jumping”. In this file we formalise constant descent Vieta jumping, and apply this to prove Q6 of IMO1988. To illustrate the technique, we also prove a similar result. -/ -- open_locale classical local attribute [instance] classical.prop_decidable local attribute [simp] pow_two /-- Constant descent Vieta jumping. This proof technique allows one to prove an arbitrary proposition `claim`, by running a descent argument on a hyperbola `H` in the first quadrant of the plane, under the following conditions: * `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`. * `H_symm` : The hyperbola has a symmetry along the diagonal in the plane. * `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true. * `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true. * `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`, with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`. For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate. (In question 6 of IMO1988, where this proof technique was first developped, the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`, and the predicate `H` would be `λ a b, a * a + b * b = (a * b + 1) * k`.) To ensure that the predicate `H` actually describes a hyperbola, the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation. Finally, `H_quad` is the proof obligation that the quadratic equation `(y:ℤ) * y - B x * y + C x = 0` describes the same hyperbola as the predicate `H`. For extra flexibility, one must provide a predicate `base` on the integral points in the plane. In the descent step `H_desc` this will give the user the additional assumption that the point `(x,y)` does not lie in this base locus. The user must provide a proof that the proposition `claim` is true if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus. If such a base locus is not necessary, once can simply let it be `λ x y, false`. -/ lemma constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop} (h₀ : H x y) (B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop) (H_quad : ∀ {x y}, H x y ↔ (y:ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x) (H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim) (H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y → ∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x) (H_base : ∀ {x y}, H x y → base x y → claim) : claim := begin -- First of all, we may assume that x ≤ y. -- We justify this using H_symm. wlog hxy : x ≤ y, swap, { rw H_symm at h₀, solve_by_elim }, -- In fact, we can easily deal with the case x = y. by_cases x_eq_y : x = y, {subst x_eq_y, exact H_diag h₀}, -- Hence we may assume that x < y. replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y, clear x_eq_y, -- Consider the upper branch of the hyperbola defined by H. let upper_branch : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2}, -- Note that the point p = (x,y) lies on the upper branch. let p : ℕ × ℕ := ⟨x,y⟩, have hp : p ∈ upper_branch := ⟨h₀, hxy⟩, -- We also consider the exceptional set of solutions (a,b) that satisfy -- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus. let exceptional : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1) }, -- Let S be the projection of the upper branch on to the y-axis -- after removing the exceptional locus. let S : set ℕ := prod.snd '' (upper_branch \ exceptional), -- The strategy is to show that the exceptional locus in nonempty -- by running a descent argument that starts with the given point p = (x,y). -- Our assumptions ensure that we can then prove the claim. suffices exc : exceptional.nonempty, { -- Suppose that there exists an element in the exceptional locus. simp [exceptional, -add_comm, set.nonempty] at exc, -- Let (a,b) be such an element, and consider all the possible cases. rcases exc with ⟨a, b, hH, hb⟩, rcases hb with _|rfl|rfl|hB|hB, -- The first three cases are rather easy to solve. { solve_by_elim }, { rw H_symm at hH, solve_by_elim }, { solve_by_elim }, -- The final two cases are very similar. all_goals { -- Consider the quadratic equation that (a,b) satisfies. rw H_quad at hH, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩, -- By substitutions we find that b = 0 or b = a. simp [hB] at hV₁, subst hV₁, rw [← int.coe_nat_zero] at *, rw ← H_quad at h_root, -- And hence we are done by H_zero and H_diag. solve_by_elim } }, -- To finish the main proof, we need to show that the exceptional locus is nonempty. -- So we assume that the exceptional locus is empty, and work towards dering a contradiction. rw ← set.ne_empty_iff_nonempty, assume exceptional_empty, -- Observe that S is nonempty. have S_nonempty : S.nonempty, { -- It contains the image of p. use p.2, apply set.mem_image_of_mem, -- After all, we assumed that the exceptional locus is empty. rwa [exceptional_empty, set.diff_empty], }, -- We are now set for an infinite descent argument. -- Let m be the smallest element of the nonempty set S. let m : ℕ := well_founded.min nat.lt_wf S S_nonempty, have m_mem : m ∈ S := well_founded.min_mem nat.lt_wf S S_nonempty, have m_min : ∀ k ∈ S, ¬ k < m := λ k hk, well_founded.not_lt_min nat.lt_wf S S_nonempty hk, -- It suffices to show that there is point (a,b) with b ∈ S and b < m. suffices hp' : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m, { rcases hp' with ⟨p', p'_mem, p'_small⟩, solve_by_elim }, -- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S -- and that does not lie in the exceptional locus. rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩, -- This means that m_y = m, -- and the conditions H(m_x, m_y) and m_x < m_y are satisfied. simp [exceptional, hHm] at mx_lt_my h_base m_eq, push_neg at h_base, -- Finally, it also means that (m_x, m_y) does not lie in the base locus, -- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y. rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩, replace hmx : 0 < mx := pos_iff_ne_zero.mpr hmx, -- Consider the quadratic equation that (m_x, m_y) satisfies. have h_quad := hHm, rw H_quad at h_quad, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩, -- No we rewrite Vietas formulas a bit, and apply the descent step. replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁, rw mul_comm at hV₂, have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂, -- This means that we may assume that c ≥ 0 and c ≤ m_x. cases Hc with c_nonneg c_lt, -- In other words, c is a natural number. lift c to ℕ using c_nonneg, -- Recall that we are trying find a point (a,b) such that b ∈ S and b < m. -- We claim that p' = (c, m_x) does the job. let p' : ℕ × ℕ := ⟨c, mx⟩, use p', -- The second condition is rather easy to check, so we do that first. split, swap, { rwa m_eq at mx_lt_my }, -- Now we need to show that p' projects onto S. In other words, that c ∈ S. -- We do that, by showing that it lies in the upper branch -- (which is sufficient, because we assumed that the exceptional locus is empty). apply set.mem_image_of_mem, rw [exceptional_empty, set.diff_empty], -- Now we are ready to prove that p' = (c, m_x) lies on the upper branch. -- We need to check two conditions: H(c, m_x) and c < m_x. split; dsimp only, { -- The first condition is not so hard. After all, c is the other root of the quadratic equation. rw [H_symm, H_quad], simpa using h_root, }, { -- For the second condition, we note that it suffices to check that c ≠ m_x. suffices hc : c ≠ mx, { refine lt_of_le_of_ne _ hc, exact_mod_cast c_lt, }, -- However, recall that B(m_x) ≠ m_x + m_y. -- If c = m_x, we can prove B(m_x) = m_x + m_y. contrapose! hm_B₂, subst c, simp [hV₁], } -- Hence p' = (c, m_x) lies on the upper branch, and we are done. end /--Question 6 of IMO1988. If a and b are two natural numbers such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square.-/ lemma imo1988_q6 {a b : ℕ} (h : (a*b+1) ∣ a^2 + b^2) : ∃ d, d^2 = (a^2 + b^2)/(a*b + 1) := begin rcases h with ⟨k, hk⟩, rw [hk, nat.mul_div_cancel_left _ (nat.succ_pos (a*b))], simp only [pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x - k) (λ x y, false); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, norm_cast, simp, ring, }, { -- Show that the solution set is symmetric in a and b. intros x y, simp [add_comm (x*x), mul_comm x], }, { -- Show that the claim is true if b = 0. suffices : ∀ a, a * a = k → ∃ d, d * d = k, by simpa, rintros x rfl, use x }, { -- Show that the claim is true if a = b. intros x hx, suffices : k ≤ 1, { rw [nat.le_add_one_iff, nat.le_zero_iff] at this, rcases this with rfl|rfl, { use 0, simp }, { use 1, simp } }, contrapose! hx with k_lt_one, apply ne_of_lt, calc x*x + x*x = x*x * 2 : by rw mul_two ... ≤ x*x * k : nat.mul_le_mul_left (x*x) k_lt_one ... < (x*x + 1) * k : by linarith }, { -- Show the descent step. intros x y hx x_lt_y hxky h z h_root hV₁ hV₀, split, { dsimp [-sub_eq_add_neg] at *, have hpos : z*z + x*x > 0, { apply add_pos_of_nonneg_of_pos, { apply mul_self_nonneg }, { apply mul_pos; exact_mod_cast hx }, }, have hzx : z*z + x*x = (z * x + 1) * k, { rw [← sub_eq_zero, ← h_root], ring, }, rw hzx at hpos, replace hpos : z * x + 1 > 0 := pos_of_mul_pos_right hpos (int.coe_zero_le k), replace hpos : z * x ≥ 0 := int.le_of_lt_add_one hpos, apply nonneg_of_mul_nonneg_right hpos (by exact_mod_cast hx), }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, calc z * y > x*x : by apply mul_lt_mul'; linarith ... ≥ x*x - k : sub_le_self _ (int.coe_zero_le k) }, }, { -- There is no base case in this application of Vieta jumping. simp }, end /- The following example illustrates the use of constant descent Vieta jumping in the presence of a non-trivial base case. -/ example {a b : ℕ} (h : a*b ∣ a^2 + b^2 + 1) : 3*a*b = a^2 + b^2 + 1 := begin rcases h with ⟨k, hk⟩, suffices : k = 3, { simp * at *, ring, }, simp only [pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x + 1) (λ x y, x ≤ 1); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, simp, ring, }, { -- Show that the solution set is symmetric in a and b. cc }, { -- Show that the claim is true if b = 0. simp }, { -- Show that the claim is true if a = b. intros x hx, have x_sq_dvd : x*x ∣ x*x*k := dvd_mul_right (x*x) k, rw ← hx at x_sq_dvd, obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [nat.dvd_add_self_left, add_assoc] using x_sq_dvd, obtain ⟨rfl,rfl⟩ : x = 1 ∧ y = 1 := by simpa [nat.mul_eq_one_iff] using hy.symm, simpa using hx.symm, }, { -- Show the descent step. intros x y x_lt_y hx h_base h z h_root hV₁ hV₀, split, { have zy_pos : z * y ≥ 0, { rw hV₀, exact_mod_cast (nat.zero_le _) }, apply nonneg_of_mul_nonneg_right zy_pos, linarith }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, push_neg at h_base, calc z * y > x * y : by apply mul_lt_mul_of_pos_right; linarith ... ≥ x * (x + 1) : by apply mul_le_mul; linarith ... > x * x + 1 : begin rw [mul_add, mul_one], apply add_lt_add_left, assumption_mod_cast end, } }, { -- Show the base case. intros x y h h_base, obtain rfl|rfl : x = 0 ∨ x = 1 := by rwa [nat.le_add_one_iff, nat.le_zero_iff] at h_base, { simpa using h, }, { simp only [mul_one, one_mul, add_comm, zero_add] at h, have y_dvd : y ∣ y * k := dvd_mul_right y k, rw [← h, ← add_assoc, nat.dvd_add_left (dvd_mul_left y y)] at y_dvd, obtain rfl|rfl : y = 1 ∨ y = 2 := nat.prime_two.2 y y_dvd, all_goals { ring at h, omega } } } end
8d22f82f4367b1b6eed7832368acae955fd1739c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/simp_dsimp.lean
eb0f14616b5f6e7ffc7651ac0d5f53e4a2e84b97
[ "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
306
lean
opaque A : Nat → Type opaque f (x : Nat) (a : A x) : Nat example (x : Nat) (a : A (x + 0)) : f (x + 0) a = x := by simp trace_state -- ⊢ f x a = x sorry example (x : Nat) (a : A (x + 0)) : f (x + 0) a = x := by simp (config := { dsimp := false }) trace_state -- ⊢ f (x + 0) a = x sorry
5f8f5b6f1417128e6b4321090e11dd0d5e9fa3ff
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/group_power/lemmas.lean
56a4139af2701aba203e0383383e059196e5afab
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
33,338
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.invertible import data.int.cast /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `zsmul` which require additional imports besides those available in `algebra.group_power.basic`. -/ open function int nat universes u v w x y z u₁ u₂ variables {α : Type*} {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n := begin refine eq_nat_cast' (⟨_, _, _⟩ : ℕ →+ A) _, { simp [zero_nsmul] }, { simp [add_nsmul] }, { simp } end instance invertible_pow (m : M) [invertible m] (n : ℕ) : invertible (m ^ n) := { inv_of := ⅟ m ^ n, inv_of_mul_self := by rw [← (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow], mul_inv_of_self := by rw [← (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] } lemma inv_of_pow (m : M) [invertible m] (n : ℕ) [invertible (m ^ n)] : ⅟(m ^ n) = ⅟m ^ n := @invertible_unique M _ (m ^ n) (m ^ n) _ (invertible_pow m n) rfl lemma is_unit.pow {m : M} (n : ℕ) : is_unit m → is_unit (m ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ @[simp] lemma is_unit_pow_succ_iff {m : M} {n : ℕ} : is_unit (m ^ (n + 1)) ↔ is_unit m := begin refine ⟨_, λ h, h.pow _⟩, rw [pow_succ, ((commute.refl _).pow_right _).is_unit_mul_iff], exact and.left end lemma is_unit_pos_pow_iff {m : M} : ∀ {n : ℕ} (h : 0 < n), is_unit (m ^ n) ↔ is_unit m | (n + 1) _ := is_unit_pow_succ_iff /-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/ def invertible_of_pow_succ_eq_one (x : M) (n : ℕ) (hx : x ^ n.succ = 1) : invertible x := ⟨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hx⟩ /-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/ def invertible_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : invertible x := begin apply invertible_of_pow_succ_eq_one x (n - 1), convert hx, exact tsub_add_cancel_of_le (nat.succ_le_of_lt hn), end lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin haveI := invertible_of_pow_eq_one x n hx hn, exact is_unit_of_invertible x end lemma smul_pow [mul_action M N] [is_scalar_tower M N N] [smul_comm_class M N N] (k : M) (x : N) (p : ℕ) : (k • x) ^ p = k ^ p • x ^ p := begin induction p with p IH, { simp }, { rw [pow_succ', IH, smul_mul_smul, ←pow_succ', ←pow_succ'] } end @[simp] lemma smul_pow' [mul_distrib_mul_action M N] (x : M) (m : N) (n : ℕ) : x • m ^ n = (x • m) ^ n := begin induction n with n ih, { rw [pow_zero, pow_zero], exact smul_one x }, { rw [pow_succ, pow_succ], exact (smul_mul' x m (m ^ n)).trans (congr_arg _ ih) } end end monoid section sub_neg_monoid variables [sub_neg_monoid A] lemma zsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n := by cases n; simp end sub_neg_monoid section group variables [group G] @[to_additive add_one_zsmul] lemma zpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+n] := by rw [int.neg_succ_of_nat_eq, zpow_neg, neg_add, neg_add_cancel_right, zpow_neg, ← int.coe_nat_succ, zpow_coe_nat, zpow_coe_nat, pow_succ _ n, mul_inv_rev, inv_mul_cancel_right] @[to_additive zsmul_sub_one] lemma zpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← zpow_add_one, sub_add_cancel] @[to_additive add_zsmul] lemma zpow_add (a : G) (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, zpow_add_one, ihn, mul_assoc] }, { rw [zpow_sub_one, ← mul_assoc, ← ihn, ← zpow_sub_one, add_sub_assoc] } end @[to_additive add_zsmul_self] lemma mul_self_zpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← zpow_one b }, rw [← zpow_add, add_comm] } @[to_additive add_self_zsmul] lemma mul_zpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← zpow_one b }, rw [← zpow_add, add_comm] } @[to_additive sub_zsmul] lemma zpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, zpow_add, zpow_neg] @[to_additive one_add_zsmul] theorem zpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [zpow_add, zpow_one] @[to_additive] theorem zpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← zpow_add, ← zpow_add, add_comm] -- note that `mul_zsmul` and `zpow_mul` have the primes swapped since their argument order -- and therefore the more "natural" choice of lemma is reversed. @[to_additive mul_zsmul'] theorem zpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, zpow_add, ihn]) (λ n ihn, by simp only [mul_sub, zpow_sub, ihn, mul_one, zpow_one]) @[to_additive mul_zsmul] theorem zpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, zpow_mul] @[to_additive bit0_zsmul] theorem zpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := zpow_add _ _ _ @[to_additive bit1_zsmul] theorem zpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, zpow_add, zpow_bit0, zpow_one] end group /-! ### `zpow`/`zsmul` and an order Those lemmas are placed here (rather than in `algebra.group_power.order` with their friends) because they require facts from `data.int.basic`. -/ section ordered_add_comm_group variables [ordered_comm_group α] {m n : ℤ} {a b : α} @[to_additive zsmul_pos] lemma one_lt_zpow' (ha : 1 < a) {k : ℤ} (hk : (0:ℤ) < k) : 1 < a^k := begin lift k to ℕ using int.le_of_lt hk, rw zpow_coe_nat, exact one_lt_pow' ha (coe_nat_pos.mp hk).ne', end @[to_additive zsmul_strict_mono_left] lemma zpow_strict_mono_right (ha : 1 < a) : strict_mono (λ n : ℤ, a ^ n) := λ m n h, calc a ^ m = a ^ m * 1 : (mul_one _).symm ... < a ^ m * a ^ (n - m) : mul_lt_mul_left' (one_lt_zpow' ha $ sub_pos_of_lt h) _ ... = a ^ n : by { rw ←zpow_add, simp } @[to_additive zsmul_mono_left] lemma zpow_mono_right (ha : 1 ≤ a) : monotone (λ n : ℤ, a ^ n) := λ m n h, calc a ^ m = a ^ m * 1 : (mul_one _).symm ... ≤ a ^ m * a ^ (n - m) : mul_le_mul_left' (one_le_zpow ha $ sub_nonneg_of_le h) _ ... = a ^ n : by { rw ←zpow_add, simp } @[to_additive] lemma zpow_le_zpow (ha : 1 ≤ a) (h : m ≤ n) : a ^ m ≤ a ^ n := zpow_mono_right ha h @[to_additive] lemma zpow_lt_zpow (ha : 1 < a) (h : m < n) : a ^ m < a ^ n := zpow_strict_mono_right ha h @[to_additive] lemma zpow_le_zpow_iff (ha : 1 < a) : a ^ m ≤ a ^ n ↔ m ≤ n := (zpow_strict_mono_right ha).le_iff_le @[to_additive] lemma zpow_lt_zpow_iff (ha : 1 < a) : a ^ m < a ^ n ↔ m < n := (zpow_strict_mono_right ha).lt_iff_lt variables (α) @[to_additive zsmul_strict_mono_right] lemma zpow_strict_mono_left (hn : 0 < n) : strict_mono ((^ n) : α → α) := λ a b hab, by { rw [←one_lt_div', ←div_zpow], exact one_lt_zpow' (one_lt_div'.2 hab) hn } @[to_additive zsmul_mono_right] lemma zpow_mono_left (hn : 0 ≤ n) : monotone ((^ n) : α → α) := λ a b hab, by { rw [←one_le_div', ←div_zpow], exact one_le_zpow (one_le_div'.2 hab) hn } variables {α} @[to_additive] lemma zpow_le_zpow' (hn : 0 ≤ n) (h : a ≤ b) : a ^ n ≤ b ^ n := zpow_mono_left α hn h @[to_additive] lemma zpow_lt_zpow' (hn : 0 < n) (h : a < b) : a ^ n < b ^ n := zpow_strict_mono_left α hn h end ordered_add_comm_group section linear_ordered_comm_group variables [linear_ordered_comm_group α] {n : ℤ} {a b : α} @[to_additive] lemma zpow_le_zpow_iff' (hn : 0 < n) {a b : α} : a ^ n ≤ b ^ n ↔ a ≤ b := (zpow_strict_mono_left α hn).le_iff_le @[to_additive] lemma zpow_lt_zpow_iff' (hn : 0 < n) {a b : α} : a ^ n < b ^ n ↔ a < b := (zpow_strict_mono_left α hn).lt_iff_lt @[nolint to_additive_doc, to_additive zsmul_right_injective "See also `smul_right_injective`. TODO: provide a `no_zero_smul_divisors` instance. We can't do that here because importing that definition would create import cycles."] lemma zpow_left_injective (hn : n ≠ 0) : function.injective ((^ n) : α → α) := begin cases hn.symm.lt_or_lt, { exact (zpow_strict_mono_left α h).injective }, { refine λ a b (hab : a ^ n = b ^ n), (zpow_strict_mono_left α (neg_pos.mpr h)).injective _, rw [zpow_neg, zpow_neg, hab] } end @[to_additive zsmul_right_inj] lemma zpow_left_inj (hn : n ≠ 0) : a ^ n = b ^ n ↔ a = b := (zpow_left_injective hn).eq_iff /-- Alias of `zsmul_right_inj`, for ease of discovery alongside `zsmul_le_zsmul_iff'` and `zsmul_lt_zsmul_iff'`. -/ @[to_additive "Alias of `zsmul_right_inj`, for ease of discovery alongside `zsmul_le_zsmul_iff'` and `zsmul_lt_zsmul_iff'`."] lemma zpow_eq_zpow_iff' (hn : n ≠ 0) : a ^ n = b ^ n ↔ a = b := zpow_left_inj hn end linear_ordered_comm_group section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {a b : α} lemma abs_nsmul (n : ℕ) (a : α) : |n • a| = n • |a| := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_zsmul (n : ℤ) (a : α) : |n • a| = |n| • |a| := begin obtain n0 | n0 := le_total 0 n, { lift n to ℕ using n0, simp only [abs_nsmul, coe_nat_abs, coe_nat_zsmul] }, { lift (- n) to ℕ using neg_nonneg.2 n0 with m h, rw [← abs_neg (n • a), ← neg_zsmul, ← abs_neg n, ← h, coe_nat_zsmul, coe_nat_abs, coe_nat_zsmul], exact abs_nsmul m _ }, end lemma abs_add_eq_add_abs_le (hle : a ≤ b) : |a + b| = |a| + |b| ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := begin obtain a0 | a0 := le_or_lt 0 a; obtain b0 | b0 := le_or_lt 0 b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : α) $ a0.trans_lt $ hle.trans_lt b0).elim }, any_goals { simp [a0.le, b0.le, abs_of_nonpos, add_nonpos, add_comm] }, have : (|a + b| = -a + b ↔ b ≤ 0) ↔ (|a + b| = |a| + |b| ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0), { simp [a0, a0.le, a0.not_le, b0, abs_of_neg, abs_of_nonneg] }, refine this.mp ⟨λ h, _, λ h, by simp only [le_antisymm h b0, abs_of_neg a0, add_zero]⟩, obtain ab | ab := le_or_lt (a + b) 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ab, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : α) _).elim, rw [abs_of_pos ab, add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at a0 } end lemma abs_add_eq_add_abs_iff (a b : α) : |a + b| = |a| + |b| ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := begin obtain ab | ab := le_total a b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ab, and.comm, @and.comm (b ≤ 0)] } end end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((n • a : A) : with_bot A) = n • a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [non_assoc_semiring R] (a : R) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [non_assoc_semiring R] (n : ℕ) (a : R) : n • a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] /-- Note that `add_comm_monoid.nat_smul_comm_class` requires stronger assumptions on `R`. -/ instance non_unital_non_assoc_semiring.nat_smul_comm_class [non_unital_non_assoc_semiring R] : smul_comm_class ℕ R R := ⟨λ n x y, match n with | 0 := by simp_rw [zero_nsmul, smul_eq_mul, mul_zero] | (n + 1) := by simp_rw [succ_nsmul, smul_eq_mul, mul_add, ←smul_eq_mul, _match n] end⟩ /-- Note that `add_comm_monoid.nat_is_scalar_tower` requires stronger assumptions on `R`. -/ instance non_unital_non_assoc_semiring.nat_is_scalar_tower [non_unital_non_assoc_semiring R] : is_scalar_tower ℕ R R := ⟨λ n x y, match n with | 0 := by simp_rw [zero_nsmul, smul_eq_mul, zero_mul] | (n + 1) := by simp_rw [succ_nsmul, ←_match n, smul_eq_mul, add_mul] end⟩ @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero], exact nat.cast_one }, { rw [pow_succ', pow_succ', nat.cast_mul, ih] } end @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `zsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [non_unital_non_assoc_ring R] {n r : R} : bit0 n * r = (2 : ℤ) • (n * r) := by { dsimp [bit0], rw [add_mul, add_zsmul, one_zsmul], } lemma mul_bit0 [non_unital_non_assoc_ring R] {n r : R} : r * bit0 n = (2 : ℤ) • (r * n) := by { dsimp [bit0], rw [mul_add, add_zsmul, one_zsmul], } lemma bit1_mul [non_assoc_ring R] {n r : R} : bit1 n * r = (2 : ℤ) • (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [non_assoc_ring R] {n r : R} : r * bit1 n = (2 : ℤ) • (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem zsmul_eq_mul [non_assoc_ring R] (a : R) : ∀ (n : ℤ), n • a = n * a | (n : ℕ) := by { rw [coe_nat_zsmul, nsmul_eq_mul], refl } | -[1+ n] := by simp [nat.cast_succ, neg_add_rev, int.cast_neg_succ_of_nat, add_mul] theorem zsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n • a = a * n := by rw [zsmul_eq_mul, (n.cast_commute a).eq] /-- Note that `add_comm_group.int_smul_comm_class` requires stronger assumptions on `R`. -/ instance non_unital_non_assoc_ring.int_smul_comm_class [non_unital_non_assoc_ring R] : smul_comm_class ℤ R R := ⟨λ n x y, match n with | (n : ℕ) := by simp_rw [coe_nat_zsmul, smul_comm] | -[1+n] := by simp_rw [zsmul_neg_succ_of_nat, smul_eq_mul, mul_neg, mul_smul_comm] end⟩ /-- Note that `add_comm_group.int_is_scalar_tower` requires stronger assumptions on `R`. -/ instance non_unital_non_assoc_ring.int_is_scalar_tower [non_unital_non_assoc_ring R] : is_scalar_tower ℤ R R := ⟨λ n x y, match n with | (n : ℕ) := by simp_rw [coe_nat_zsmul, smul_assoc] | -[1+n] := by simp_rw [zsmul_neg_succ_of_nat, smul_eq_mul, neg_mul, smul_mul_assoc] end⟩ lemma zsmul_int_int (a b : ℤ) : a • b = a * b := by simp lemma zsmul_int_one (n : ℤ) : n • 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero, int.cast_one] }, { rw [pow_succ, pow_succ, int.cast_mul, ih] } end lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [sq] section ordered_semiring variables [ordered_semiring R] {a : R} /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' (Hsq : 0 ≤ a * a) (Hsq' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsq H)) Hsq, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsq' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_le_pow_of_le_one_aux (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by { rw [←add_assoc, ←one_mul (a^i), pow_succ], exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one } lemma pow_le_pow_of_le_one (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_of_le_one (h₀ : 0 ≤ a) (h₁ : a ≤ 1) {n : ℕ} (hn : n ≠ 0) : a ^ n ≤ a := (pow_one a).subst (pow_le_pow_of_le_one h₀ h₁ (nat.pos_of_ne_zero hn)) lemma sq_le (h₀ : 0 ≤ a) (h₁ : a ≤ 1) : a ^ 2 ≤ a := pow_le_of_le_one h₀ h₁ two_ne_zero end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : ℕ} @[simp] lemma abs_pow (a : R) (n : ℕ) : |a ^ n| = |a| ^ n := (pow_abs a n).symm @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ ha, pow_bit1_neg ha n⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int alias int.units_sq ← int.units_pow_two lemma units_pow_eq_pow_mod_two (u : ℤˣ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_sq, one_pow, mul_one] @[simp] lemma nat_abs_sq (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [sq, int.nat_abs_mul_self', sq] alias int.nat_abs_sq ← int.nat_abs_pow_two lemma abs_le_self_sq (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_sq a, sq], norm_cast, apply nat.le_mul_self } alias int.abs_le_self_sq ← int.abs_le_self_pow_two lemma le_self_sq (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_sq _) alias int.le_self_sq ← int.le_self_pow_two lemma pow_right_injective {x : ℤ} (h : 1 < x.nat_abs) : function.injective ((^) x : ℕ → ℤ) := begin suffices : function.injective (nat_abs ∘ ((^) x : ℕ → ℤ)), { exact function.injective.of_comp this }, convert nat.pow_right_injective h, ext n, rw [function.comp_app, nat_abs_pow] end end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, by { convert pow_zero x, exact to_add_one }, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def zpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, zpow_zero x, λ m n, zpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := zpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_zpow, ← of_add_zsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def zmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_zsmul x, λ m n, add_zsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_zsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_zsmul (f 1) } attribute [to_additive multiples_hom] powers_hom attribute [to_additive zmultiples_hom] zpowers_hom variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma zpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : zpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma zpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (zpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n • x := rfl attribute [to_additive multiples_hom_apply] powers_hom_apply @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl attribute [to_additive multiples_hom_symm_apply] powers_hom_symm_apply @[simp] lemma zmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : zmultiples_hom A x n = n • x := rfl attribute [to_additive zmultiples_hom_apply] zpowers_hom_apply @[simp] lemma zmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (zmultiples_hom A).symm f = f 1 := rfl attribute [to_additive zmultiples_hom_symm_apply] zpowers_hom_symm_apply -- TODO use to_additive in the rest of this file lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← zpowers_hom_symm_apply, ← zpowers_hom_apply, equiv.apply_symm_apply] /-! `monoid_hom.ext_mint` is defined in `data.int.cast` -/ lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n • (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n • (f 1) := by rw [← zmultiples_hom_symm_apply, ← zmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `zpowers_hom` is a multiplicative equivalence. -/ def zpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_zpow], ..zpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `zmultiples_hom` is an additive equivalence. -/ def zmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [zsmul_add], ..zmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma zpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : zpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma zpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (zpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n • x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma zmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : zmultiples_add_hom A x n = n • x := rfl @[simp] lemma zmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (zmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `zpow` or `zsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp, to_additive] lemma units_zpow_right {a : M} {x y : Mˣ} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [zpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [zpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute (m * a : R) (n * b : R) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a : R) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute (m * a : R) (n * a : R) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp, to_additive] lemma units_zpow_right {a : M} {u : Mˣ} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_zpow_right m @[simp, to_additive] lemma units_zpow_left {u : Mˣ} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_zpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b : R) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute (m * a : R) (n * b : R) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] lemma cast_int_left : commute (m : R) a := by { rw [← mul_one (m : R)], exact (one_left a).cast_int_mul_left m } @[simp] lemma cast_int_right : commute a m := by { rw [← mul_one (m : R)], exact (one_right a).cast_int_mul_right m } @[simp] theorem self_cast_int_mul : commute a (n * a : R) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute (m * a : R) (n * a : R) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_zpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [zpow_add, mul_add] {contextual := tt}) (by simp [zpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_zpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : Mˣ) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : Mˣ) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n end units namespace mul_opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow [monoid M] (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := rfl @[simp] lemma unop_pow [monoid M] (x : Mᵐᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := rfl /-- Moving to the opposite group or group_with_zero commutes with taking powers. -/ @[simp] lemma op_zpow [div_inv_monoid M] (x : M) (z : ℤ) : op (x ^ z) = (op x) ^ z := rfl @[simp] lemma unop_zpow [div_inv_monoid M] (x : Mᵐᵒᵖ) (z : ℤ) : unop (x ^ z) = (unop x) ^ z := rfl end mul_opposite
1a2ef285349568c89066c4e88e5867d0614a8a0f
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/metric_space/metrizable.lean
7fb64fc6a9b69786b10d7a4d6e65d113b74a45d9
[ "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
11,665
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.specific_limits.basic import topology.urysohns_lemma import topology.continuous_function.bounded import topology.uniform_space.cauchy /-! # Metrizability of a T₃ topological space with second countable topology In this file we define metrizable topological spaces, i.e., topological spaces for which there exists a metric space structure that generates the same topology. We also show that a T₃ topological space with second countable topology `X` is metrizable. First we prove that `X` can be embedded into `l^∞`, then use this embedding to pull back the metric space structure. -/ open set filter metric open_locale bounded_continuous_function filter topology namespace topological_space variables {ι X Y : Type*} {π : ι → Type*} [topological_space X] [topological_space Y] [finite ι] [Π i, topological_space (π i)] /-- A topological space is *pseudo metrizable* if there exists a pseudo metric space structure compatible with the topology. To endow such a space with a compatible distance, use `letI : pseudo_metric_space X := topological_space.pseudo_metrizable_space_pseudo_metric X`. -/ class pseudo_metrizable_space (X : Type*) [t : topological_space X] : Prop := (exists_pseudo_metric : ∃ (m : pseudo_metric_space X), m.to_uniform_space.to_topological_space = t) @[priority 100] instance _root_.pseudo_metric_space.to_pseudo_metrizable_space {X : Type*} [m : pseudo_metric_space X] : pseudo_metrizable_space X := ⟨⟨m, rfl⟩⟩ /-- Construct on a metrizable space a metric compatible with the topology. -/ noncomputable def pseudo_metrizable_space_pseudo_metric (X : Type*) [topological_space X] [h : pseudo_metrizable_space X] : pseudo_metric_space X := h.exists_pseudo_metric.some.replace_topology h.exists_pseudo_metric.some_spec.symm instance pseudo_metrizable_space_prod [pseudo_metrizable_space X] [pseudo_metrizable_space Y] : pseudo_metrizable_space (X × Y) := begin letI : pseudo_metric_space X := pseudo_metrizable_space_pseudo_metric X, letI : pseudo_metric_space Y := pseudo_metrizable_space_pseudo_metric Y, apply_instance end /-- Given an inducing map of a topological space into a pseudo metrizable space, the source space is also pseudo metrizable. -/ lemma _root_.inducing.pseudo_metrizable_space [pseudo_metrizable_space Y] {f : X → Y} (hf : inducing f) : pseudo_metrizable_space X := begin letI : pseudo_metric_space Y := pseudo_metrizable_space_pseudo_metric Y, exact ⟨⟨hf.comap_pseudo_metric_space, rfl⟩⟩ end /-- Every pseudo-metrizable space is first countable. -/ @[priority 100] instance pseudo_metrizable_space.first_countable_topology [h : pseudo_metrizable_space X] : topological_space.first_countable_topology X := begin unfreezingI { rcases h with ⟨_, hm⟩, rw ←hm }, exact @uniform_space.first_countable_topology X pseudo_metric_space.to_uniform_space emetric.uniformity.filter.is_countably_generated, end instance pseudo_metrizable_space.subtype [pseudo_metrizable_space X] (s : set X) : pseudo_metrizable_space s := inducing_coe.pseudo_metrizable_space instance pseudo_metrizable_space_pi [Π i, pseudo_metrizable_space (π i)] : pseudo_metrizable_space (Π i, π i) := by { casesI nonempty_fintype ι, letI := λ i, pseudo_metrizable_space_pseudo_metric (π i), apply_instance } /-- A topological space is metrizable if there exists a metric space structure compatible with the topology. To endow such a space with a compatible distance, use `letI : metric_space X := topological_space.metrizable_space_metric X` -/ class metrizable_space (X : Type*) [t : topological_space X] : Prop := (exists_metric : ∃ (m : metric_space X), m.to_uniform_space.to_topological_space = t) @[priority 100] instance _root_.metric_space.to_metrizable_space {X : Type*} [m : metric_space X] : metrizable_space X := ⟨⟨m, rfl⟩⟩ @[priority 100] instance metrizable_space.to_pseudo_metrizable_space [h : metrizable_space X] : pseudo_metrizable_space X := ⟨let ⟨m, hm⟩ := h.1 in ⟨m.to_pseudo_metric_space, hm⟩⟩ /-- Construct on a metrizable space a metric compatible with the topology. -/ noncomputable def metrizable_space_metric (X : Type*) [topological_space X] [h : metrizable_space X] : metric_space X := h.exists_metric.some.replace_topology h.exists_metric.some_spec.symm @[priority 100] instance t2_space_of_metrizable_space [metrizable_space X] : t2_space X := by { letI : metric_space X := metrizable_space_metric X, apply_instance } instance metrizable_space_prod [metrizable_space X] [metrizable_space Y] : metrizable_space (X × Y) := begin letI : metric_space X := metrizable_space_metric X, letI : metric_space Y := metrizable_space_metric Y, apply_instance end /-- Given an embedding of a topological space into a metrizable space, the source space is also metrizable. -/ lemma _root_.embedding.metrizable_space [metrizable_space Y] {f : X → Y} (hf : embedding f) : metrizable_space X := begin letI : metric_space Y := metrizable_space_metric Y, exact ⟨⟨hf.comap_metric_space f, rfl⟩⟩ end instance metrizable_space.subtype [metrizable_space X] (s : set X) : metrizable_space s := embedding_subtype_coe.metrizable_space instance metrizable_space_pi [Π i, metrizable_space (π i)] : metrizable_space (Π i, π i) := by { casesI nonempty_fintype ι, letI := λ i, metrizable_space_metric (π i), apply_instance } variables (X) [t3_space X] [second_countable_topology X] /-- A T₃ topological space with second countable topology can be embedded into `l^∞ = ℕ →ᵇ ℝ`. -/ lemma exists_embedding_l_infty : ∃ f : X → (ℕ →ᵇ ℝ), embedding f := begin haveI : normal_space X := normal_space_of_t3_second_countable X, -- Choose a countable basis, and consider the set `s` of pairs of set `(U, V)` such that `U ∈ B`, -- `V ∈ B`, and `closure U ⊆ V`. rcases exists_countable_basis X with ⟨B, hBc, -, hB⟩, set s : set (set X × set X) := {UV ∈ B ×ˢ B| closure UV.1 ⊆ UV.2}, -- `s` is a countable set. haveI : encodable s := ((hBc.prod hBc).mono (inter_subset_left _ _)).to_encodable, -- We don't have the space of bounded (possibly discontinuous) functions, so we equip `s` -- with the discrete topology and deal with `s →ᵇ ℝ` instead. letI : topological_space s := ⊥, haveI : discrete_topology s := ⟨rfl⟩, rsuffices ⟨f, hf⟩ : ∃ f : X → (s →ᵇ ℝ), embedding f, { exact ⟨λ x, (f x).extend (encodable.encode' s) 0, (bounded_continuous_function.isometry_extend (encodable.encode' s) (0 : ℕ →ᵇ ℝ)).embedding.comp hf⟩ }, have hd : ∀ UV : s, disjoint (closure UV.1.1) (UV.1.2ᶜ) := λ UV, disjoint_compl_right.mono_right (compl_subset_compl.2 UV.2.2), -- Choose a sequence of `εₙ > 0`, `n : s`, that is bounded above by `1` and tends to zero -- along the `cofinite` filter. obtain ⟨ε, ε01, hε⟩ : ∃ ε : s → ℝ, (∀ UV, ε UV ∈ Ioc (0 : ℝ) 1) ∧ tendsto ε cofinite (𝓝 0), { rcases pos_sum_of_encodable zero_lt_one s with ⟨ε, ε0, c, hεc, hc1⟩, refine ⟨ε, λ UV, ⟨ε0 UV, _⟩, hεc.summable.tendsto_cofinite_zero⟩, exact (le_has_sum hεc UV $ λ _ _, (ε0 _).le).trans hc1 }, /- For each `UV = (U, V) ∈ s` we use Urysohn's lemma to choose a function `f UV` that is equal to zero on `U` and is equal to `ε UV` on the complement to `V`. -/ have : ∀ UV : s, ∃ f : C(X, ℝ), eq_on f 0 UV.1.1 ∧ eq_on f (λ _, ε UV) UV.1.2ᶜ ∧ ∀ x, f x ∈ Icc 0 (ε UV), { intro UV, rcases exists_continuous_zero_one_of_closed is_closed_closure (hB.is_open UV.2.1.2).is_closed_compl (hd UV) with ⟨f, hf₀, hf₁, hf01⟩, exact ⟨ε UV • f, λ x hx, by simp [hf₀ (subset_closure hx)], λ x hx, by simp [hf₁ hx], λ x, ⟨mul_nonneg (ε01 _).1.le (hf01 _).1, mul_le_of_le_one_right (ε01 _).1.le (hf01 _).2⟩⟩ }, choose f hf0 hfε hf0ε, have hf01 : ∀ UV x, f UV x ∈ Icc (0 : ℝ) 1, from λ UV x, Icc_subset_Icc_right (ε01 _).2 (hf0ε _ _), /- The embedding is given by `F x UV = f UV x`. -/ set F : X → s →ᵇ ℝ := λ x, ⟨⟨λ UV, f UV x, continuous_of_discrete_topology⟩, 1, λ UV₁ UV₂, real.dist_le_of_mem_Icc_01 (hf01 _ _) (hf01 _ _)⟩, have hF : ∀ x UV, F x UV = f UV x := λ _ _, rfl, refine ⟨F, embedding.mk' _ (λ x y hxy, _) (λ x, le_antisymm _ _)⟩, { /- First we prove that `F` is injective. Indeed, if `F x = F y` and `x ≠ y`, then we can find `(U, V) ∈ s` such that `x ∈ U` and `y ∉ V`, hence `F x UV = 0 ≠ ε UV = F y UV`. -/ refine not_not.1 (λ Hne, _), -- `by_contra Hne` timeouts rcases hB.mem_nhds_iff.1 (is_open_ne.mem_nhds Hne) with ⟨V, hVB, hxV, hVy⟩, rcases hB.exists_closure_subset (hB.mem_nhds hVB hxV) with ⟨U, hUB, hxU, hUV⟩, set UV : ↥s := ⟨(U, V), ⟨hUB, hVB⟩, hUV⟩, apply (ε01 UV).1.ne, calc (0 : ℝ) = F x UV : (hf0 UV hxU).symm ... = F y UV : by rw hxy ... = ε UV : hfε UV (λ h : y ∈ V, hVy h rfl) }, { /- Now we prove that each neighborhood `V` of `x : X` include a preimage of a neighborhood of `F x` under `F`. Without loss of generality, `V` belongs to `B`. Choose `U ∈ B` such that `x ∈ V` and `closure V ⊆ U`. Then the preimage of the `(ε (U, V))`-neighborhood of `F x` is included by `V`. -/ refine ((nhds_basis_ball.comap _).le_basis_iff hB.nhds_has_basis).2 _, rintro V ⟨hVB, hxV⟩, rcases hB.exists_closure_subset (hB.mem_nhds hVB hxV) with ⟨U, hUB, hxU, hUV⟩, set UV : ↥s := ⟨(U, V), ⟨hUB, hVB⟩, hUV⟩, refine ⟨ε UV, (ε01 UV).1, λ y (hy : dist (F y) (F x) < ε UV), _⟩, replace hy : dist (F y UV) (F x UV) < ε UV, from (bounded_continuous_function.dist_coe_le_dist _).trans_lt hy, contrapose! hy, rw [hF, hF, hfε UV hy, hf0 UV hxU, pi.zero_apply, dist_zero_right], exact le_abs_self _ }, { /- Finally, we prove that `F` is continuous. Given `δ > 0`, consider the set `T` of `(U, V) ∈ s` such that `ε (U, V) ≥ δ`. Since `ε` tends to zero, `T` is finite. Since each `f` is continuous, we can choose a neighborhood such that `dist (F y (U, V)) (F x (U, V)) ≤ δ` for any `(U, V) ∈ T`. For `(U, V) ∉ T`, the same inequality is true because both `F y (U, V)` and `F x (U, V)` belong to the interval `[0, ε (U, V)]`. -/ refine (nhds_basis_closed_ball.comap _).ge_iff.2 (λ δ δ0, _), have h_fin : {UV : s | δ ≤ ε UV}.finite, by simpa only [← not_lt] using hε (gt_mem_nhds δ0), have : ∀ᶠ y in 𝓝 x, ∀ UV, δ ≤ ε UV → dist (F y UV) (F x UV) ≤ δ, { refine (eventually_all_finite h_fin).2 (λ UV hUV, _), exact (f UV).continuous.tendsto x (closed_ball_mem_nhds _ δ0) }, refine this.mono (λ y hy, (bounded_continuous_function.dist_le δ0.le).2 $ λ UV, _), cases le_total δ (ε UV) with hle hle, exacts [hy _ hle, (real.dist_le_of_mem_Icc (hf0ε _ _) (hf0ε _ _)).trans (by rwa sub_zero)] } end /-- *Urysohn's metrization theorem* (Tychonoff's version): a T₃ topological space with second countable topology `X` is metrizable, i.e., there exists a metric space structure that generates the same topology. -/ lemma metrizable_space_of_t3_second_countable : metrizable_space X := let ⟨f, hf⟩ := exists_embedding_l_infty X in hf.metrizable_space instance : metrizable_space ennreal := metrizable_space_of_t3_second_countable ennreal end topological_space
40b359a5c2c264249a63e207ab000baa75accfed
26ac254ecb57ffcb886ff709cf018390161a9225
/src/ring_theory/polynomial_algebra.lean
af77fe6384e7f3fd9e1e389cf9c9760ece42fe71
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
11,939
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 ring_theory.tensor_product import ring_theory.matrix_algebra import data.polynomial /-! # Algebra isomorphism between matrices of polynomials and polynomials of matrices Given `[comm_ring R] [ring A] [algebra R A]` we show `polynomial A ≃ₐ[R] (A ⊗[R] polynomial R)`. Combining this with the isomorphism `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)` proved earlier in `ring_theory.matrix_algebra`, we obtain the algebra isomorphism ``` def mat_poly_equiv : matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R) ``` which is characterized by ``` coeff (mat_poly_equiv m) k i j = coeff (m i j) k ``` We will use this algebra isomorphism to prove the Cayley-Hamilton theorem. -/ universes u v w open_locale tensor_product open polynomial open tensor_product open algebra.tensor_product (alg_hom_of_linear_map_tensor_product include_left) noncomputable theory variables (R A : Type*) variables [comm_semiring R] variables [semiring A] [algebra R A] namespace poly_equiv_tensor /-- (Implementation detail). The bare function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, on pure tensors. -/ def to_fun (a : A) (p : polynomial R) : polynomial A := p.sum (λ n r, monomial n (a * algebra_map R A r)) /-- (Implementation detail). The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, as a linear map in the second factor. -/ def to_fun_linear_right (a : A) : polynomial R →ₗ[R] polynomial A := { to_fun := to_fun R A a, map_smul' := λ r p, begin dsimp [to_fun], rw finsupp.sum_smul_index, { dsimp [finsupp.sum], rw finset.smul_sum, apply finset.sum_congr rfl, intros k hk, rw [monomial_eq_smul_X, monomial_eq_smul_X, algebra.smul_def, ← C_mul', ← C_mul', ← mul_assoc], congr' 1, rw [← algebra.commutes, ← algebra.commutes], simp only [ring_hom.map_mul, polynomial.algebra_map_apply, mul_assoc], }, { intro i, simp only [ring_hom.map_zero, mul_zero, monomial_zero_right] }, end, map_add' := λ p q, begin simp only [to_fun], rw finsupp.sum_add_index, { simp only [monomial_zero_right, forall_const, ring_hom.map_zero, mul_zero], }, { intros i r s, simp only [ring_hom.map_add, mul_add, monomial_add], }, end, } /-- (Implementation detail). The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, as a bilinear function of two arguments. -/ def to_fun_bilinear : A →ₗ[R] polynomial R →ₗ[R] polynomial A := { to_fun := to_fun_linear_right R A, map_smul' := by { intros, unfold to_fun_linear_right, congr, simp only [linear_map.coe_mk], unfold to_fun finsupp.sum monomial, simp_rw [finset.smul_sum, finsupp.smul_single, ← algebra.smul_mul_assoc], refl }, map_add' := by { intros, unfold to_fun_linear_right, congr, simp only [linear_map.coe_mk], unfold to_fun finsupp.sum monomial, simp_rw [← finset.sum_add_distrib, ← finsupp.single_add, ← add_mul], refl } } /-- (Implementation detail). The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, as a linear map. -/ def to_fun_linear : A ⊗[R] polynomial R →ₗ[R] polynomial A := tensor_product.lift (to_fun_bilinear R A) -- We apparently need to provide the decidable instance here -- in order to successfully rewrite by this lemma. lemma to_fun_linear_mul_tmul_mul_aux_1 (p : polynomial R) (k : ℕ) (h : decidable (¬p.coeff k = 0)) (a : A) : ite (¬coeff p k = 0) (a * (algebra_map R A) (coeff p k)) 0 = a * (algebra_map R A) (coeff p k) := by { classical, split_ifs; simp *, } lemma to_fun_linear_mul_tmul_mul_aux_2 (k : ℕ) (a₁ a₂ : A) (p₁ p₂ : polynomial R) : a₁ * a₂ * (algebra_map R A) ((p₁ * p₂).coeff k) = (finset.nat.antidiagonal k).sum (λ x, a₁ * (algebra_map R A) (coeff p₁ x.1) * (a₂ * (algebra_map R A) (coeff p₂ x.2))) := begin simp_rw [mul_assoc, algebra.commutes, ←finset.mul_sum, mul_assoc, ←finset.mul_sum], congr, simp_rw [algebra.commutes (coeff p₂ _), coeff_mul, ring_hom.map_sum, ring_hom.map_mul], end lemma to_fun_linear_mul_tmul_mul (a₁ a₂ : A) (p₁ p₂ : polynomial R) : (to_fun_linear R A) ((a₁ * a₂) ⊗ₜ[R] p₁ * p₂) = (to_fun_linear R A) (a₁ ⊗ₜ[R] p₁) * (to_fun_linear R A) (a₂ ⊗ₜ[R] p₂) := begin dsimp [to_fun_linear], simp only [lift.tmul], dsimp [to_fun_bilinear, to_fun_linear_right, to_fun], ext k, -- TODO This is a bit annoying: the polynomial API is breaking down. have apply_eq_coeff : ∀ {p : ℕ →₀ R} {n : ℕ}, p n = coeff p n := by { intros, refl }, simp_rw [coeff_sum, coeff_monomial, finsupp.sum, finset.sum_ite_eq', finsupp.mem_support_iff, ne.def, coeff_mul, finset_sum_coeff, coeff_monomial, finset.sum_ite_eq', finsupp.mem_support_iff, ne.def, mul_ite, mul_zero, ite_mul, zero_mul, apply_eq_coeff], simp_rw [ite_mul_zero_left (¬coeff p₁ _ = 0) (a₁ * (algebra_map R A) (coeff p₁ _))], simp_rw [ite_mul_zero_right (¬coeff p₂ _ = 0) _ (_ * _)], simp_rw [to_fun_linear_mul_tmul_mul_aux_1, to_fun_linear_mul_tmul_mul_aux_2], end lemma to_fun_linear_algebra_map_tmul_one (r : R) : (to_fun_linear R A) ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R (polynomial A)) r := begin dsimp [to_fun_linear], simp only [lift.tmul], dsimp [to_fun_bilinear, to_fun_linear_right, to_fun], rw [← C_1, ←monomial_zero_left, monomial, finsupp.sum_single_index], { simp, refl, }, { simp, }, end /-- (Implementation detail). The algebra homomorphism `A ⊗[R] polynomial R →ₐ[R] polynomial A`. -/ def to_fun_alg_hom : A ⊗[R] polynomial R →ₐ[R] polynomial A := alg_hom_of_linear_map_tensor_product (to_fun_linear R A) (to_fun_linear_mul_tmul_mul R A) (to_fun_linear_algebra_map_tmul_one R A) @[simp] lemma to_fun_alg_hom_apply_tmul (a : A) (p : polynomial R) : to_fun_alg_hom R A (a ⊗ₜ[R] p) = p.sum (λ n r, monomial n (a * (algebra_map R A) r)) := by simp [to_fun_alg_hom, to_fun_linear, to_fun_bilinear, to_fun_linear_right, to_fun] /-- (Implementation detail.) The bare function `polynomial A → A ⊗[R] polynomial R`. (We don't need to show that it's an algebra map, thankfully --- just that it's an inverse.) -/ def inv_fun (p : polynomial A) : A ⊗[R] polynomial R := p.eval₂ (include_left : A →ₐ[R] A ⊗[R] polynomial R) ((1 : A) ⊗ₜ[R] (X : polynomial R)) @[simp] lemma inv_fun_add {p q} : inv_fun R A (p + q) = inv_fun R A p + inv_fun R A q := by simp only [inv_fun, eval₂_add] lemma left_inv (x : A ⊗ polynomial R) : inv_fun R A ((to_fun_alg_hom R A) x) = x := begin apply tensor_product.induction_on x, { simp [inv_fun], }, { intros a p, dsimp only [inv_fun], rw [to_fun_alg_hom_apply_tmul, eval₂_sum], simp_rw [eval₂_monomial, alg_hom.coe_to_ring_hom, algebra.tensor_product.tmul_pow, one_pow, algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_mul_tmul, mul_one, one_mul, ←algebra.commutes, ←algebra.smul_def'', smul_tmul], rw [finsupp.sum, ←tmul_sum], conv_rhs { rw [←sum_C_mul_X_eq p], }, simp only [algebra.smul_def''], refl, }, { intros p q hp hq, simp only [alg_hom.map_add, inv_fun_add, hp, hq], }, end lemma right_inv (x : polynomial A) : (to_fun_alg_hom R A) (inv_fun R A x) = x := begin apply polynomial.induction_on' x, { intros p q hp hq, simp only [inv_fun_add, alg_hom.map_add, hp, hq], }, { intros n a, rw [inv_fun, eval₂_monomial, alg_hom.coe_to_ring_hom, algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_pow, one_pow, algebra.tensor_product.tmul_mul_tmul, mul_one, one_mul, to_fun_alg_hom_apply_tmul, ←monomial_one_eq_X_pow], dsimp [monomial], rw [finsupp.sum_single_index]; simp, } end /-- (Implementation detail) The equivalence, ignoring the algebra structure, `(A ⊗[R] polynomial R) ≃ polynomial A`. -/ def equiv : (A ⊗[R] polynomial R) ≃ polynomial A := { to_fun := to_fun_alg_hom R A, inv_fun := inv_fun R A, left_inv := left_inv R A, right_inv := right_inv R A, } end poly_equiv_tensor open poly_equiv_tensor /-- The `R`-algebra isomorphism `polynomial A ≃ₐ[R] (A ⊗[R] polynomial R)`. -/ def poly_equiv_tensor : polynomial A ≃ₐ[R] (A ⊗[R] polynomial R) := alg_equiv.symm { ..(poly_equiv_tensor.to_fun_alg_hom R A), ..(poly_equiv_tensor.equiv R A) } @[simp] lemma poly_equiv_tensor_apply (p : polynomial A) : poly_equiv_tensor R A p = p.eval₂ (include_left : A →ₐ[R] A ⊗[R] polynomial R) ((1 : A) ⊗ₜ[R] (X : polynomial R)) := rfl @[simp] lemma poly_equiv_tensor_symm_apply_tmul (a : A) (p : polynomial R) : (poly_equiv_tensor R A).symm (a ⊗ₜ p) = p.sum (λ n r, monomial n (a * algebra_map R A r)) := begin simp [poly_equiv_tensor, to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear], refl, end open matrix open_locale big_operators variables {R} variables {n : Type w} [fintype n] [decidable_eq n] /-- The algebra isomorphism stating "matrices of polynomials are the same as polynomials of matrices". (You probably shouldn't attempt to use this underlying definition --- it's an algebra equivalence, and characterised extensionally by the lemma `mat_poly_equiv_coeff_apply` below.) -/ noncomputable def mat_poly_equiv : matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R) := (((matrix_equiv_tensor R (polynomial R) n)).trans (algebra.tensor_product.comm R _ _)).trans (poly_equiv_tensor R (matrix n n R)).symm open finset lemma mat_poly_equiv_coeff_apply_aux_1 (i j : n) (k : ℕ) (x : R) : mat_poly_equiv (std_basis_matrix i j $ monomial k x) = monomial k (std_basis_matrix i j x) := begin simp only [mat_poly_equiv, alg_equiv.trans_apply, matrix_equiv_tensor_apply_std_basis], apply (poly_equiv_tensor R (matrix n n R)).injective, simp only [alg_equiv.apply_symm_apply], convert algebra.tensor_product.comm_tmul _ _ _ _ _, simp only [poly_equiv_tensor_apply], convert eval₂_monomial _ _, simp only [algebra.tensor_product.tmul_mul_tmul, one_pow, one_mul, matrix.mul_one, algebra.tensor_product.tmul_pow, algebra.tensor_product.include_left_apply, mul_eq_mul], rw [monomial_eq_smul_X, ← tensor_product.smul_tmul], congr, ext, simp, dsimp, simp, end lemma mat_poly_equiv_coeff_apply_aux_2 (i j : n) (p : polynomial R) (k : ℕ) : coeff (mat_poly_equiv (std_basis_matrix i j p)) k = std_basis_matrix i j (coeff p k) := begin apply polynomial.induction_on' p, { intros p q hp hq, ext, simp [hp, hq, coeff_add, add_val, std_basis_matrix_add], }, { intros k x, simp only [mat_poly_equiv_coeff_apply_aux_1, coeff_monomial], split_ifs; { funext, simp, }, } end @[simp] lemma mat_poly_equiv_coeff_apply (m : matrix n n (polynomial R)) (k : ℕ) (i j : n) : coeff (mat_poly_equiv m) k i j = coeff (m i j) k := begin apply matrix.induction_on' m, { simp, }, { intros p q hp hq, simp [hp, hq], }, { intros i' j' x, erw mat_poly_equiv_coeff_apply_aux_2, dsimp [std_basis_matrix], split_ifs, { rcases h with ⟨rfl, rfl⟩, simp [std_basis_matrix], }, { simp [std_basis_matrix, h], }, }, end @[simp] lemma mat_poly_equiv_symm_apply_coeff (p : polynomial (matrix n n R)) (i j : n) (k : ℕ) : coeff (mat_poly_equiv.symm p i j) k = coeff p k i j := begin have t : p = mat_poly_equiv (mat_poly_equiv.symm p) := by simp, conv_rhs { rw t, }, simp only [mat_poly_equiv_coeff_apply], end lemma mat_poly_equiv_smul_one (p : polynomial R) : mat_poly_equiv (p • 1) = p.map (algebra_map R (matrix n n R)) := begin ext m i j, simp only [coeff_map, one_val, algebra_map_matrix_val, mul_boole, smul_val, mat_poly_equiv_coeff_apply], split_ifs; simp, end
f9b2aa5dd43af405eaed8db13256d06bda1d5421
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/struct_infer.lean
1114180967832533a27b52783dd51b043770fd6d
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
644
lean
import data.nat.basic open nat definition associative {A : Type} (op : A → A → A) := ∀a b c, op (op a b) c = op a (op b c) structure semigroup [class] (A : Type) := mk {} :: (mul: A → A → A) (mul_assoc : associative mul) definition nat_semigroup [instance] : semigroup nat := semigroup.mk nat.mul nat.mul.assoc example (a b c : nat) : (a * b) * c = a * (b * c) := semigroup.mul_assoc a b c structure semigroup2 (A : Type) := mk () :: (mul: A → A → A) (mul_assoc : associative mul) definition s := semigroup2.mk nat nat.mul nat.mul.assoc example (a b c : nat) : (a * b) * c = a * (b * c) := semigroup2.mul_assoc nat s a b c
ed4cf8e27befed997988b633717577a5f5a4f895
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/set/finite_auto.lean
fe08139351ee9bdd4c85d4aa97e85e7b843421e8
[]
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
25,389
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.PostPort universes u u_1 v u_2 x u_3 namespace Mathlib /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite {α : Type u} (s : set α) := Nonempty (fintype ↥s) /-- A set is infinite if it is not finite. -/ def infinite {α : Type u} (s : set α) := ¬finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ def finite.fintype {α : Type u} {s : set α} (h : finite s) : fintype ↥s := Classical.choice h /-- Get a finset from a finite set -/ def finite.to_finset {α : Type u} {s : set α} (h : finite s) : finset α := to_finset s @[simp] theorem finite.mem_to_finset {α : Type u} {s : set α} {h : finite s} {a : α} : a ∈ finite.to_finset h ↔ a ∈ s := mem_to_finset @[simp] theorem finite.to_finset.nonempty {α : Type u} {s : set α} (h : finite s) : finset.nonempty (finite.to_finset h) ↔ set.nonempty s := (fun (this : (∃ (x : α), x ∈ finite.to_finset h) ↔ ∃ (x : α), x ∈ s) => this) (exists_congr fun (_x : α) => finite.mem_to_finset) @[simp] theorem finite.coe_to_finset {α : Type u_1} {s : set α} (h : finite s) : ↑(finite.to_finset h) = s := coe_to_finset s theorem finite.exists_finset {α : Type u} {s : set α} : finite s → ∃ (s' : finset α), ∀ (a : α), a ∈ s' ↔ a ∈ s := sorry theorem finite.exists_finset_coe {α : Type u} {s : set α} (hs : finite s) : ∃ (s' : finset α), ↑s' = s := Exists.intro (finite.to_finset hs) (finite.coe_to_finset hs) /-- Finite sets can be lifted to finsets. -/ protected instance finset.can_lift {α : Type u} : can_lift (set α) (finset α) := can_lift.mk coe finite sorry theorem finite_mem_finset {α : Type u} (s : finset α) : finite (set_of fun (a : α) => a ∈ s) := Nonempty.intro (fintype.of_finset s fun (_x : α) => iff.rfl) theorem finite.of_fintype {α : Type u} [fintype α] (s : set α) : finite s := Nonempty.intro (set_fintype s) theorem exists_finite_iff_finset {α : Type u} {p : set α → Prop} : (∃ (s : set α), finite s ∧ p s) ↔ ∃ (s : finset α), p ↑s := sorry /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype {α : Type u} [DecidableEq α] (s : set α) [fintype ↥s] (a : α) : Decidable (a ∈ s) := decidable_of_iff (a ∈ to_finset s) mem_to_finset protected instance fintype_empty {α : Type u} : fintype ↥∅ := fintype.of_finset ∅ sorry theorem empty_card {α : Type u} : fintype.card ↥∅ = 0 := rfl @[simp] theorem empty_card' {α : Type u} {h : fintype ↥∅} : fintype.card ↥∅ = 0 := sorry @[simp] theorem finite_empty {α : Type u} : finite ∅ := Nonempty.intro set.fintype_empty protected instance finite.inhabited {α : Type u} : Inhabited (Subtype fun (s : set α) => finite s) := { default := { val := ∅, property := finite_empty } } /-- A `fintype` structure on `insert a s`. -/ def fintype_insert' {α : Type u} {a : α} (s : set α) [fintype ↥s] (h : ¬a ∈ s) : fintype ↥(insert a s) := fintype.of_finset (finset.mk (a ::ₘ finset.val (to_finset s)) sorry) sorry theorem card_fintype_insert' {α : Type u} {a : α} (s : set α) [fintype ↥s] (h : ¬a ∈ s) : fintype.card ↥(insert a s) = fintype.card ↥s + 1 := sorry @[simp] theorem card_insert {α : Type u} {a : α} (s : set α) [fintype ↥s] (h : ¬a ∈ s) {d : fintype ↥(insert a s)} : fintype.card ↥(insert a s) = fintype.card ↥s + 1 := sorry theorem card_image_of_inj_on {α : Type u} {β : Type v} {s : set α} [fintype ↥s] {f : α → β} [fintype ↥(f '' s)] (H : ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) : fintype.card ↥(f '' s) = fintype.card ↥s := sorry theorem card_image_of_injective {α : Type u} {β : Type v} (s : set α) [fintype ↥s] {f : α → β} [fintype ↥(f '' s)] (H : function.injective f) : fintype.card ↥(f '' s) = fintype.card ↥s := card_image_of_inj_on fun (_x : α) (_x_1 : _x ∈ s) (_x_2 : α) (_x_3 : _x_2 ∈ s) (h : f _x = f _x_2) => H h protected instance fintype_insert {α : Type u} [DecidableEq α] (a : α) (s : set α) [fintype ↥s] : fintype ↥(insert a s) := dite (a ∈ s) (fun (h : a ∈ s) => eq.mpr sorry (eq.mpr sorry _inst_2)) fun (h : ¬a ∈ s) => fintype_insert' s h @[simp] theorem finite.insert {α : Type u} (a : α) {s : set α} : finite s → finite (insert a s) := fun (ᾰ : finite s) => nonempty.dcases_on ᾰ fun (ᾰ : fintype ↥s) => idRhs (Nonempty (fintype ↥(insert a s))) (Nonempty.intro (set.fintype_insert a s)) theorem to_finset_insert {α : Type u} [DecidableEq α] {a : α} {s : set α} (hs : finite s) : finite.to_finset (finite.insert a hs) = insert a (finite.to_finset hs) := sorry theorem finite.induction_on {α : Type u} {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a : α} {s : set α}, ¬a ∈ s → finite s → C s → C (insert a s)) : C s := sorry theorem finite.dinduction_on {α : Type u} {C : (s : set α) → finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a : α} {s : set α}, ¬a ∈ s → ∀ (h : finite s), C s h → C (insert a s) (finite.insert a h)) : C s h := sorry protected instance fintype_singleton {α : Type u} (a : α) : fintype ↥(singleton a) := unique.fintype @[simp] theorem card_singleton {α : Type u} (a : α) : fintype.card ↥(singleton a) = 1 := fintype.card_of_subsingleton Inhabited.default @[simp] theorem finite_singleton {α : Type u} (a : α) : finite (singleton a) := Nonempty.intro (set.fintype_singleton a) protected instance fintype_pure {α : Type u} (a : α) : fintype ↥(pure a) := set.fintype_singleton theorem finite_pure {α : Type u} (a : α) : finite (pure a) := Nonempty.intro (set.fintype_pure a) protected instance fintype_univ {α : Type u} [fintype α] : fintype ↥univ := fintype.of_equiv α (equiv.symm (equiv.set.univ α)) theorem finite_univ {α : Type u} [fintype α] : finite univ := Nonempty.intro set.fintype_univ theorem infinite_univ_iff {α : Type u} : infinite univ ↔ infinite α := sorry theorem infinite_univ {α : Type u} [h : infinite α] : infinite univ := iff.mpr infinite_univ_iff h theorem infinite_coe_iff {α : Type u} {s : set α} : infinite ↥s ↔ infinite s := sorry theorem infinite.to_subtype {α : Type u} {s : set α} (h : infinite s) : infinite ↥s := iff.mpr infinite_coe_iff h /-- Embedding of `ℕ` into an infinite set. -/ def infinite.nat_embedding {α : Type u} (s : set α) (h : infinite s) : ℕ ↪ ↥s := infinite.nat_embedding ↥s theorem infinite.exists_subset_card_eq {α : Type u} {s : set α} (hs : infinite s) (n : ℕ) : ∃ (t : finset α), ↑t ⊆ s ∧ finset.card t = n := sorry protected instance fintype_union {α : Type u} [DecidableEq α] (s : set α) (t : set α) [fintype ↥s] [fintype ↥t] : fintype ↥(s ∪ t) := fintype.of_finset (to_finset s ∪ to_finset t) sorry theorem finite.union {α : Type u} {s : set α} {t : set α} : finite s → finite t → finite (s ∪ t) := sorry protected instance fintype_sep {α : Type u} (s : set α) (p : α → Prop) [fintype ↥s] [decidable_pred p] : fintype ↥(has_sep.sep (fun (a : α) => p a) s) := fintype.of_finset (finset.filter p (to_finset s)) sorry protected instance fintype_inter {α : Type u} (s : set α) (t : set α) [fintype ↥s] [decidable_pred t] : fintype ↥(s ∩ t) := set.fintype_sep s t /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset {α : Type u} (s : set α) {t : set α} [fintype ↥s] [decidable_pred t] (h : t ⊆ s) : fintype ↥t := eq.mpr sorry (set.fintype_inter s t) theorem finite.subset {α : Type u} {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t := fun (ᾰ : finite s) {t : set α} (ᾰ_1 : t ⊆ s) => nonempty.dcases_on ᾰ fun (ᾰ_1_1 : fintype ↥s) => idRhs (Nonempty (fintype ↥t)) (Nonempty.intro (fintype_subset s ᾰ_1)) theorem infinite_mono {α : Type u} {s : set α} {t : set α} (h : s ⊆ t) : infinite s → infinite t := mt fun (ht : finite t) => finite.subset ht h protected instance fintype_image {α : Type u} {β : Type v} [DecidableEq β] (s : set α) (f : α → β) [fintype ↥s] : fintype ↥(f '' s) := fintype.of_finset (finset.image f (to_finset s)) sorry protected instance fintype_range {α : Type u} {β : Type v} [DecidableEq β] (f : α → β) [fintype α] : fintype ↥(range f) := fintype.of_finset (finset.image f finset.univ) sorry theorem finite_range {α : Type u} {β : Type v} (f : α → β) [fintype α] : finite (range f) := Nonempty.intro (set.fintype_range f) theorem finite.image {α : Type u} {β : Type v} {s : set α} (f : α → β) : finite s → finite (f '' s) := fun (ᾰ : finite s) => nonempty.dcases_on ᾰ fun (ᾰ : fintype ↥s) => idRhs (Nonempty (fintype ↥(f '' s))) (Nonempty.intro (set.fintype_image s f)) theorem infinite_of_infinite_image {α : Type u} {β : Type v} (f : α → β) {s : set α} (hs : infinite (f '' s)) : infinite s := mt (finite.image f) hs theorem finite.dependent_image {α : Type u} {β : Type v} {s : set α} (hs : finite s) {F : (i : α) → i ∈ s → β} {t : set β} (H : ∀ (y : β), y ∈ t → ∃ (x : α), ∃ (hx : x ∈ s), y = F x hx) : finite t := sorry protected instance fintype_map {α : Type u_1} {β : Type u_1} [DecidableEq β] (s : set α) (f : α → β) [fintype ↥s] : fintype ↥(f <$> s) := set.fintype_image theorem finite.map {α : Type u_1} {β : Type u_1} {s : set α} (f : α → β) : finite s → finite (f <$> s) := finite.image /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image {α : Type u} {β : Type v} (s : set α) {f : α → β} {g : β → Option α} (I : function.is_partial_inv f g) [fintype ↥(f '' s)] : fintype ↥s := fintype.of_finset (finset.mk (multiset.filter_map g (finset.val (to_finset (f '' s)))) sorry) sorry theorem finite_of_finite_image {α : Type u} {β : Type v} {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) → finite s := sorry theorem finite_image_iff {α : Type u} {β : Type v} {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := { mp := finite_of_finite_image hi, mpr := finite.image f } theorem infinite_image_iff {α : Type u} {β : Type v} {s : set α} {f : α → β} (hi : inj_on f s) : infinite (f '' s) ↔ infinite s := not_congr (finite_image_iff hi) theorem infinite_of_inj_on_maps_to {α : Type u} {β : Type v} {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t := infinite_mono (iff.mp maps_to' hm) (iff.mpr (infinite_image_iff hi) hs) theorem infinite_range_of_injective {α : Type u} {β : Type v} [infinite α] {f : α → β} (hi : function.injective f) : infinite (range f) := sorry theorem infinite_of_injective_forall_mem {α : Type u} {β : Type v} [infinite α] {s : set β} {f : α → β} (hi : function.injective f) (hf : ∀ (x : α), f x ∈ s) : infinite s := infinite_mono (eq.mp (Eq._oldrec (Eq.refl (∀ (x : α), f x ∈ s)) (Eq.symm (propext range_subset_iff))) hf) (infinite_range_of_injective hi) theorem finite.preimage {α : Type u} {β : Type v} {s : set β} {f : α → β} (I : inj_on f (f ⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (finite.subset h (image_preimage_subset f s)) theorem finite.preimage_embedding {α : Type u} {β : Type v} {s : set β} (f : α ↪ β) (h : finite s) : finite (⇑f ⁻¹' s) := sorry protected instance fintype_Union {α : Type u} [DecidableEq α] {ι : Type u_1} [fintype ι] (f : ι → set α) [(i : ι) → fintype ↥(f i)] : fintype ↥(Union fun (i : ι) => f i) := fintype.of_finset (finset.bUnion finset.univ fun (i : ι) => to_finset (f i)) sorry theorem finite_Union {α : Type u} {ι : Type u_1} [fintype ι] {f : ι → set α} (H : ∀ (i : ι), finite (f i)) : finite (Union fun (i : ι) => f i) := Nonempty.intro (set.fintype_Union fun (i : ι) => f i) /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_set_bUnion {α : Type u} [DecidableEq α] {ι : Type u_1} {s : set ι} [fintype ↥s] (f : ι → set α) (H : (i : ι) → i ∈ s → fintype ↥(f i)) : fintype ↥(Union fun (i : ι) => Union fun (H : i ∈ s) => f i) := eq.mpr sorry (set.fintype_Union fun (x : ↥s) => f ↑x) protected instance fintype_set_bUnion' {α : Type u} [DecidableEq α] {ι : Type u_1} {s : set ι} [fintype ↥s] (f : ι → set α) [H : (i : ι) → fintype ↥(f i)] : fintype ↥(Union fun (i : ι) => Union fun (H : i ∈ s) => f i) := fintype_set_bUnion (fun (i : ι) => f i) fun (i : ι) (_x : i ∈ s) => H i theorem finite.sUnion {α : Type u} {s : set (set α)} (h : finite s) (H : ∀ (t : set α), t ∈ s → finite t) : finite (⋃₀s) := eq.mpr (id (Eq._oldrec (Eq.refl (finite (⋃₀s))) sUnion_eq_Union)) (finite_Union (eq.mpr (id (propext set_coe.forall)) (eq.mp (Eq.refl (∀ (t : set α), t ∈ s → finite t)) H))) theorem finite.bUnion {α : Type u_1} {ι : Type u_2} {s : set ι} {f : (i : ι) → i ∈ s → set α} : finite s → (∀ (i : ι) (H : i ∈ s), finite (f i H)) → finite (Union fun (i : ι) => Union fun (H : i ∈ s) => f i H) := sorry protected instance fintype_lt_nat (n : ℕ) : fintype ↥(set_of fun (i : ℕ) => i < n) := fintype.of_finset (finset.range n) sorry protected instance fintype_le_nat (n : ℕ) : fintype ↥(set_of fun (i : ℕ) => i ≤ n) := eq.mpr sorry (eq.mp sorry (set.fintype_lt_nat (n + 1))) theorem finite_le_nat (n : ℕ) : finite (set_of fun (i : ℕ) => i ≤ n) := Nonempty.intro (set.fintype_le_nat n) theorem finite_lt_nat (n : ℕ) : finite (set_of fun (i : ℕ) => i < n) := Nonempty.intro (set.fintype_lt_nat n) protected instance fintype_prod {α : Type u} {β : Type v} (s : set α) (t : set β) [fintype ↥s] [fintype ↥t] : fintype ↥(set.prod s t) := fintype.of_finset (finset.product (to_finset s) (to_finset t)) sorry theorem finite.prod {α : Type u} {β : Type v} {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) := sorry /-- `image2 f s t` is finitype if `s` and `t` are. -/ protected instance fintype_image2 {α : Type u} {β : Type v} {γ : Type x} [DecidableEq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype ↥s] [ht : fintype ↥t] : fintype ↥(image2 f s t) := eq.mpr sorry (set.fintype_image (set.prod s t) fun (x : α × β) => f (prod.fst x) (prod.snd x)) theorem finite.image2 {α : Type u} {β : Type v} {γ : Type x} (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (image2 f s t) := eq.mpr (id (Eq._oldrec (Eq.refl (finite (image2 f s t))) (Eq.symm (image_prod f)))) (finite.image (fun (x : α × β) => f (prod.fst x) (prod.snd x)) (finite.prod hs ht)) /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bUnion {α : Type u_1} {β : Type u_1} [DecidableEq β] (s : set α) [fintype ↥s] (f : α → set β) (H : (a : α) → a ∈ s → fintype ↥(f a)) : fintype ↥(s >>= f) := fintype_set_bUnion (fun (i : α) => f i) H protected instance fintype_bUnion' {α : Type u_1} {β : Type u_1} [DecidableEq β] (s : set α) [fintype ↥s] (f : α → set β) [H : (a : α) → fintype ↥(f a)] : fintype ↥(s >>= f) := fintype_bUnion s f fun (i : α) (_x : i ∈ s) => H i theorem finite_bUnion {α : Type u_1} {β : Type u_1} {s : set α} {f : α → set β} : finite s → (∀ (a : α), a ∈ s → finite (f a)) → finite (s >>= f) := sorry protected instance fintype_seq {α : Type u} {β : Type u} [DecidableEq β] (f : set (α → β)) (s : set α) [fintype ↥f] [fintype ↥s] : fintype ↥(f <*> s) := eq.mpr sorry (set.fintype_bUnion' f fun (_x : α → β) => _x <$> s) theorem finite.seq {α : Type u} {β : Type u} {f : set (α → β)} {s : set α} : finite f → finite s → finite (f <*> s) := sorry /-- There are finitely many subsets of a given finite set -/ theorem finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite (set_of fun (b : set α) => b ⊆ a) := sorry theorem exists_min_image {α : Type u} {β : Type v} [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : set.nonempty s → ∃ (a : α), ∃ (H : a ∈ s), ∀ (b : α), b ∈ s → f a ≤ f b := sorry theorem exists_max_image {α : Type u} {β : Type v} [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : set.nonempty s → ∃ (a : α), ∃ (H : a ∈ s), ∀ (b : α), b ∈ s → f b ≤ f a := sorry end set namespace finset theorem finite_to_set {α : Type u} (s : finset α) : set.finite ↑s := set.finite_mem_finset s @[simp] theorem coe_bUnion {α : Type u} {β : Type v} [DecidableEq β] {s : finset α} {f : α → finset β} : ↑(finset.bUnion s f) = set.Union fun (x : α) => set.Union fun (H : x ∈ ↑s) => ↑(f x) := sorry @[simp] theorem finite_to_set_to_finset {α : Type u_1} (s : finset α) : set.finite.to_finset (finite_to_set s) = s := sorry end finset namespace set theorem finite_subset_Union {α : Type u} {s : set α} (hs : finite s) {ι : Type u_1} {t : ι → set α} (h : s ⊆ Union fun (i : ι) => t i) : ∃ (I : set ι), finite I ∧ s ⊆ Union fun (i : ι) => Union fun (H : i ∈ I) => t i := sorry theorem eq_finite_Union_of_finite_subset_Union {α : Type u} {ι : Type u_1} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ Union fun (i : ι) => s i) : ∃ (I : set ι), finite I ∧ ∃ (σ : ↥(set_of fun (i : ι) => i ∈ I) → set α), (∀ (i : ↥(set_of fun (i : ι) => i ∈ I)), finite (σ i)) ∧ (∀ (i : ↥(set_of fun (i : ι) => i ∈ I)), σ i ⊆ s ↑i) ∧ t = Union fun (i : ↥(set_of fun (i : ι) => i ∈ I)) => σ i := sorry /-- An increasing union distributes over finite intersection. -/ theorem Union_Inter_of_monotone {ι : Type u_1} {ι' : Type u_2} {α : Type u_3} [fintype ι] [linear_order ι'] [Nonempty ι'] {s : ι → ι' → set α} (hs : ∀ (i : ι), monotone (s i)) : (Union fun (j : ι') => Inter fun (i : ι) => s i j) = Inter fun (i : ι) => Union fun (j : ι') => s i j := sorry protected instance nat.fintype_Iio (n : ℕ) : fintype ↥(Iio n) := fintype.of_finset (finset.range n) sorry /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ theorem seq_of_forall_finite_exists {γ : Type u_1} {P : γ → set γ → Prop} (h : ∀ (t : set γ), finite t → ∃ (c : γ), P c t) : ∃ (u : ℕ → γ), ∀ (n : ℕ), P (u n) (u '' Iio n) := sorry theorem finite_range_ite {α : Type u} {β : Type v} {p : α → Prop} [decidable_pred p] {f : α → β} {g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range fun (x : α) => ite (p x) (f x) (g x)) := finite.subset (finite.union hf hg) range_ite_subset theorem finite_range_const {α : Type u} {β : Type v} {c : β} : finite (range fun (x : α) => c) := finite.subset (finite_singleton c) range_const_subset theorem range_find_greatest_subset {α : Type u} {P : α → ℕ → Prop} [(x : α) → decidable_pred (P x)] {b : ℕ} : (range fun (x : α) => nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := sorry theorem finite_range_find_greatest {α : Type u} {P : α → ℕ → Prop} [(x : α) → decidable_pred (P x)] {b : ℕ} : finite (range fun (x : α) => nat.find_greatest (P x) b) := finite.subset (finset.finite_to_set (finset.range (b + 1))) range_find_greatest_subset theorem card_lt_card {α : Type u} {s : set α} {t : set α} [fintype ↥s] [fintype ↥t] (h : s ⊂ t) : fintype.card ↥s < fintype.card ↥t := sorry theorem card_le_of_subset {α : Type u} {s : set α} {t : set α} [fintype ↥s] [fintype ↥t] (hsub : s ⊆ t) : fintype.card ↥s ≤ fintype.card ↥t := sorry theorem eq_of_subset_of_card_le {α : Type u} {s : set α} {t : set α} [fintype ↥s] [fintype ↥t] (hsub : s ⊆ t) (hcard : fintype.card ↥t ≤ fintype.card ↥s) : s = t := or.elim (eq_or_ssubset_of_subset hsub) id fun (h : s ⊂ t) => absurd hcard (not_le_of_lt (card_lt_card h)) theorem subset_iff_to_finset_subset {α : Type u} (s : set α) (t : set α) [fintype ↥s] [fintype ↥t] : s ⊆ t ↔ to_finset s ⊆ to_finset t := { mp := fun (h : s ⊆ t) (x : α) (hx : x ∈ to_finset s) => iff.mpr mem_to_finset (h (iff.mp mem_to_finset hx)), mpr := fun (h : to_finset s ⊆ to_finset t) (x : α) (hx : x ∈ s) => iff.mp mem_to_finset (h (iff.mpr mem_to_finset hx)) } theorem card_range_of_injective {α : Type u} {β : Type v} [fintype α] {f : α → β} (hf : function.injective f) [fintype ↥(range f)] : fintype.card ↥(range f) = fintype.card α := Eq.symm (fintype.card_congr (equiv.set.range f hf)) theorem finite.exists_maximal_wrt {α : Type u} {β : Type v} [partial_order β] (f : α → β) (s : set α) (h : finite s) : set.nonempty s → ∃ (a : α), ∃ (H : a ∈ s), ∀ (a' : α), a' ∈ s → f a ≤ f a' → f a = f a' := sorry theorem finite.card_to_finset {α : Type u} {s : set α} [fintype ↥s] (h : finite s) : finset.card (finite.to_finset h) = fintype.card ↥s := sorry theorem to_finset_compl {α : Type u_1} [fintype α] (s : set α) : to_finset (sᶜ) = (to_finset sᶜ) := sorry theorem to_finset_inter {α : Type u_1} [fintype α] (s : set α) (t : set α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := sorry theorem to_finset_union {α : Type u_1} [fintype α] (s : set α) (t : set α) : to_finset (s ∪ t) = to_finset s ∪ to_finset t := sorry /--A finite set is bounded above.-/ protected theorem finite.bdd_above {α : Type u} [semilattice_sup α] [Nonempty α] {s : set α} (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty fun (a : α) (s : set α) (_x : ¬a ∈ s) (_x : finite s) (h : bdd_above s) => bdd_above.insert a h /--A finite union of sets which are all bounded above is still bounded above.-/ theorem finite.bdd_above_bUnion {α : Type u} {β : Type v} [semilattice_sup α] [Nonempty α] {I : set β} {S : β → set α} (H : finite I) : bdd_above (Union fun (i : β) => Union fun (H : i ∈ I) => S i) ↔ ∀ (i : β), i ∈ I → bdd_above (S i) := sorry /--A finite set is bounded below.-/ protected theorem finite.bdd_below {α : Type u} [semilattice_inf α] [Nonempty α] {s : set α} (hs : finite s) : bdd_below s := finite.bdd_above hs /--A finite union of sets which are all bounded below is still bounded below.-/ theorem finite.bdd_below_bUnion {α : Type u} {β : Type v} [semilattice_inf α] [Nonempty α] {I : set β} {S : β → set α} (H : finite I) : bdd_below (Union fun (i : β) => Union fun (H : i ∈ I) => S i) ↔ ∀ (i : β), i ∈ I → bdd_below (S i) := finite.bdd_above_bUnion H end set namespace finset /-- A finset is bounded above. -/ protected theorem bdd_above {α : Type u} [semilattice_sup α] [Nonempty α] (s : finset α) : bdd_above ↑s := set.finite.bdd_above (finite_to_set s) /-- A finset is bounded below. -/ protected theorem bdd_below {α : Type u} [semilattice_inf α] [Nonempty α] (s : finset α) : bdd_below ↑s := set.finite.bdd_below (finite_to_set s) end finset theorem fintype.exists_max {α : Type u} [fintype α] [Nonempty α] {β : Type u_1} [linear_order β] (f : α → β) : ∃ (x₀ : α), ∀ (x : α), f x ≤ f x₀ := sorry end Mathlib