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
e07d7546bd243e2bdc378b3614c5620c25acbc05
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0312.lean
9606b4e8071a6a6bb2b17295323bc31d527edf5b
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
107
lean
variables p q : Prop example (h : p ∨ q) : q ∨ p := or.elim h (λ hp, or.inr hp) (λ hq, or.inl hq)
cf6d7bfa192c674028ff678959b83630960a26d0
d5b53bc87e7f4dda87570c8ef6ee4b4de685f315
/src/G_module/basic.lean
be6d1c7fc9d1a3e4ae811383aab759711f5a7a9d
[]
no_license
Shenyang1995/M4R
3bec366fba7262ed29d7f64b4ba7cc978494c022
a6a3399c4d1935b39a22f64c30f293ef2a32fdeb
refs/heads/master
1,597,008,096,640
1,591,722,931,000
1,591,722,931,000
214,177,424
5
0
null
null
null
null
UTF-8
Lean
false
false
2,012
lean
import algebra.group -- for is_add_group_hom import group_theory.subgroup -- for kernels import algebra.module import tactic.linarith import tactic.omega import tactic.fin_cases import add_group_hom.basic import algebra.pi_instances class G_module (G : Type*) [group G] (M : Type*) [add_comm_group M] extends has_scalar G M := (id : ∀ m : M, (1 : G) • m = m) (mul : ∀ g h : G, ∀ m : M, g • (h • m) = (g * h) • m) (linear : ∀ g : G, ∀ m n : M, g • (m + n) = g • m + g • n) attribute [simp] G_module.linear G_module.mul @[simp] lemma G_module.G_neg {G : Type*} [group G] {M : Type*} [add_comm_group M] [G_module G M] (g : G) (m : M) : g • (-m) = -(g • m) := begin -- h1: g • (m+(-m))=(0:M), --norm_num, -- have h: g• (0:M)+g• (0:M)=g• ((0:M)+(0:M)), --rw G_module.linear, -- rw add_zero at h, --exact add_left_eq_self.mp h, --rw G_module.linear at h1, --have h2:g • m + g • -m -(g• m)= -(g• m), -- exact add_left_eq_self.mpr h1, -- have h3:g • m + g • -m -(g• m)= g • -m, -- exact add_sub_cancel' _ _, -- exact (eq.congr rfl h2).mp (eq.symm h3), have h:g • -m +g • m= -(g • m)+g • m, rw <-G_module.linear, norm_num, have h: g• (0:M)+g• (0:M)=g• ((0:M)+(0:M)), rw G_module.linear, rw add_zero at h, exact add_left_eq_self.mp h, exact (add_right_inj (g • m)).mp h, end lemma G_module.G_sum_smul {G : Type*} [group G] {M : Type*} [add_comm_group M] [G_module G M] (n:ℕ )(g : G)(f: ℕ → M):finset.sum (finset.range (n+1))(λ (x : ℕ ), g • f x) = g • finset.sum (finset.range(n+1)) f:= begin induction n with d hd, norm_num, rw finset.sum_range_succ, rw hd, rw <-G_module.linear, rw <-finset.sum_range_succ _ (d+1), end lemma G_module.neg_one_pow_mul_comm {G : Type*} [group G] {M : Type*} [add_comm_group M] [G_module G M] (n:ℕ )(g:G)(m:M): (-1:ℤ )^n • g • m = g • (-1:ℤ)^n • m:= begin induction n with d hd, norm_num, rw nat.succ_eq_add_one, rw pow_add, norm_num, exact hd, end
819db245ff61e12bb1c59dfc66ba9c92ab9ec4fe
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/polynomial/degree/card_pow_degree.lean
96c09b3eed82214b74233c12f446ef8adf3bea55
[ "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
3,702
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.order.euclidean_absolute_value import data.polynomial.field_division /-! # Absolute value on polynomials over a finite field. Let `Fq` be a finite field of cardinality `q`, then the map sending a polynomial `p` to `q ^ degree p` (where `q ^ degree 0 = 0`) is an absolute value. ## Main definitions * `polynomial.card_pow_degree` is an absolute value on `𝔽_q[t]`, the ring of polynomials over a finite field of cardinality `q`, mapping a polynomial `p` to `q ^ degree p` (where `q ^ degree 0 = 0`) ## Main results * `polynomial.card_pow_degree_is_euclidean`: `card_pow_degree` respects the Euclidean domain structure on the ring of polynomials -/ namespace polynomial variables {Fq : Type*} [field Fq] [fintype Fq] open absolute_value open_locale classical /-- `card_pow_degree` is the absolute value on `𝔽_q[t]` sending `f` to `q ^ degree f`. `card_pow_degree 0` is defined to be `0`. -/ noncomputable def card_pow_degree : absolute_value (polynomial Fq) ℤ := have card_pos : 0 < fintype.card Fq := fintype.card_pos_iff.mpr infer_instance, have pow_pos : ∀ n, 0 < (fintype.card Fq : ℤ) ^ n := λ n, pow_pos (int.coe_nat_pos.mpr card_pos) n, { to_fun := λ p, if p = 0 then 0 else fintype.card Fq ^ p.nat_degree, nonneg' := λ p, by { split_ifs, { refl }, exact pow_nonneg (int.coe_zero_le _) _ }, eq_zero' := λ p, ite_eq_left_iff.trans $ ⟨λ h, by { contrapose! h, exact ⟨h, (pow_pos _).ne'⟩ }, absurd⟩, add_le' := λ p q, begin by_cases hp : p = 0, { simp [hp] }, by_cases hq : q = 0, { simp [hq] }, by_cases hpq : p + q = 0, { simp only [hpq, hp, hq, eq_self_iff_true, if_true, if_false], exact add_nonneg (pow_pos _).le (pow_pos _).le }, simp only [hpq, hp, hq, if_false], refine le_trans (pow_le_pow (by linarith) (polynomial.nat_degree_add_le _ _)) _, refine le_trans (le_max_iff.mpr _) (max_le_add_of_nonneg (pow_nonneg (by linarith) _) (pow_nonneg (by linarith) _)), exact (max_choice p.nat_degree q.nat_degree).imp (λ h, by rw [h]) (λ h, by rw [h]) end, map_mul' := λ p q, begin by_cases hp : p = 0, { simp [hp] }, by_cases hq : q = 0, { simp [hq] }, have hpq : p * q ≠ 0 := mul_ne_zero hp hq, simp only [hpq, hp, hq, eq_self_iff_true, if_true, if_false, polynomial.nat_degree_mul hp hq, pow_add], end } lemma card_pow_degree_apply (p : polynomial Fq) : card_pow_degree p = if p = 0 then 0 else fintype.card Fq ^ nat_degree p := rfl @[simp] lemma card_pow_degree_zero : card_pow_degree (0 : polynomial Fq) = 0 := if_pos rfl @[simp] lemma card_pow_degree_nonzero (p : polynomial Fq) (hp : p ≠ 0) : card_pow_degree p = fintype.card Fq ^ p.nat_degree := if_neg hp lemma card_pow_degree_is_euclidean : is_euclidean (card_pow_degree : absolute_value (polynomial Fq) ℤ) := have card_pos : 0 < fintype.card Fq := fintype.card_pos_iff.mpr infer_instance, have pow_pos : ∀ n, 0 < (fintype.card Fq : ℤ) ^ n := λ n, pow_pos (int.coe_nat_pos.mpr card_pos) n, { map_lt_map_iff' := λ p q, begin simp only [euclidean_domain.r, card_pow_degree_apply], split_ifs with hp hq hq, { simp only [hp, hq, lt_self_iff_false] }, { simp only [hp, hq, degree_zero, ne.def, bot_lt_iff_ne_bot, degree_eq_bot, pow_pos, not_false_iff] }, { simp only [hp, hq, degree_zero, not_lt_bot, (pow_pos _).not_lt] }, { rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe, pow_lt_pow_iff], exact_mod_cast @fintype.one_lt_card Fq _ _ }, end } end polynomial
8cf5c0e4201c5debdf6c78f4acda69bd5dc14dd2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/inductive_sorry.lean
37bb8d15b8bed4b5a7ed3e9eddaee08bedeae083
[ "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
199
lean
inductive foo₁ (A : sorry → ℕ) | mk : foo₁ inductive foo₂ : sorry → Type | mk : foo₂ sorry inductive foo₃ | mk : sorry → foo₃ structure foo₄ (A : sorry → ℕ) := (x : ℕ)
0f8d791b04560d3ef6671d9faeabe8a6dd67d729
43390109ab88557e6090f3245c47479c123ee500
/src/Geometry/tarski_3.lean
1534c5379142580c6ac5bdb69908e67e14eb3f42
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,263
lean
import geometry.tarski_2 open classical set namespace Euclidean_plane variables {point : Type} [Euclidean_plane point] local attribute [instance, priority 0] prop_decidable -- Right Angles def R (a b c : point) : Prop := eqd a c a (S b c) theorem R.symm {a b c : point} : R a b c → R c b a := begin intro h, have h1 := seven13 b a (S b c), simp at h1, unfold R at h, exact (eqd.trans h h1).flip end theorem eight3 {a b c a' : point} : R a b c → a ≠ b → col b a a' → R a' b c := begin intros h h1 h2, unfold R at *, exact four17 h1.symm h2 (seven5 b c).2 h end theorem R.flip {a b c : point} : R a b c → R a b (S b c) := begin intro h, unfold R at *, simpa using h.symm end @[simp] theorem eight4 (a b : point) : R a a b := (seven5 a b).2 @[simp] theorem eight5a (a b : point) : R a b b := (eight4 b a).symm theorem eight6 {a b c a' : point} : R a b c → R a' b c → B a c a' → b = c := begin intros h h1 h2, unfold R at *, generalize h3 : S b c = c', rw h3 at *, have : c = c', exact four19 h2 h h1.flip, rw ←this at *, exact (seven10.1 h3) end theorem eight7 {a b c : point} : R a b c → R a c b → b = c := begin intros h h1, have h_1 : eqd a c a (S b c), unfold R at h, exact h, have h_2 : eqd a b a (S c b), unfold R at h1, exact h1, have h2 := seven5 b c, generalize h3 : S b c = c', rw h3 at *, generalize h4 : S c a = a', by_contradiction h5, have h6 : col c b c', left, exact h2.1, have h7 := eight3 h1.symm h5 h6, unfold R at h7, rw h4 at h7, have h8 := seven5 c a, rw h4 at h8, have h9 := h8.2, have h10 : R a' b c, unfold R, rw h3, exact eqd.trans h9.symm.flip (eqd.trans h_1 h7.flip), exact h5 (eight6 h h10 h8.1) end theorem eight8 {a b : point} : R a b a → a = b := begin intro h, exact eight7 (eight5a b a).symm h end theorem eight9 {a b c : point} : R a b c → col a b c → a = b ∨ c = b := begin intros h h1, cases em (a = b), simp *, right, have h2 := eight3 h h_1 (four11 h1).2.1, exact eight8 h2 end theorem eight10 {a b c a' b' c' : point} : R a b c → cong a b c a' b' c' → R a' b' c' := begin intros h h1, cases em (b = c), rw h_1 at *, have h2 : b' = c', exact id_eqd h1.2.1.symm, rw h2, exact eight5a a' c', unfold R at *, generalize h2 : S b c = d, generalize h3 : S b' c' = d', have h4 := seven5 b c, have h5 := seven5 b' c', rw h2 at *, rw h3 at *, have h6 : afs c b d a c' b' d' a', repeat {split}, exact h4.1, exact h5.1, exact h1.2.1.flip, exact eqd.trans h4.2.symm (eqd.trans h1.2.1 h5.2), exact h1.2.2.flip, exact h1.1.flip, have h7 := afive_seg h6 (ne.symm h_1), exact eqd.trans h1.2.2.symm (eqd.trans h h7.flip) end def xperp (x : point) (A A' : set point) : Prop := line A ∧ line A' ∧ x ∈ A ∧ x ∈ A' ∧ ∀ {u v}, u ∈ A → v ∈ A' → R u x v def perp (A A' : set point) : Prop := ∃ x, xperp x A A' notation A ` ⊥ ` B := perp A B theorem xperp.symm {x : point} {A A' : set point} : xperp x A A' → xperp x A' A := begin intro h, unfold xperp at *, split, exact h.2.1, split, exact h.1, split, exact h.2.2.2.1, split, exact h.2.2.1, intros u v hu hv, exact (h.2.2.2.2 hv hu).symm end theorem perp.symm {A A' : set point} : perp A A' → perp A' A := begin intro h, cases h with x hx, constructor, exact hx.symm end theorem eight14a {A A' : set point} : perp A A' → A ≠ A' := begin intros h h1, subst A', rcases h with ⟨x, h1, h2, h3, h4, h5⟩, cases six22 h1 h3 with y hy, rw hy.2 at h5, exact hy.1.symm (eight8 (h5 (six17b x y) (six17b x y))) end theorem eight14b {x : point} {A A' : set point} : xperp x A A' → A ≠ A' := λ h, eight14a ⟨x, h⟩ theorem eight14c {x : point} {A A' : set point} : xperp x A A' ↔ perp A A' ∧ is x A A' := begin split, intro h, split, constructor, exact h, have h1 : perp A A', constructor, exact h, unfold xperp at h, unfold is, split, exact h.1, split, exact h.2.1, split, exact eight14a h1, split, exact h.2.2.1, exact h.2.2.2.1, intro h, cases h with h h1, cases h with y hy, unfold is at h1, suffices : x = y, rwa ←this at hy, by_contradiction, suffices : A = A', exact h1.2.2.1 this, apply six21 a h1.1 h1.2.1 h1.2.2.2.1 h1.2.2.2.2, unfold xperp at hy, exact hy.2.2.1, exact hy.2.2.2.1 end theorem eight14d {x y : point} {A A' : set point} : xperp x A A' → xperp y A A' → x = y := begin intros hx hy, by_contradiction, have h : perp A A', constructor, exact hx, have h1 := eight14a h, suffices : A = A', exact h1 this, unfold xperp at *, exact six21 a hx.1 hx.2.1 hx.2.2.1 hx.2.2.2.1 hy.2.2.1 hy.2.2.2.1 end theorem eight14e {A A' : set point} : perp A A' → line A ∧ line A' := begin intro h, cases h with x hx, split, exact hx.1, exact hx.2.1 end theorem eight14f {a b c : point} {A : set point} : perp (l a b) A → col a b c → a ≠ c → perp (l a c) A := begin intros h h1 h2, suffices : l a b = l a c, rwa ←this, exact six18 (eight14e h).1 h2 (six17a a b) h1 end theorem eight13 {x : point} {A A' : set point} : xperp x A A' ↔ line A ∧ line A' ∧ x ∈ A ∧ x ∈ A' ∧ ∃ u v, u ∈ A ∧ v ∈ A' ∧ u ≠ x ∧ v ≠ x ∧ R u x v := begin split, intro h, split, exact h.1, split, exact h.2.1, split, exact h.2.2.1, split, exact h.2.2.2.1, unfold xperp at h, cases six22 h.1 h.2.2.1 with u hu, cases six22 h.2.1 h.2.2.2.1 with v hv, existsi u, existsi v, have h1 : u ∈ A, rw hu.2, simp, have h2 : v ∈ A', rw hv.2, simp, split, exact h1, split, exact h2, split, exact hu.1.symm, split, exact hv.1.symm, exact h.2.2.2.2 h1 h2, intro h, unfold xperp, split, exact h.1, split, exact h.2.1, split, exact h.2.2.1, split, exact h.2.2.2.1, intros a b ha hb, cases h.2.2.2.2 with u hu, cases hu with v hv, have h1 : R a x v, apply eight3 hv.2.2.2.2 hv.2.2.1, have h_1 : A = l x u, exact six18 h.1 hv.2.2.1.symm h.2.2.1 hv.1, rw h_1 at ha, exact ha, apply R.symm, apply eight3 h1.symm hv.2.2.2.1, have h_2 : A' = l x v, exact six18 h.2.1 hv.2.2.2.1.symm h.2.2.2.1 hv.2.1, rw h_2 at hb, exact hb end theorem perp_of_R {a b c : point} : a ≠ b → c ≠ b → R a b c → perp (l a b) (l c (S b c)) := λ h h1 h2, ⟨b, eight13.2 ⟨six14 h, six14 (seven12b h1).symm, six17b a b, or.inr (or.inl (seven5 b c).1.symm), a, c, six17a a b, six17a c (S b c), h, h1, h2⟩⟩ theorem xperp_of_R {a b c : point} : a ≠ b → c ≠ b → R a b c → xperp b (l a b) (l c b) := λ h h1 h2, eight13.2 ⟨six14 h, six14 h1, six17b a b, six17b c b, a, c, six17a a b, six17a c b, h, h1, h2⟩ theorem eight15 {x : point} {A B : set point} : perp A B → x ∈ A → x ∈ B → xperp x A B := begin intros h h1 h2, cases h with y hy, suffices : x = y, subst x, exact hy, by_contradiction h_1, apply eight14b hy, apply six21 h_1, exact hy.1, exact hy.2.1, exact h1, exact h2, exact hy.2.2.1, exact hy.2.2.2.1 end theorem eight16 {a b c u x : point} : col a b x → col a b u → u ≠ x → (c ≠ x ∧ perp (l a b) (l c x) ↔ ¬col a b c ∧ R c x u) := begin intros h1 h2 h3, split, intro h4, have h5 : xperp x (l a b) (l c x), exact eight15 h4.2 h1 (six17b c x), split, intro h_1, apply eight14b h5, exact six18 h5.1 h4.1 h_1 h1, apply R.symm, exact h5.2.2.2.2 h2 (six17a c x), intro h4, cases h4 with h4 h5, have h_1 : c ≠ x, intro h_1, rw h_1 at h4, exact h4 h1, split, exact h_1, existsi x, apply eight13.2, split, exact six14 (six26 h4).1, split, exact six14 h_1, split, exact h1, split, simp, existsi u, existsi c, split, exact h2, split, exact (six17a c x), split, exact h3, split, exact h_1, exact h5.symm end theorem eight18 {a b c : point} : ¬col a b c → ∃! x, col a b x ∧ perp (l a b) (l c x) := begin intros h, cases seg_cons a a c b with y hy, cases seven25 hy.2.symm with p hp, have h1: R a p y, unfold R, suffices : S p y = c, rw this, exact hy.2, exact (seven6 hp.symm).symm, cases seg_cons y y p a with z hz, cases seg_cons y y a p with q hq, generalize hq' : S z q = q', cases seg_cons y y c q' with c' hc', have h2 : afs a y z q q y p a, focus {repeat {split}}, exact hz.1, exact hq.1.symm, exact hq.2.symm.flip, exact hz.2, exact two5 (eqd.refl a q), exact hq.2, have h3 : a ≠ y, intro h_1, rw h_1 at *, have : y = c, exact id_eqd hy.2.symm, exact (six26 h).2.2 this, have h4 := afive_seg h2 h3, have h5 : cong a p y q z y, split, exact h4.symm.flip, split, exact hz.2.symm.flip, exact hq.2.symm.flip, have h6 := (eight10 h1 h5).symm, have h7 : eqd y q y q', unfold R at h6, rwa hq' at h6, cases seven25 hc'.2 with x hx, existsi x, have h8 : R y x c, unfold R, suffices : S x c = c', rw this, exact hc'.2.symm, exact (seven6 hx.symm).symm, have h9 : c ≠ y, intro h_1, rw ←h_1 at hy, apply h, right, right, exact hy.1.symm, have h10 : y ≠ p, intro h_1, rw ←h_1 at hp, unfold M at hp, apply h9, exact id_eqd hp.2.flip, have h11 : hourglass q q' y c c' z x, have h_1 := seven5 z q, rw hq' at h_1, focus {repeat {split}}, exact (three7a hp.1 hq.1 h10.symm).symm, exact hc'.1, exact h7, exact hc'.2.symm, exact h_1.1, exact h_1.2, exact hx.1.symm, exact hx.2.symm, have h12 := seven22 h11, have h13 : y ≠ z, intro h_1, rw ←h_1 at hz, exact h10 (id_eqd hz.2.symm), have h14 : a ≠ y, intro h_1, rw ←h_1 at hy, apply (six26 h).2.2, exact id_eqd hy.2.symm, have h15 : l y z = l a b, apply six18 (six14 h13) (six26 h).1, right, right, exact hz.1, right, right, exact three7a hy.1 hz.1 h14, have h16 : c ≠ x, intro h_1, rw h_1 at *, apply h, have h_2 : x ∈ l a b, rw ←h15, right, right, exact h12.symm, exact h_2, have h17 : q ≠ z, intro h_1, rw h_1 at *, have h_2 : B z y c, exact three7b hq.1.symm hp.1.symm h10, apply h, suffices : c ∈ l a b, exact this, rw ←h15, right, right, exact h_2.symm, have h18 : xperp x (l y z) (l c x), apply eight13.2, split, exact six14 h13, split, exact (six14 h16), split, right, right, exact h12.symm, split, simp, existsi y, existsi c, simp, split, intro h_1, rw h_1 at *, have h_1 : q ∈ l c x, left, exact three7a hp.1 hq.1 h10.symm, have h_2 : q' ∈ l c x, suffices : c' ≠ x, cases five2 this hx.1 hc'.1.symm, right, right, exact h_2.symm, right, left, exact h_2, intro h_2, rw h_2 at *, apply h9, exact id_eqd hx.2.symm.flip, have h_3 := seven5 z q, rw hq' at h_3, have h_4 : q ≠ q', intro h_4, rw ←h_4 at *, apply h17, exact seven3.1 h_3, have h_5 : l c x = l q q', exact six18 (six14 h9) h_4 h_1 h_2, have h_6 : z ∈ l c x, rw h_5, right, left, exact h_3.1.symm, have h_7 := (four11 h_6).2.2.1, have h_8 : c ∈ l a b, rw ←h15, exact h_7, exact h h_8, split, exact h16, exact h8, rw h15 at h18, have h19 : x ∈ l y z, right, right, exact h12.symm, split, split, rw h15 at h19, exact h19, constructor, exact h18, intros x' hx', have h20 : c ≠ x', intro h_1, apply h, rw ←h_1 at hx', exact hx'.1, have h21 : xperp x' (l a b) (l c x'), exact eight15 hx'.2 hx'.1 (six17b c x'), have h22 : R c x x', apply (h18.symm).2.2.2.2, simp, exact hx'.1, have h23 : R c x' x, apply (h21.symm).2.2.2.2, simp, rw ←h15, exact h19, exact eight7 h23 h22 end theorem eight17 {a : point} {A : set point} : line A → a ∉ A → ∃! x, xperp x A (l a x) := begin intros h h1, rcases h with ⟨p, q, hq, h2⟩, subst h2, have h3 : ¬col p q a, intro h_1, exact h1 h_1, cases eight18 h3 with x hx, refine ⟨x, eight15 hx.1.2 hx.1.1 (six17b a x), _⟩, intros y hy, exact hx.2 y ⟨hy.2.2.1, y, hy⟩ end theorem eight19 {p q r : point} (a : point) : R p q r ↔ R (S a p) (S a q) (S a r) := begin unfold R, split, intro h, suffices : (S (S a q) (S a r)) = (S a (S q r)), rw this, exact (seven16 a).1 h, have h1 := seven5 (S a q) (S a r), suffices : M (S a r) (S a q) (S a (S q r)), exact seven4 h1 this, apply (seven14 a).1, exact seven5 q r, intro h, suffices : S a ((S (S a q) (S a r))) = S q r, rw ←this, apply (seven16 a).2, simp, exact h, suffices : S a (S a (S (S a q) (S a r))) = (S a (S q r)), exact seven9 this, simp, have h1 := seven5 (S a q) (S a r), suffices : M (S a r) (S a q) (S a (S q r)), exact seven4 h1 this, apply (seven14 a).1, exact seven5 q r end theorem eight20 {a b c p : point} : R a b c → M (S a c) p (S b c) → R b a p ∧ (b ≠ c → a ≠ p) := begin intros h h1, have h2 := seven5 b c, have h3 := seven5 a b, have h4 := seven5 a c, have h5 := seven5 a (S b c), have h6 := seven5 a p, have h7 : R (S a b) b c, cases em (a = b), rw h_1 at *, simp, apply eight3 h h_1, left, exact h3.1, have h8 := (eight19 a).1 h7, unfold R at h7, have h9 := (seven16 a).1 h7, simp at *, have h10 : ifs (S a c) p (S b c) b (S a (S b c)) (S a p) c b, focus {repeat {split}}, exact h1.1, have h_1 := (seven15 a).1 h1.1, simp at h_1, exact h_1.symm, apply two5, have h_2 := seven13 a (S a c) (S b c), simp at h_2, exact h_2, apply eqd.trans h1.2.symm, have h_3 := seven13 a p (S a c), simp at h_3, exact h_3, exact h9.flip, exact h2.2.symm.flip, have h11 := four2 h10, split, unfold R, exact h11.flip, intros hbc hap, apply hbc, have h12 := seven7 a c, rw hap at *, have h13 := seven5 p (S p c), simp at h13, have h14 := seven4 h13 h1, rw ←h14 at h2, exact (seven3.1 h2).symm end theorem eight21 {a b : point} (hab : a ≠ b) (c : point) : ∃ p t, perp (l a b) (l p a) ∧ col a b t ∧ B c t p := begin cases em (col a b c) with habc h, cases six25 hab with c' h, cases eight18 h with x hx, have h1 : c' ≠ x, intro h_1, rw h_1 at *, exact h hx.1.1, have h2 : xperp x (l a b) (l c' x), exact eight15 hx.1.2 hx.1.1 (six17b c' x), unfold xperp at h2, have h3 := h2.2.2.2.2 (six17a a b) (six17a c' x), unfold R at h3, have h4 := seven5 a c', cases seven25 (eqd.trans h4.2.symm h3) with p hp, have h5 := eight20 (h2.2.2.2.2 (six17a a b) (six17a c' x)) hp, have h6 := h5.2 h1.symm, existsi p, existsi c, cases em (x = a), rw h_1 at hx, rw h_1 at hp, have h_2 : S a c' = p, exact seven3.1 hp, rw h_2 at h4, have h_3 : col c' a p, left, exact h4.1, have h_4 : l c' a = l p a, apply six18 (six14 (six26 h).2.2.symm) h6.symm h_3 (six17b c' a), have h_5 := hx.1, rw h_4 at h_5, split, exact h_5.2, split, exact habc, exact three3 c p, split, existsi a, apply eight13.2, split, exact six14 (six26 h).1, split, exact six14 h6.symm, split, simp, split, simp, existsi x, existsi p, split, exact hx.1.1, simp, split, exact h_1, split, exact h6.symm, exact h5.1, split, exact habc, exact three3 c p, cases eight18 h with x hx, have h1 : c ≠ x, intro h_1, rw h_1 at *, exact h hx.1.1, have h2 : xperp x (l a b) (l c x), exact eight15 hx.1.2 hx.1.1 (six17b c x), unfold xperp at h2, have h3 := h2.2.2.2.2 (six17a a b) (six17a c x), unfold R at h3, have h4 := seven5 a c, cases seven25 (eqd.trans h4.2.symm h3) with p hp, have h5 := eight20 (h2.2.2.2.2 (six17a a b) (six17a c x)) hp, have h6 := h5.2 h1.symm, cases three17 (seven5 x c).1.symm h4.1.symm hp.1.symm with t ht, cases em (x = a), rw h_1 at ht, existsi p, existsi a, have h_2 : t = a, exact (bet_same ht.2).symm, rw h_2 at *, rw h_1 at hx, have h_3 := hx.1, have h_4 : l c a = l p a, apply six18 (six14 (six26 h).2.2.symm) h6.symm, left, exact ht.1.symm, simp, rw h_4 at h_3, split, exact h_3.2, split, exact h_3.1, exact ht.1.symm, existsi p, existsi t, have h7 : col a b t, have h_2 : col a x t, right, left, exact ht.2, exact five4 (ne.symm h_1) (four11 hx.1.1).1 h_2, split, existsi a, apply eight13.2, split, exact six14 (six26 h).1, split, exact six14 h6.symm, split, simp, split, simp, existsi x, existsi p, split, exact hx.1.1, split, simp, split, exact h_1, split, exact h6.symm, exact h5.1, split, exact h7, exact ht.1.symm end lemma eight23 {a b p q t t' r : point} (hp : ((l a b) ⊥ l p a) ∧ col a b t' ∧ B a t' p) (ht : ((l b a) ⊥ l q b) ∧ col b a t ∧ B p t q) (hr : B b r q ∧ eqd a p b r): ∃ x, M a x b ∧ M p x r := begin have h : a ≠ b, exact six13 (eight14e hp.1).1, cases pasch ht.2.2 hr.1 with x hx, have h1 : col a b x, have h_1 : col b t x, right, left, exact hx.1, cases em (b = t), rw ←h_2 at *, have h_3 : x = b, exact (bet_same hx.1).symm, rw h_3, left, exact three1 a b, exact (four11 (five4 h_2 (four11 ht.2.1).1 h_1)).2.1, have h2 : xperp a (l a b) (l p a), exact eight15 hp.1 (four11 (four12 a b)).1 (six17b p a), have h3 : xperp b (l b a) (l q b), exact eight15 ht.1 (four11 (four12 b a)).1 (six17b q b), have h4 := h2.2.2.2.2 (six17b a b) (six17a p a), have h5 := h3.2.2.2.2 (six17b b a) (six17a q b), have h6 : R a b r, have : col b q r, right, left, exact hr.1.symm, exact (eight3 h5.symm (six13 h3.2.1) this).symm, have h7 : ¬col a p b, intro h_1, cases eight9 h4 (four11 h_1).2.2.2.1, exact h h_2.symm, exact (six13 h2.2.1) h_2, have h8 : ¬col a b r, intro h_1, cases eight9 h6 h_1, exact h h_2, rw h_2 at *, exact (six13 h2.2.1).symm (id_eqd hr.2), suffices : eqd b p a r, have h_1 : p ≠ r, intro h_1, rw h_1 at hx, have h_2 : r = x, exact bet_same hx.2, rw h_2 at h8, exact h8 h1, constructor, apply seven21 h7 h_1 hr.2 this.flip (four11 h1).1, left, exact hx.2.symm, have h9 : x ≠ a, intro h_1, rw h_1 at *, have h_2 : col a p r, right, right, exact hx.2, have h_3 : R r a b, exact eight3 h4.symm (six13 h2.2.1) h_2, apply h, exact eight7 h_3 h6.symm, have h10 := seven5 a p, cases seg_cons x x r (S a p) with r' hr', cases seven25 hr'.2 with m hm, have h11 := seven5 m r, have h12 := seven4 h11 hm.symm, have h13 : R x m r, unfold R, rw ←h12 at hr', exact hr'.2.symm, have h14 : R x a p, exact eight3 h4 (ne.symm h) h1, have h15 : ¬col x p (S a p), intro h_1, have h_2 : col p a (S a p), left, exact (seven5 a p).1, have h_3 : p ≠ (S a p), intro h_3, exact (six13 h2.2.1) (seven10.1 h_3.symm).symm, have h_4 : col p a x, exact five4 h_3 (four11 h_2).1 (four11 h_1).2.2.1, cases eight9 h14.symm h_4, exact (six13 h2.2.1) h_5, exact h9 h_5, have h16 : hourglass p (S a p) x r r' a m, focus {repeat {split}}, exact hx.2.symm, exact hr'.1, unfold R at h14, exact h14, exact hr'.2.symm, exact h10.1, exact h10.2, rw ←h12, exact h11.1, rw ←h12, exact h11.2, have h17 := seven22 h16, have h18 : r ≠ m, intro h_1, rw ←h_1 at h17, have h_2 : col a x r, left, exact h17, apply h8, exact five4 h9.symm (four11 h1).1 h_2, have h19 : x ≠ m, intro h_1, have h_2 : col r x p, left, exact hx.2, have h_3 : x ≠ r', intro h_3, rw [←h_1, ←h_3] at h12, rw ←h_1 at h18, apply h18, exact seven9 (eq.trans h12 (seven11 x).symm), have h_4 : col r x (S a p), have h_4 : col x r' (S a p), right, right, exact hr'.1, have h_5 : col x r' r, rw h_1, right, right, exact hm.1.symm, exact (four11 (five4 h_3 h_5 h_4)).2.1, have h_5 : x ≠ r, intro h_5, rw h_5 at h_1, exact h18 h_1, apply h15, exact five4 h_5 (four11 h_2).2.1 (four11 h_4).2.1, have h20 : col a b m, have h_1 : col a x m, left, exact h17, exact five4 h9.symm (four11 h1).1 h_1, have h21 : xperp b (l a b) (l r b), apply eight13.2, split, exact six14 h, split, exact six14 (six26 h8).2.1.symm, split, simp, split, simp, existsi a, existsi r, simp, split, exact h, split, exact (six26 h8).2.1.symm, exact h6, have h22 : xperp m (l a b) (l r m), apply eight13.2, split, exact six14 h, split, exact six14 h18, split, exact h20, split, simp, existsi x, existsi r, split, exact h1, simp, split, exact h19, split, exact h18, exact h13, have h23 : perp (l a b) (l r b), constructor, exact h21, have h24 : perp (l a b) (l r m), constructor, exact h22, have h25 : m = b, apply unique_of_exists_unique (eight18 h8), split, exact h20, exact h24, split, left, exact three1 a b, exact h23, subst m, have h26 : ifs (S a p) a p r r b r' (S a p), focus {repeat {split}}, exact h10.1.symm, exact hm.1.symm, apply two4, apply two11 h10.1 hm.1.symm, exact hr.2.flip, exact eqd.trans h10.2.symm (eqd.trans hr.2 hm.2.symm), exact eqd.trans hr.2 hm.2.symm, exact two4 (eqd.refl r (S a p)), apply two5, apply two11 hx.2.symm hr'.1, unfold R at h14, exact h14.flip, exact hr'.2.symm, have h27 := four2 h26, unfold R at h4, exact eqd.trans h4 h27.symm end theorem eight22 (a b : point) : ∃! x, M a x b := begin cases em (a = b), rw h, existsi b, split, apply seven3.2, refl, intros y hy, exact (seven3.1 hy).symm, apply exists_unique_of_exists_of_unique, cases eight21 h a with p hp, cases eight21 (ne.symm h) p with q hq, cases hp with t' hp, cases hq with t ht, cases five10 a p b q, cases h_1 with r hr, cases eight23 hp ht hr with x hx, constructor, exact hx.1, suffices : ∃ x, M b x a, cases this with x hx, constructor, exact hx.symm, cases h_1 with r hr, have : ∃ x, M b x a ∧ M q x r, apply eight23, split, exact ht.1, split, exact (four11 (four12 b a)).1, exact three3 b q, split, exact hp.1, split, exact (four11 ht.2.1).2.1, exact ht.2.2.symm, exact hr, cases this with x hx, constructor, exact hx.1, intros x y hx hy, exact seven17 hx hy end theorem eight24 {a b p q r t : point} : perp (l p a) (l a b) → perp (l q b) (l a b) → col a b t → B p t q → B b r q → eqd a p b r → ∃ x, M a x b ∧ M p x r := begin intros g3 g4 g5 g6 g7 g8, have g9 := (four11 (four12 a b)).1, have g10 := three3 a p, have g11 := six17 a b, rw g11 at g4, have hp : ((l a b) ⊥ l p a) ∧ col a b a ∧ B a a p, exact ⟨g3.symm, ⟨g9, g10⟩⟩, have ht : ((l b a) ⊥ l q b) ∧ col b a t ∧ B p t q, exact ⟨g4.symm, ⟨(four11 g5).2.1, g6⟩⟩, have hr : B b r q ∧ eqd a p b r, exact ⟨g7, g8⟩, exact eight23 hp ht hr end theorem eight25 {a b : point} : a ≠ b → ∃ c, R a b c ∧ c ≠ b := begin intro h, rcases eight21 h.symm a with ⟨c, p, h1⟩, refine ⟨c, (eight15 h1.1 (six17a b a) (six17b c b)).2.2.2.2 (six17b b a) (six17a c b), _⟩, exact six13 (eight14e h1.1).2 end end Euclidean_plane
ee1da4b7b0fb67be65e225e216aa22f157514231
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/combinatorics/stirling.lean
2ee846ad994ae0d642253c8ee795aa6af163012f
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,725
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This is about the Stirling numbers (of the first and second kinds) and the Bell numbers, which arise in various places in combinatorics. The file combinatorics/partition/fin_map.lean contains the basic theorems about the combinatorial interpretation of `stirling2` and `bell`. We have not yet proved anything about `stirling1`. -/ import algebra.big_operators namespace partition.number /- https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind https://oeis.org/A008275 OEIS defines a signed integer s(n,r); our (stirling 1 n r) is OEIS's |s(n,r)|. The command below gives an initial segment of the list of values as given by OEIS. #eval (list.Ico 1 7).bind (λ n, (list.Ico 1 (n + 1)).map (stirling1 n)) -/ def stirling1 : ∀ (n r : ℕ), ℕ | 0 0 := 1 | 0 (r + 1) := 0 | (n + 1) 0 := 0 | (n + 1) (r + 1) := (stirling1 n r) + (stirling1 n (r + 1)) * n /- https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind https://oeis.org/A008277 Our (stirling2 n r) is OEIS's S2(n,r). The command below gives an initial segment of the list of values as given by OEIS. #eval (list.Ico 1 7).bind (λ n, (list.Ico 1 (n + 1)).map (stirling2 n)) -/ def stirling2 : ∀ (n r : ℕ), ℕ | 0 0 := 1 | 0 (r + 1) := 0 | (n + 1) 0 := 0 | (n + 1) (r + 1) := (stirling2 n r) + (stirling2 n (r + 1)) * (r + 1) /- https://en.wikipedia.org/wiki/Bell_number https://oeis.org/A000110 #eval (list.range 5).map bell -/ def bell (n : ℕ) : ℕ := list.sum ((list.range n.succ).map (stirling2 n)) end partition.number
5dd1ec55cc8096bf85f59400a5b544ec48e80eb4
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebraic_geometry/morphisms/ring_hom_properties.lean
e240172a464f323aee3eef13d2535808abae1aa9
[ "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
23,595
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.morphisms.basic import ring_theory.local_properties /-! # Properties of morphisms from properties of ring homs. We provide the basic framework for talking about properties of morphisms that come from properties of ring homs. For `P` a property of ring homs, we have two ways of defining a property of scheme morphisms: Let `f : X ⟶ Y`, - `target_affine_locally (affine_and P)`: the preimage of an affine open `U = Spec A` is affine (`= Spec B`) and `A ⟶ B` satisfies `P`. (TODO) - `affine_locally P`: For each pair of affine open `U = Spec A ⊆ X` and `V = Spec B ⊆ f ⁻¹' U`, the ring hom `A ⟶ B` satisfies `P`. For these notions to be well defined, we require `P` be a sufficient local property. For the former, `P` should be local on the source (`ring_hom.respects_iso P`, `ring_hom.localization_preserves P`, `ring_hom.of_localization_span`), and `target_affine_locally (affine_and P)` will be local on the target. (TODO) For the latter `P` should be local on the target (`ring_hom.property_is_local P`), and `affine_locally P` will be local on both the source and the target. Further more, these properties are stable under compositions (resp. base change) if `P` is. (TODO) -/ universe u open category_theory opposite topological_space category_theory.limits algebraic_geometry variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop) namespace ring_hom include P variable {P} lemma respects_iso.basic_open_iff (hP : respects_iso @P) {X Y : Scheme} [is_affine X] [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) : P (Scheme.Γ.map (f ∣_ Y.basic_open r).op) ↔ P (@is_localization.away.map (Y.presheaf.obj (opposite.op ⊤)) _ (Y.presheaf.obj (opposite.op $ Y.basic_open r)) _ _ (X.presheaf.obj (opposite.op ⊤)) _ (X.presheaf.obj (opposite.op $ X.basic_open (Scheme.Γ.map f.op r))) _ _ (Scheme.Γ.map f.op) r _ _) := begin rw [Γ_map_morphism_restrict, hP.cancel_left_is_iso, hP.cancel_right_is_iso, ← (hP.cancel_right_is_iso (f.val.c.app (opposite.op (Y.basic_open r))) (X.presheaf.map (eq_to_hom (Scheme.preimage_basic_open f r).symm).op)), ← eq_iff_iff], congr, delta is_localization.away.map, refine is_localization.ring_hom_ext (submonoid.powers r) _, convert (is_localization.map_comp _).symm using 1, change Y.presheaf.map _ ≫ _ = _ ≫ X.presheaf.map _, rw f.val.c.naturality_assoc, erw ← X.presheaf.map_comp, congr, end lemma respects_iso.basic_open_iff_localization (hP : respects_iso @P) {X Y : Scheme} [is_affine X] [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) : P (Scheme.Γ.map (f ∣_ Y.basic_open r).op) ↔ P (localization.away_map (Scheme.Γ.map f.op) r) := (hP.basic_open_iff _ _).trans (hP.is_localization_away_iff _ _ _ _).symm lemma respects_iso.of_restrict_morphism_restrict_iff (hP : ring_hom.respects_iso @P) {X Y : Scheme} [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) (U : opens X.carrier) (hU : is_affine_open U) {V : opens _} (e : V = (opens.map (X.of_restrict ((opens.map f.1.base).obj _).open_embedding).1.base).obj U) : P (Scheme.Γ.map ((X.restrict ((opens.map f.1.base).obj _).open_embedding).of_restrict V.open_embedding ≫ f ∣_ Y.basic_open r).op) ↔ P (localization.away_map (Scheme.Γ.map (X.of_restrict U.open_embedding ≫ f).op) r) := begin subst e, convert (hP.is_localization_away_iff _ _ _ _).symm, rotate, { apply_instance }, { apply ring_hom.to_algebra, refine X.presheaf.map (@hom_of_le _ _ ((is_open_map.functor _).obj _) ((is_open_map.functor _).obj _) _).op, rw [opens.le_def], dsimp, change coe '' (coe '' set.univ) ⊆ coe '' set.univ, rw [subtype.coe_image_univ, subtype.coe_image_univ], exact set.image_preimage_subset _ _ }, { exact algebraic_geometry.Γ_restrict_is_localization Y r }, { rw ← U.open_embedding_obj_top at hU, dsimp [Scheme.Γ_obj_op, Scheme.Γ_map_op, Scheme.restrict], apply algebraic_geometry.is_localization_of_eq_basic_open _ hU, rw [opens.open_embedding_obj_top, opens.functor_obj_map_obj], convert (X.basic_open_res (Scheme.Γ.map f.op r) (hom_of_le le_top).op).symm using 1, rw [opens.open_embedding_obj_top, opens.open_embedding_obj_top, inf_comm, Scheme.Γ_map_op, ← Scheme.preimage_basic_open], refl }, { apply is_localization.ring_hom_ext (submonoid.powers r) _, swap, { exact algebraic_geometry.Γ_restrict_is_localization Y r }, rw [is_localization.away.map, is_localization.map_comp, ring_hom.algebra_map_to_algebra, ring_hom.algebra_map_to_algebra, op_comp, functor.map_comp, op_comp, functor.map_comp], refine (@category.assoc CommRing _ _ _ _ _ _ _ _).symm.trans _, refine eq.trans _ (@category.assoc CommRing _ _ _ _ _ _ _ _), dsimp only [Scheme.Γ_map, quiver.hom.unop_op], rw [morphism_restrict_c_app, category.assoc, category.assoc, category.assoc], erw [f.1.c.naturality_assoc, ← X.presheaf.map_comp, ← X.presheaf.map_comp, ← X.presheaf.map_comp], congr }, end lemma stable_under_base_change.Γ_pullback_fst (hP : stable_under_base_change @P) (hP' : respects_iso @P) {X Y S : Scheme} [is_affine X] [is_affine Y] [is_affine S] (f : X ⟶ S) (g : Y ⟶ S) (H : P (Scheme.Γ.map g.op)) : P (Scheme.Γ.map (pullback.fst : pullback f g ⟶ _).op) := begin rw [← preserves_pullback.iso_inv_fst AffineScheme.forget_to_Scheme (AffineScheme.of_hom f) (AffineScheme.of_hom g), op_comp, functor.map_comp, hP'.cancel_right_is_iso, AffineScheme.forget_to_Scheme_map], have := _root_.congr_arg quiver.hom.unop (preserves_pullback.iso_hom_fst AffineScheme.Γ.right_op (AffineScheme.of_hom f) (AffineScheme.of_hom g)), simp only [quiver.hom.unop_op, functor.right_op_map, unop_comp] at this, delta AffineScheme.Γ at this, simp only [quiver.hom.unop_op, functor.comp_map, AffineScheme.forget_to_Scheme_map, functor.op_map] at this, rw [← this, hP'.cancel_right_is_iso, ← pushout_iso_unop_pullback_inl_hom (quiver.hom.unop _) (quiver.hom.unop _), hP'.cancel_right_is_iso], exact hP.pushout_inl _ hP' _ _ H end end ring_hom namespace algebraic_geometry /-- For `P` a property of ring homomorphisms, `source_affine_locally P` holds for `f : X ⟶ Y` whenever `P` holds for the restriction of `f` on every affine open subset of `X`. -/ def source_affine_locally : affine_target_morphism_property := λ X Y f hY, ∀ (U : X.affine_opens), P (Scheme.Γ.map (X.of_restrict U.1.open_embedding ≫ f).op) /-- For `P` a property of ring homomorphisms, `affine_locally P` holds for `f : X ⟶ Y` if for each affine open `U = Spec A ⊆ Y` and `V = Spec B ⊆ f ⁻¹' U`, the ring hom `A ⟶ B` satisfies `P`. Also see `affine_locally_iff_affine_opens_le`. -/ abbreviation affine_locally : morphism_property Scheme := target_affine_locally (source_affine_locally @P) variable {P} lemma source_affine_locally_respects_iso (h₁ : ring_hom.respects_iso @P) : (source_affine_locally @P).to_property.respects_iso := begin apply affine_target_morphism_property.respects_iso_mk, { introv H U, rw [← h₁.cancel_right_is_iso _ (Scheme.Γ.map (Scheme.restrict_map_iso e.inv U.1).hom.op), ← functor.map_comp, ← op_comp], convert H ⟨_, U.prop.map_is_iso e.inv⟩ using 3, rw [is_open_immersion.iso_of_range_eq_hom, is_open_immersion.lift_fac_assoc, category.assoc, e.inv_hom_id_assoc], refl }, { introv H U, rw [← category.assoc, op_comp, functor.map_comp, h₁.cancel_left_is_iso], exact H U } end lemma affine_locally_respects_iso (h : ring_hom.respects_iso @P) : (affine_locally @P).respects_iso := target_affine_locally_respects_iso (source_affine_locally_respects_iso h) lemma affine_locally_iff_affine_opens_le (hP : ring_hom.respects_iso @P) {X Y : Scheme} (f : X ⟶ Y) : affine_locally @P f ↔ (∀ (U : Y.affine_opens) (V : X.affine_opens) (e : V.1 ≤ (opens.map f.1.base).obj U.1), P (f.1.c.app (op U) ≫ X.presheaf.map (hom_of_le e).op)) := begin apply forall_congr, intro U, delta source_affine_locally, simp_rw [op_comp, Scheme.Γ.map_comp, Γ_map_morphism_restrict, category.assoc, Scheme.Γ_map_op, hP.cancel_left_is_iso], split, { intros H V e, let U' := (opens.map f.val.base).obj U.1, have e' : U'.open_embedding.is_open_map.functor.obj ((opens.map U'.inclusion).obj V.1) = V.1, { ext1, refine set.image_preimage_eq_inter_range.trans (set.inter_eq_left_iff_subset.mpr _), convert e, exact subtype.range_coe }, have := H ⟨(opens.map (X.of_restrict (U'.open_embedding)).1.base).obj V.1, _⟩, erw ← X.presheaf.map_comp at this, rw [← hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc, ← X.presheaf.map_comp], convert this using 1, { dsimp only [functor.op, unop_op], rw opens.open_embedding_obj_top, congr' 1, exact e'.symm }, { apply_instance }, { apply (is_affine_open_iff_of_is_open_immersion (X.of_restrict _) _).mp, convert V.2, apply_instance } }, { intros H V, specialize H ⟨_, V.2.image_is_open_immersion (X.of_restrict _)⟩ (subtype.coe_image_subset _ _), erw ← X.presheaf.map_comp, rw [← hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc, ← X.presheaf.map_comp], convert H, { dsimp only [functor.op, unop_op], rw opens.open_embedding_obj_top, refl }, { apply_instance } } end lemma Scheme_restrict_basic_open_of_localization_preserves (h₁ : ring_hom.respects_iso @P) (h₂ : ring_hom.localization_preserves @P) {X Y : Scheme} [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (op ⊤)) (H : source_affine_locally @P f) (U : (X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).affine_opens) : P (Scheme.Γ.map ((X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).of_restrict U.1.open_embedding ≫ f ∣_ Y.basic_open r).op) := begin specialize H ⟨_, U.2.image_is_open_immersion (X.of_restrict _)⟩, convert (h₁.of_restrict_morphism_restrict_iff _ _ _ _ _).mpr _ using 1, swap 5, { exact h₂.away r H }, { apply_instance }, { exact U.2.image_is_open_immersion _}, { ext1, exact (set.preimage_image_eq _ subtype.coe_injective).symm } end lemma source_affine_locally_is_local (h₁ : ring_hom.respects_iso @P) (h₂ : ring_hom.localization_preserves @P) (h₃ : ring_hom.of_localization_span @P) : (source_affine_locally @P).is_local := begin constructor, { exact source_affine_locally_respects_iso h₁ }, { introv H U, apply Scheme_restrict_basic_open_of_localization_preserves h₁ h₂; assumption }, { introv hs hs' U, resetI, apply h₃ _ _ hs, intro r, have := hs' r ⟨(opens.map (X.of_restrict _).1.base).obj U.1, _⟩, rwa h₁.of_restrict_morphism_restrict_iff at this, { exact U.2 }, { refl }, { apply_instance }, { suffices : ∀ (V = (opens.map f.val.base).obj (Y.basic_open r.val)), is_affine_open ((opens.map (X.of_restrict V.open_embedding).1.base).obj U.1), { exact this _ rfl, }, intros V hV, rw Scheme.preimage_basic_open at hV, subst hV, exact U.2.map_restrict_basic_open (Scheme.Γ.map f.op r.1) } } end variables {P} (hP : ring_hom.property_is_local @P) lemma source_affine_locally_of_source_open_cover_aux (h₁ : ring_hom.respects_iso @P) (h₃ : ring_hom.of_localization_span_target @P) {X Y : Scheme} (f : X ⟶ Y) (U : X.affine_opens) (s : set (X.presheaf.obj (op U.1))) (hs : ideal.span s = ⊤) (hs' : ∀ (r : s), P (Scheme.Γ.map (X.of_restrict (X.basic_open r.1).open_embedding ≫ f).op)) : P (Scheme.Γ.map (X.of_restrict U.1.open_embedding ≫ f).op) := begin apply_fun ideal.map (X.presheaf.map (eq_to_hom U.1.open_embedding_obj_top).op) at hs, rw [ideal.map_span, ideal.map_top] at hs, apply h₃ _ _ hs, rintro ⟨s, r, hr, hs⟩, have := (@@localization.alg_equiv _ _ _ _ _ (@@algebraic_geometry.Γ_restrict_is_localization _ U.2 s)).to_ring_equiv.to_CommRing_iso, refine (h₁.cancel_right_is_iso _ (@@localization.alg_equiv _ _ _ _ _ (@@algebraic_geometry.Γ_restrict_is_localization _ U.2 s)) .to_ring_equiv.to_CommRing_iso.hom).mp _, subst hs, rw [CommRing.comp_eq_ring_hom_comp, ← ring_hom.comp_assoc], erw [is_localization.map_comp, ring_hom.comp_id], rw [ring_hom.algebra_map_to_algebra, op_comp, functor.map_comp, ← CommRing.comp_eq_ring_hom_comp, Scheme.Γ_map_op, Scheme.Γ_map_op, Scheme.Γ_map_op, category.assoc], erw ← X.presheaf.map_comp, rw [← h₁.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _))], convert hs' ⟨r, hr⟩ using 1, { erw category.assoc, rw [← X.presheaf.map_comp, op_comp, Scheme.Γ.map_comp, Scheme.Γ_map_op, Scheme.Γ_map_op], congr }, { dsimp [functor.op], conv_lhs { rw opens.open_embedding_obj_top }, conv_rhs { rw opens.open_embedding_obj_top }, erw is_open_immersion.image_basic_open (X.of_restrict U.1.open_embedding), erw PresheafedSpace.is_open_immersion.of_restrict_inv_app_apply, rw Scheme.basic_open_res_eq }, { apply_instance } end lemma is_open_immersion_comp_of_source_affine_locally (h₁ : ring_hom.respects_iso @P) {X Y Z : Scheme} [is_affine X] [is_affine Z] (f : X ⟶ Y) [is_open_immersion f] (g : Y ⟶ Z) (h₂ : source_affine_locally @P g) : P (Scheme.Γ.map (f ≫ g).op) := begin rw [← h₁.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq (Y.of_restrict _) f _).hom.op), ← functor.map_comp, ← op_comp], convert h₂ ⟨_, range_is_affine_open_of_open_immersion f⟩ using 3, { rw [is_open_immersion.iso_of_range_eq_hom, is_open_immersion.lift_fac_assoc] }, { apply_instance }, { exact subtype.range_coe }, { apply_instance } end end algebraic_geometry open algebraic_geometry namespace ring_hom.property_is_local variables {P} (hP : ring_hom.property_is_local @P) include hP lemma source_affine_locally_of_source_open_cover {X Y : Scheme} (f : X ⟶ Y) [is_affine Y] (𝒰 : X.open_cover) [∀ i, is_affine (𝒰.obj i)] (H : ∀ i, P (Scheme.Γ.map (𝒰.map i ≫ f).op)) : source_affine_locally @P f := begin let S := λ i, (⟨⟨set.range (𝒰.map i).1.base, (𝒰.is_open i).base_open.open_range⟩, range_is_affine_open_of_open_immersion (𝒰.map i)⟩ : X.affine_opens), intros U, apply of_affine_open_cover U, swap 5, { exact set.range S }, { intros U r H, convert hP.stable_under_composition _ _ H _ using 1, swap, { refine X.presheaf.map (@hom_of_le _ _ ((is_open_map.functor _).obj _) ((is_open_map.functor _).obj _) _).op, rw [unop_op, unop_op, opens.open_embedding_obj_top, opens.open_embedding_obj_top], exact X.basic_open_subset _ }, { rw [op_comp, op_comp, functor.map_comp, functor.map_comp], refine (eq.trans _ (category.assoc _ _ _).symm : _), congr' 1, refine eq.trans _ (X.presheaf.map_comp _ _), change X.presheaf.map _ = _, congr }, convert hP.holds_for_localization_away _ (X.presheaf.map (eq_to_hom U.1.open_embedding_obj_top).op r), { exact (ring_hom.algebra_map_to_algebra _).symm }, { dsimp [Scheme.Γ], have := U.2, rw ← U.1.open_embedding_obj_top at this, convert is_localization_basic_open this _ using 6; rw opens.open_embedding_obj_top; exact (Scheme.basic_open_res_eq _ _ _).symm } }, { introv hs hs', exact source_affine_locally_of_source_open_cover_aux hP.respects_iso hP.2 _ _ _ hs hs' }, { rw set.eq_univ_iff_forall, intro x, rw set.mem_Union, exact ⟨⟨_, 𝒰.f x, rfl⟩, 𝒰.covers x⟩ }, { rintro ⟨_, i, rfl⟩, specialize H i, rw ← hP.respects_iso.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq (𝒰.map i) (X.of_restrict (S i).1.open_embedding) subtype.range_coe.symm).inv.op) at H, rwa [← Scheme.Γ.map_comp, ← op_comp, is_open_immersion.iso_of_range_eq_inv, is_open_immersion.lift_fac_assoc] at H } end lemma affine_open_cover_tfae {X Y : Scheme.{u}} [is_affine Y] (f : X ⟶ Y) : tfae [source_affine_locally @P f, ∃ (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)], ∀ (i : 𝒰.J), P (Scheme.Γ.map (𝒰.map i ≫ f).op), ∀ (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J), P (Scheme.Γ.map (𝒰.map i ≫ f).op), ∀ {U : Scheme} (g : U ⟶ X) [is_affine U] [is_open_immersion g], P (Scheme.Γ.map (g ≫ f).op)] := begin tfae_have : 1 → 4, { intros H U g _ hg, resetI, specialize H ⟨⟨_, hg.base_open.open_range⟩, range_is_affine_open_of_open_immersion g⟩, rw [← hP.respects_iso.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq g (X.of_restrict (opens.open_embedding ⟨_, hg.base_open.open_range⟩)) subtype.range_coe.symm).hom.op), ← Scheme.Γ.map_comp, ← op_comp, is_open_immersion.iso_of_range_eq_hom] at H, erw is_open_immersion.lift_fac_assoc at H, exact H }, tfae_have : 4 → 3, { intros H 𝒰 _ i, resetI, apply H }, tfae_have : 3 → 2, { intro H, refine ⟨X.affine_cover, infer_instance, H _⟩ }, tfae_have : 2 → 1, { rintro ⟨𝒰, _, h𝒰⟩, exactI hP.source_affine_locally_of_source_open_cover f 𝒰 h𝒰 }, tfae_finish end lemma open_cover_tfae {X Y : Scheme.{u}} [is_affine Y] (f : X ⟶ Y) : tfae [source_affine_locally @P f, ∃ (𝒰 : Scheme.open_cover.{u} X), ∀ (i : 𝒰.J), source_affine_locally @P (𝒰.map i ≫ f), ∀ (𝒰 : Scheme.open_cover.{u} X) (i : 𝒰.J), source_affine_locally @P (𝒰.map i ≫ f), ∀ {U : Scheme} (g : U ⟶ X) [is_open_immersion g], source_affine_locally @P (g ≫ f)] := begin tfae_have : 1 → 4, { intros H U g hg V, resetI, rw (hP.affine_open_cover_tfae f).out 0 3 at H, haveI : is_affine _ := V.2, rw ← category.assoc, apply H }, tfae_have : 4 → 3, { intros H 𝒰 _ i, resetI, apply H }, tfae_have : 3 → 2, { intro H, refine ⟨X.affine_cover, H _⟩ }, tfae_have : 2 → 1, { rintro ⟨𝒰, h𝒰⟩, rw (hP.affine_open_cover_tfae f).out 0 1, refine ⟨𝒰.bind (λ _, Scheme.affine_cover _), _, _⟩, { intro i, dsimp, apply_instance }, { intro i, specialize h𝒰 i.1, rw (hP.affine_open_cover_tfae (𝒰.map i.fst ≫ f)).out 0 3 at h𝒰, erw category.assoc, apply @@h𝒰 _ (show _, from _), dsimp, apply_instance } }, tfae_finish end lemma source_affine_locally_comp_of_is_open_immersion {X Y Z : Scheme.{u}} [is_affine Z] (f : X ⟶ Y) (g : Y ⟶ Z) [is_open_immersion f] (H : source_affine_locally @P g) : source_affine_locally @P (f ≫ g) := by apply ((hP.open_cover_tfae g).out 0 3).mp H lemma source_affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y) [is_affine Y] (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)] : source_affine_locally @P f ↔ (∀ i, P (Scheme.Γ.map (𝒰.map i ≫ f).op)) := ⟨λ H, let h := ((hP.affine_open_cover_tfae f).out 0 2).mp H in h 𝒰, λ H, let h := ((hP.affine_open_cover_tfae f).out 1 0).mp in h ⟨𝒰, infer_instance, H⟩⟩ lemma is_local_source_affine_locally : (source_affine_locally @P).is_local := source_affine_locally_is_local hP.respects_iso hP.localization_preserves (@ring_hom.property_is_local.of_localization_span _ hP) lemma is_local_affine_locally : property_is_local_at_target (affine_locally @P) := hP.is_local_source_affine_locally.target_affine_locally_is_local lemma affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y) (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (𝒰' : ∀ i, Scheme.open_cover.{u} ((𝒰.pullback_cover f).obj i)) [∀ i j, is_affine ((𝒰' i).obj j)] : affine_locally @P f ↔ (∀ i j, P (Scheme.Γ.map ((𝒰' i).map j ≫ pullback.snd).op)) := (hP.is_local_source_affine_locally.affine_open_cover_iff f 𝒰).trans (forall_congr (λ i, hP.source_affine_open_cover_iff _ (𝒰' i))) lemma source_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y) (𝒰 : Scheme.open_cover.{u} X) : affine_locally @P f ↔ ∀ i, affine_locally @P (𝒰.map i ≫ f) := begin split, { intros H i U, rw morphism_restrict_comp, delta morphism_restrict, apply hP.source_affine_locally_comp_of_is_open_immersion, apply H }, { intros H U, haveI : is_affine _ := U.2, apply ((hP.open_cover_tfae (f ∣_ U.1)).out 1 0).mp, use 𝒰.pullback_cover (X.of_restrict _), intro i, specialize H i U, rw morphism_restrict_comp at H, delta morphism_restrict at H, have := source_affine_locally_respects_iso hP.respects_iso, rw [category.assoc, affine_cancel_left_is_iso this, ← affine_cancel_left_is_iso this (pullback_symmetry _ _).hom, pullback_symmetry_hom_comp_snd_assoc] at H, exact H } end lemma affine_locally_of_is_open_immersion (hP : ring_hom.property_is_local @P) {X Y : Scheme} (f : X ⟶ Y) [hf : is_open_immersion f] : affine_locally @P f := begin intro U, haveI H : is_affine _ := U.2, rw ← category.comp_id (f ∣_ U), apply hP.source_affine_locally_comp_of_is_open_immersion, rw hP.source_affine_open_cover_iff _ (Scheme.open_cover_of_is_iso (𝟙 _)), { intro i, erw [category.id_comp, op_id, Scheme.Γ.map_id], convert hP.holds_for_localization_away _ (1 : Scheme.Γ.obj _), { exact (ring_hom.algebra_map_to_algebra _).symm }, { apply_instance }, { refine is_localization.away_of_is_unit_of_bijective _ is_unit_one function.bijective_id } }, { intro i, exact H } end lemma affine_locally_stable_under_composition : (affine_locally @P).stable_under_composition := begin intros X Y S f g hf hg, let 𝒰 : ∀ i, ((S.affine_cover.pullback_cover (f ≫ g)).obj i).open_cover, { intro i, refine Scheme.open_cover.bind _ (λ i, Scheme.affine_cover _), apply Scheme.open_cover.pushforward_iso _ (pullback_right_pullback_fst_iso g (S.affine_cover.map i) f).hom, apply Scheme.pullback.open_cover_of_right, exact (pullback g (S.affine_cover.map i)).affine_cover }, rw hP.affine_open_cover_iff (f ≫ g) S.affine_cover _, rotate, { exact 𝒰 }, { intros i j, dsimp at *, apply_instance }, { rintros i ⟨j, k⟩, dsimp at i j k, dsimp only [Scheme.open_cover.bind_map, Scheme.open_cover.pushforward_iso_obj, Scheme.pullback.open_cover_of_right_obj, Scheme.open_cover.pushforward_iso_map, Scheme.pullback.open_cover_of_right_map, Scheme.open_cover.bind_obj], rw [category.assoc, category.assoc, pullback_right_pullback_fst_iso_hom_snd, pullback.lift_snd_assoc, category.assoc, ← category.assoc, op_comp, functor.map_comp], apply hP.stable_under_composition, { exact (hP.affine_open_cover_iff _ _ _).mp hg _ _ }, { delta affine_locally at hf, rw (hP.is_local_source_affine_locally.affine_open_cover_tfae f).out 0 3 at hf, specialize hf ((pullback g (S.affine_cover.map i)).affine_cover.map j ≫ pullback.fst), rw (hP.affine_open_cover_tfae (pullback.snd : pullback f ((pullback g (S.affine_cover.map i)) .affine_cover.map j ≫ pullback.fst) ⟶ _)).out 0 3 at hf, apply hf } } end end ring_hom.property_is_local
dc621f853d132f361b8d607bb4184b896c4d2155
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/field.lean
3580233ae937d41090a70a3f680042cc7631e0c8
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,079
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring.basic import algebra.group_with_zero /-! # Fields and division rings This file introduces fields and division rings (also known as skewfields) and proves some basic statements about them. For a more extensive theory of fields, see the `field_theory` folder. ## Main definitions * `division_ring`: introduces the notion of a division ring as a `ring` such that `0 ≠ 1` and `a * a⁻¹ = 1` for `a ≠ 0` * `field`: a division ring which is also a commutative ring. * `is_field`: a predicate on a ring that it is a field, i.e. that the multiplication is commutative, that it has more than one element and that all non-zero elements have a multiplicative inverse. In contrast to `field`, which contains the data of a function associating to an element of the field its multiplicative inverse, this predicate only assumes the existence and can therefore more easily be used to e.g. transfer along ring isomorphisms. ## Implementation details By convention `0⁻¹ = 0` in a field or division ring. This is due to the fact that working with total functions has the advantage of not constantly having to check that `x ≠ 0` when writing `x⁻¹`. With this convention in place, some statements like `(a + b) * c⁻¹ = a * c⁻¹ + b * c⁻¹` still remain true, while others like the defining property `a * a⁻¹ = 1` need the assumption `a ≠ 0`. If you are a beginner in using Lean and are confused by that, you can read more about why this convention is taken in Kevin Buzzard's [blogpost](https://xenaproject.wordpress.com/2020/07/05/division-by-zero-in-type-theory-a-faq/) A division ring or field is an example of a `group_with_zero`. If you cannot find a division ring / field lemma that does not involve `+`, you can try looking for a `group_with_zero` lemma instead. ## Tags field, division ring, skew field, skew-field, skewfield -/ open set set_option old_structure_cmd true universe u variables {K : Type u} /-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor ring div_inv_monoid nontrivial] class division_ring (K : Type u) extends ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) section division_ring variables [division_ring K] {a b : K} /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero K := { .. ‹division_ring K›, .. (infer_instance : semiring K) } lemma inverse_eq_has_inv : (ring.inverse : K → K) = has_inv.inv := begin ext x, by_cases hx : x = 0, { simp [hx] }, { exact ring.inverse_unit (units.mk0 x hx) } end attribute [field_simps] inv_eq_one_div local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma one_div_neg_one_eq_neg_one : (1:K) / (-1) = -1 := have (-1) * (-1) = (1:K), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : K) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : K) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b / a) : by rw mul_one_div lemma neg_div (a b : K) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' (a b : K) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : K) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] @[field_simps] lemma div_add_div_same (a b c : K) : a / c + b / c = (a + b) / c := by simpa only [div_eq_mul_inv] using (right_distrib a b (c⁻¹)).symm lemma same_add_div {a b : K} (h : b ≠ 0) : (b + a) / b = 1 + a / b := by simpa only [← @div_self _ _ b h] using (div_add_div_same b a b).symm lemma one_add_div {a b : K} (h : b ≠ 0 ) : 1 + a / b = (b + a) / b := (same_add_div h).symm lemma div_add_same {a b : K} (h : b ≠ 0) : (a + b) / b = a / b + 1 := by simpa only [← @div_self _ _ b h] using (div_add_div_same a b b).symm lemma div_add_one {a b : K} (h : b ≠ 0) : a / b + 1 = (a + b) / b := (div_add_same h).symm lemma div_sub_div_same (a b c : K) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma same_sub_div {a b : K} (h : b ≠ 0) : (b - a) / b = 1 - a / b := by simpa only [← @div_self _ _ b h] using (div_sub_div_same b a b).symm lemma one_sub_div {a b : K} (h : b ≠ 0) : 1 - a / b = (b - a) / b := (same_sub_div h).symm lemma div_sub_same {a b : K} (h : b ≠ 0) : (a - b) / b = a / b - 1 := by simpa only [← @div_self _ _ b h] using (div_sub_div_same a b b).symm lemma div_sub_one {a b : K} (h : b ≠ 0) : a / b - 1 = (a - b) / b := (div_sub_same h).symm lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : K) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : K) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma div_neg (a : K) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma add_div_eq_mul_add_div (a b : K) {c : K} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] @[priority 100] -- see Note [lower instance priority] instance division_ring.to_domain : domain K := { ..‹division_ring K›, ..(by apply_instance : semiring K), ..(by apply_instance : no_zero_divisors K) } end division_ring /-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor comm_ring div_inv_monoid nontrivial] class field (K : Type u) extends comm_ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) section field variable [field K] @[priority 100] -- see Note [lower instance priority] instance field.to_division_ring : division_ring K := { ..show field K, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance field.to_comm_group_with_zero : comm_group_with_zero K := { .. (_ : group_with_zero K), .. ‹field K› } local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] lemma one_div_add_one_div {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [div_add_div _ _ ha hb, one_mul, mul_one, add_comm] @[field_simps] lemma div_sub_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp only [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : K) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : K) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : K) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : K) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain : integral_domain K := { ..‹field K›, ..division_ring.to_domain } end field section is_field /-- A predicate to express that a ring is a field. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. Additionaly, this is useful when trying to prove that a particular ring structure extends to a field. -/ structure is_field (R : Type u) [ring R] : Prop := (exists_pair_ne : ∃ (x y : R), x ≠ y) (mul_comm : ∀ (x y : R), x * y = y * x) (mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1) /-- Transferring from field to is_field -/ lemma field.to_is_field (R : Type u) [field R] : is_field R := { mul_inv_cancel := λ a ha, ⟨a⁻¹, field.mul_inv_cancel ha⟩, ..‹field R› } open_locale classical /-- Transferring from is_field to field -/ noncomputable def is_field.to_field (R : Type u) [ring R] (h : is_field R) : field R := { inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha), inv_zero := dif_pos rfl, mul_inv_cancel := λ a ha, begin convert classical.some_spec (is_field.mul_inv_cancel h ha), exact dif_neg ha end, .. ‹ring R›, ..h } /-- For each field, and for each nonzero element of said field, there is a unique inverse. Since `is_field` doesn't remember the data of an `inv` function and as such, a lemma that there is a unique inverse could be useful. -/ lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) : ∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 := begin intros x hx, apply exists_unique_of_exists_of_unique, { exact hf.mul_inv_cancel hx }, { intros y z hxy hxz, calc y = y * (x * z) : by rw [hxz, mul_one] ... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x] ... = z : by rw [hxy, one_mul] } end end is_field namespace ring_hom section variables {R : Type*} [semiring R] [division_ring K] (f : R →+* K) @[simp] lemma map_units_inv (u : units R) : f ↑u⁻¹ = (f ↑u)⁻¹ := (f : R →* K).map_units_inv u end section variables {R K' : Type*} [division_ring K] [semiring R] [nontrivial R] [division_ring K'] (f : K →+* R) (g : K →+* K') {x y : K} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := f.to_monoid_with_zero_hom.map_ne_zero @[simp] lemma map_eq_zero : f x = 0 ↔ x = 0 := f.to_monoid_with_zero_hom.map_eq_zero variables (x y) lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_monoid_with_zero_hom.map_inv x lemma map_div : g (x / y) = g x / g y := g.to_monoid_with_zero_hom.map_div x y protected lemma injective : function.injective f := f.injective_iff.2 $ λ x, f.map_eq_zero.1 end end ring_hom section noncomputable_defs variables {R : Type*} [nontrivial R] /-- Constructs a `division_ring` structure on a `ring` consisting only of units and 0. -/ noncomputable def division_ring_of_is_unit_or_eq_zero [hR : ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : division_ring R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } /-- Constructs a `field` structure on a `comm_ring` consisting only of units and 0. -/ noncomputable def field_of_is_unit_or_eq_zero [hR : comm_ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : field R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } end noncomputable_defs /-- Pullback a `division_ring` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.division_ring [division_ring K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] (f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : division_ring K' := { .. hf.group_with_zero f zero one mul inv div, .. hf.ring f zero one add mul neg sub } /-- Pullback a `field` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.field [field K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] (f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : field K' := { .. hf.comm_group_with_zero f zero one mul inv div, .. hf.comm_ring f zero one add mul neg sub }
835f5eb3908278815bbaf7d4863380057f63d1f3
c09f5945267fd905e23a77be83d9a78580e04a4a
/src/topology/uniform_space/uniform_embedding.lean
0aeafeb6bd5d430b8e3543944532e2ee6a91acf8
[ "Apache-2.0" ]
permissive
OHIHIYA20/mathlib
023a6df35355b5b6eb931c404f7dd7535dccfa89
1ec0a1f49db97d45e8666a3bf33217ff79ca1d87
refs/heads/master
1,587,964,529,965
1,551,819,319,000
1,551,819,319,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,373
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, Sébastien Gouëzel Uniform embeddings of uniform spaces. Extension of uniform continuous functions. -/ import topology.uniform_space.cauchy open filter topological_space lattice set classical local attribute [instance, priority 0] prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] universe u def uniform_embedding [uniform_space β] (f : α → β) := function.injective f ∧ comap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity theorem uniform_embedding_def [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ (@uniformity α _).sets ↔ ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by rw [uniform_embedding, eq_comm, filter.ext_iff]; simp [subset_def] theorem uniform_embedding_def' [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ (@uniformity α _).sets → ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_embedding.uniform_continuous [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := (uniform_embedding_def'.1 hf).2.1 lemma uniform_embedding.uniform_continuous_iff [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_embedding g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by simp [uniform_continuous, tendsto]; rw [← hg.2, ← map_le_iff_le_comap, filter.map_map] lemma uniform_embedding.embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) : embedding f := begin refine ⟨h.left, eq_of_nhds_eq_nhds $ assume a, _⟩, rw [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity, ← h.right, comap_lift'_eq, comap_lift'_eq2]; { refl <|> exact monotone_preimage } end lemma uniform_embedding.dense_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (range f)) : dense_embedding f := { dense := hd, inj := h.left, induced := assume a, by rw [h.embedding.2, nhds_induced_eq_comap] } lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (comap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (comap e $ nhds b).sets, from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (comap e $ nhds b').sets, from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).sets_of_superset (mem_nhds_left b htu) this⟩ lemma uniform_embedding_comap {f : α → β} [u : uniform_space β] (hf : function.injective f) : @uniform_embedding α β (uniform_space.comap f u) u f := ⟨hf, rfl⟩ lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by simp [prod.mk.inj_iff]; exact assume eq₁ eq₂, ⟨h₁.left eq₁, h₂.left eq₂⟩, by simp [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, comap_inf, comap_comap_comp]⟩ /-- A set is complete iff its image under a uniform embedding is complete. -/ lemma is_complete_image_iff [uniform_space β] {m : α → β} {s : set α} (hm : uniform_embedding m) : is_complete (m '' s) ↔ is_complete s := begin refine ⟨λ c f hf fs, _, λ c f hf fs, _⟩, { let f' := map m f, have cf' : cauchy f' := cauchy_map (uniform_embedding.uniform_continuous hm) hf, have f's : f' ≤ principal (m '' s), { simp only [filter.le_principal_iff, set.mem_image, filter.mem_map], exact mem_sets_of_superset (filter.le_principal_iff.1 fs) (λx hx, ⟨x, hx, rfl⟩) }, rcases c f' cf' f's with ⟨y, yms, hy⟩, rcases mem_image_iff_bex.1 yms with ⟨x, xs, rfl⟩, rw [map_le_iff_le_comap, ← nhds_induced_eq_comap, ← (uniform_embedding.embedding hm).2] at hy, exact ⟨x, xs, hy⟩ }, { rw filter.le_principal_iff at fs, let f' := comap m f, have cf' : cauchy f', { have : comap m f ≠ ⊥, { refine comap_neq_bot (λt ht, _), have A : t ∩ m '' s ∈ f.sets := filter.inter_mem_sets ht fs, have : t ∩ m '' s ≠ ∅, { by_contradiction h, simp only [not_not, ne.def] at h, simpa [h, empty_in_sets_eq_bot, hf.1] using A }, rcases ne_empty_iff_exists_mem.1 this with ⟨x, ⟨xt, xms⟩⟩, rcases mem_image_iff_bex.1 xms with ⟨y, ys, yx⟩, rw ← yx at xt, exact ⟨y, xt⟩ }, apply cauchy_comap _ hf this, simp only [hm.2, le_refl] }, have : f' ≤ principal s := by simp [f']; exact ⟨m '' s, by simpa using fs, by simp [preimage_image_eq s hm.1]⟩, rcases c f' cf' this with ⟨x, xs, hx⟩, existsi [m x, mem_image_of_mem m xs], rw [(uniform_embedding.embedding hm).2, nhds_induced_eq_comap] at hx, calc f = map m f' : (map_comap $ filter.mem_sets_of_superset fs $ image_subset_range _ _).symm ... ≤ map m (comap m (nhds (m x))) : map_mono hx ... ≤ nhds (m x) : map_comap_le } end lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (range m)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have comap m g ≠ ⊥, from comap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (range m) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ (nhds x ⊓ principal (range m)).sets, from @inter_mem_sets α (nhds x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from cauchy_comap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.comap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.comap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ lemma totally_bounded_preimage [uniform_space α] [uniform_space β] {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.2 at ht, rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage hf.1 hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (range e)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_embedding h_dense).extend f lemma uniformly_extend_of_emb (b : β) : ψ (e b) = f b := dense_embedding.extend_e_eq _ b lemma uniformly_extend_exists [complete_space γ] (a : α) : ∃c, tendsto f (comap e (nhds a)) (nhds c) := let de := (h_e.dense_embedding h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (comap e (nhds a)), from cauchy_comap (le_of_eq h_e.right) this de.comap_nhds_neq_bot, have cauchy (map f (comap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] (h_f : uniform_continuous f) (a : α) : tendsto f (comap e (nhds a)) (nhds (ψ a)) := let de := (h_e.dense_embedding h_dense) in begin by_cases ha : a ∈ range e, { rcases ha with ⟨b, rfl⟩, rw [uniformly_extend_of_emb, de.induced], exact h_f.continuous.tendsto _ }, { simp only [dense_embedding.extend, dif_neg ha], exact (@lim_spec _ _ (id _) _ $ uniformly_extend_exists h_e h_dense h_f _) } end lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (comap e (nhds a)) ≠ ⊥, from map_ne_bot (h_e.dense_embedding h_dense).comap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (comap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f _ (inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs))), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (comap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (nhds b)) (nhds c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf _ in begin rw [nhds_subtype_eq_comap] at hc, simp [comap_comap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←comap_comap_comp, tendsto_comap'_iff] at hc, exact ⟨c, hc⟩, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ range subtype.val, rw [←closure_induced, closure_eq_nhds, mem_set_of_eq, (≠), nhds_induced_eq_comap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ range subtype.val, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact assume hxs, ⟨⟨x, hp x hxs⟩, rfl⟩, exact de.inj end⟩ end end uniform_extension
9b63cd5b9a26ee984b8f1215b4f82ab346db40d7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/ring/inj_surj.lean
9a67f6e8b1ee55a94457e26989559167fddb4614
[ "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
22,031
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland -/ import algebra.ring.defs import algebra.opposites import algebra.group_with_zero.inj_surj /-! # Pulling back rings along injective maps, and pushing them forward along surjective maps. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} open function /-! ### `distrib` class -/ /-- Pullback a `distrib` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } section injective_surjective_maps /-! ### Semirings -/ variables [has_zero β] [has_add β] [has_mul β] [has_smul ℕ β] /-- Pullback a `non_unital_non_assoc_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_non_assoc_semiring {α : Type u} [non_unital_non_assoc_semiring α] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) : non_unital_non_assoc_semiring β := { .. hf.mul_zero_class f zero mul, .. hf.add_comm_monoid f zero add nsmul, .. hf.distrib f add mul } /-- Pullback a `non_unital_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_semiring {α : Type u} [non_unital_semiring α] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) : non_unital_semiring β := { .. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.semigroup_with_zero f zero mul } /-- Pullback a `non_assoc_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_assoc_semiring {α : Type u} [non_assoc_semiring α] {β : Type v} [has_zero β] [has_one β] [has_mul β] [has_add β] [has_smul ℕ β] [has_nat_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (nat_cast : ∀ n : ℕ, f n = n) : non_assoc_semiring β := { .. hf.add_monoid_with_one f zero one add nsmul nat_cast, .. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.mul_one_class f one mul } /-- Pullback a `semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semiring {α : Type u} [semiring α] {β : Type v} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : semiring β := { .. hf.non_assoc_semiring f zero one add mul nsmul nat_cast, .. hf.monoid_with_zero f zero one mul npow, .. hf.distrib f add mul } /-- Pushforward a `non_unital_non_assoc_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_non_assoc_semiring {α : Type u} [non_unital_non_assoc_semiring α] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) : non_unital_non_assoc_semiring β := { .. hf.mul_zero_class f zero mul, .. hf.add_comm_monoid f zero add nsmul, .. hf.distrib f add mul } /-- Pushforward a `non_unital_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_semiring {α : Type u} [non_unital_semiring α] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) : non_unital_semiring β := { .. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.semigroup_with_zero f zero mul } /-- Pushforward a `non_assoc_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_assoc_semiring {α : Type u} [non_assoc_semiring α] {β : Type v} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_smul ℕ β] [has_nat_cast β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (nat_cast : ∀ n : ℕ, f n = n) : non_assoc_semiring β := { .. hf.add_monoid_with_one f zero one add nsmul nat_cast, .. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.mul_one_class f one mul } /-- Pushforward a `semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.semiring {α : Type u} [semiring α] {β : Type v} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : semiring β := { .. hf.non_assoc_semiring f zero one add mul nsmul nat_cast, .. hf.monoid_with_zero f zero one mul npow, .. hf.add_comm_monoid f zero add nsmul, .. hf.distrib f add mul } end injective_surjective_maps section non_unital_comm_semiring variables [non_unital_comm_semiring α] [non_unital_comm_semiring β] {a b c : α} /-- Pullback a `non_unital_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_comm_semiring [has_zero γ] [has_add γ] [has_mul γ] [has_smul ℕ γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) : non_unital_comm_semiring γ := { .. hf.non_unital_semiring f zero add mul nsmul, .. hf.comm_semigroup f mul } /-- Pushforward a `non_unital_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_comm_semiring [has_zero γ] [has_add γ] [has_mul γ] [has_smul ℕ γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) : non_unital_comm_semiring γ := { .. hf.non_unital_semiring f zero add mul nsmul, .. hf.comm_semigroup f mul } end non_unital_comm_semiring section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} /-- Pullback a `semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] [has_smul ℕ γ] [has_nat_cast γ] [has_pow γ ℕ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : comm_semiring γ := { .. hf.semiring f zero one add mul nsmul npow nat_cast, .. hf.comm_semigroup f mul } /-- Pushforward a `semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] [has_smul ℕ γ] [has_nat_cast γ] [has_pow γ ℕ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : comm_semiring γ := { .. hf.semiring f zero one add mul nsmul npow nat_cast, .. hf.comm_semigroup f mul } end comm_semiring section has_distrib_neg section has_mul variables [has_mul α] [has_distrib_neg α] /-- A type endowed with `-` and `*` has distributive negation, if it admits an injective map that preserves `-` and `*` to a type which has distributive negation. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.has_distrib_neg [has_neg β] [has_mul β] (f : β → α) (hf : injective f) (neg : ∀ a, f (-a) = -f a) (mul : ∀ a b, f (a * b) = f a * f b) : has_distrib_neg β := { neg_mul := λ x y, hf $ by erw [neg, mul, neg, neg_mul, mul], mul_neg := λ x y, hf $ by erw [neg, mul, neg, mul_neg, mul], ..hf.has_involutive_neg _ neg, ..‹has_mul β› } /-- A type endowed with `-` and `*` has distributive negation, if it admits a surjective map that preserves `-` and `*` from a type which has distributive negation. -/ @[reducible] -- See note [reducible non-instances] protected def function.surjective.has_distrib_neg [has_neg β] [has_mul β] (f : α → β) (hf : surjective f) (neg : ∀ a, f (-a) = -f a) (mul : ∀ a b, f (a * b) = f a * f b) : has_distrib_neg β := { neg_mul := hf.forall₂.2 $ λ x y, by { erw [←neg, ← mul, neg_mul, neg, mul], refl }, mul_neg := hf.forall₂.2 $ λ x y, by { erw [←neg, ← mul, mul_neg, neg, mul], refl }, ..hf.has_involutive_neg _ neg, ..‹has_mul β› } namespace add_opposite instance : has_distrib_neg αᵃᵒᵖ := unop_injective.has_distrib_neg _ unop_neg unop_mul end add_opposite end has_mul end has_distrib_neg /-! ### Rings -/ section non_unital_non_assoc_ring variables [non_unital_non_assoc_ring α] /-- Pullback a `non_unital_non_assoc_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_non_assoc_ring [has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) : non_unital_non_assoc_ring β := { .. hf.add_comm_group f zero add neg sub nsmul zsmul, ..hf.mul_zero_class f zero mul, .. hf.distrib f add mul } /-- Pushforward a `non_unital_non_assoc_ring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_non_assoc_ring [has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) : non_unital_non_assoc_ring β := { .. hf.add_comm_group f zero add neg sub nsmul zsmul, .. hf.mul_zero_class f zero mul, .. hf.distrib f add mul } end non_unital_non_assoc_ring section non_unital_ring variables [non_unital_ring α] /-- Pullback a `non_unital_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_ring [has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x) : non_unital_ring β := { .. hf.add_comm_group f zero add neg sub nsmul gsmul, ..hf.mul_zero_class f zero mul, .. hf.distrib f add mul, .. hf.semigroup f mul } /-- Pushforward a `non_unital_ring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_ring [has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x) : non_unital_ring β := { .. hf.add_comm_group f zero add neg sub nsmul gsmul, .. hf.mul_zero_class f zero mul, .. hf.distrib f add mul, .. hf.semigroup f mul } end non_unital_ring section non_assoc_ring variables [non_assoc_ring α] /-- Pullback a `non_assoc_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_assoc_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β] [has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : non_assoc_ring β := { .. hf.add_comm_group f zero add neg sub nsmul gsmul, .. hf.add_group_with_one f zero one add neg sub nsmul gsmul nat_cast int_cast, .. hf.mul_zero_class f zero mul, .. hf.distrib f add mul, .. hf.mul_one_class f one mul } /-- Pushforward a `non_unital_ring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_assoc_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β] [has_int_cast β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : non_assoc_ring β := { .. hf.add_comm_group f zero add neg sub nsmul gsmul, .. hf.mul_zero_class f zero mul, .. hf.add_group_with_one f zero one add neg sub nsmul gsmul nat_cast int_cast, .. hf.distrib f add mul, .. hf.mul_one_class f one mul } end non_assoc_ring section ring variables [ring α] {a b c d e : α} /-- Pullback a `ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : ring β := { .. hf.add_group_with_one f zero one add neg sub nsmul zsmul nat_cast int_cast, .. hf.add_comm_group f zero add neg sub nsmul zsmul, .. hf.monoid f one mul npow, .. hf.distrib f add mul } /-- Pushforward a `ring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : ring β := { .. hf.add_group_with_one f zero one add neg sub nsmul zsmul nat_cast int_cast, .. hf.add_comm_group f zero add neg sub nsmul zsmul, .. hf.monoid f one mul npow, .. hf.distrib f add mul } end ring section non_unital_comm_ring variables [non_unital_comm_ring α] {a b c : α} /-- Pullback a `comm_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_comm_ring [has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) : non_unital_comm_ring β := { .. hf.non_unital_ring f zero add mul neg sub nsmul zsmul, .. hf.comm_semigroup f mul } /-- Pushforward a `non_unital_comm_ring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_comm_ring [has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) : non_unital_comm_ring β := { .. hf.non_unital_ring f zero add mul neg sub nsmul zsmul, .. hf.comm_semigroup f mul } end non_unital_comm_ring section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `comm_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : comm_ring β := { .. hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast, .. hf.comm_semigroup f mul } /-- Pushforward a `comm_ring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : comm_ring β := { .. hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast, .. hf.comm_semigroup f mul } end comm_ring
b4c9e667d99f392873ad1a5847824667c7515ebc
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Server/ServerBin.lean
aa723d6c5f58eb327c602da1e64ed1f2418779c2
[ "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
420
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Init.System.IO import Lean.Server def main (n : List String) : IO UInt32 := do i ← IO.getStdin; o ← IO.getStdout; e ← IO.getStderr; Lean.initSearchPath; catch (Lean.Server.initAndRunServer i o) (fun err => e.putStrLn (toString err)); pure 0
12749fcc7b089a8257bbe8a2fc4e19fc2f26998c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/to_linear_equiv.lean
a8f4601fb4f24ddef8cad764e5446d8bf22e75db
[ "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
7,400
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.matrix.nondegenerate import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.to_lin import ring_theory.localization.fraction_ring import ring_theory.localization.integer /-! # Matrices and linear equivalences This file gives the map `matrix.to_linear_equiv` from matrices with invertible determinant, to linear equivs. ## Main definitions * `matrix.to_linear_equiv`: a matrix with an invertible determinant forms a linear equiv ## Main results * `matrix.exists_mul_vec_eq_zero_iff`: `M` maps some `v ≠ 0` to zero iff `det M = 0` ## Tags matrix, linear_equiv, determinant, inverse -/ namespace matrix open linear_map variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables {n : Type*} [fintype n] section to_linear_equiv' variables [decidable_eq n] /-- An invertible matrix yields a linear equivalence from the free module to itself. See `matrix.to_linear_equiv` for the same map on arbitrary modules. -/ def to_linear_equiv' (P : matrix n n R) (h : invertible P) : (n → R) ≃ₗ[R] (n → R) := { inv_fun := (⅟P).to_lin', left_inv := λ v, show ((⅟P).to_lin'.comp P.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.inv_of_mul_self, matrix.to_lin'_one, linear_map.id_apply], right_inv := λ v, show (P.to_lin'.comp (⅟P).to_lin') v = v, by rw [← matrix.to_lin'_mul, P.mul_inv_of_self, matrix.to_lin'_one, linear_map.id_apply], ..P.to_lin' } @[simp] lemma to_linear_equiv'_apply (P : matrix n n R) (h : invertible P) : (↑(P.to_linear_equiv' h) : module.End R (n → R)) = P.to_lin' := rfl @[simp] lemma to_linear_equiv'_symm_apply (P : matrix n n R) (h : invertible P) : (↑(P.to_linear_equiv' h).symm : module.End R (n → R)) = P⁻¹.to_lin' := show (⅟P).to_lin' = _, from congr_arg _ P.inv_of_eq_nonsing_inv end to_linear_equiv' section to_linear_equiv variables (b : basis n R M) include b /-- Given `hA : is_unit A.det` and `b : basis R b`, `A.to_linear_equiv b hA` is the `linear_equiv` arising from `to_lin b b A`. See `matrix.to_linear_equiv'` for this result on `n → R`. -/ @[simps apply] noncomputable def to_linear_equiv [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : M ≃ₗ[R] M := begin refine { to_fun := to_lin b b A, inv_fun := to_lin b b A⁻¹, left_inv := λ x, _, right_inv := λ x, _, .. to_lin b b A }; rw ← linear_map.comp_apply; simp only [← matrix.to_lin_mul b b b, matrix.nonsing_inv_mul _ hA, matrix.mul_nonsing_inv _ hA, to_lin_one, linear_map.id_apply] end lemma ker_to_lin_eq_bot [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : (to_lin b b A).ker = ⊥ := ker_eq_bot.mpr (to_linear_equiv b A hA).injective lemma range_to_lin_eq_top [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : (to_lin b b A).range = ⊤ := range_eq_top.mpr (to_linear_equiv b A hA).surjective end to_linear_equiv section nondegenerate open_locale matrix /-- This holds for all integral domains (see `matrix.exists_mul_vec_eq_zero_iff`), not just fields, but it's easier to prove it for the field of fractions first. -/ lemma exists_mul_vec_eq_zero_iff_aux {K : Type*} [decidable_eq n] [field K] {M : matrix n n K} : (∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 := begin split, { rintros ⟨v, hv, mul_eq⟩, contrapose! hv, exact eq_zero_of_mul_vec_eq_zero hv mul_eq }, { contrapose!, intros h, have : function.injective M.to_lin', { simpa only [← linear_map.ker_eq_bot, ker_to_lin'_eq_bot_iff, not_imp_not] using h }, have : M ⬝ linear_map.to_matrix' ((linear_equiv.of_injective_endo M.to_lin' this).symm : (n → K) →ₗ[K] (n → K)) = 1, { refine matrix.to_lin'.injective (linear_map.ext $ λ v, _), rw [matrix.to_lin'_mul, matrix.to_lin'_one, matrix.to_lin'_to_matrix', linear_map.comp_apply], exact (linear_equiv.of_injective_endo M.to_lin' this).apply_symm_apply v }, exact matrix.det_ne_zero_of_right_inverse this } end lemma exists_mul_vec_eq_zero_iff' {A : Type*} (K : Type*) [decidable_eq n] [comm_ring A] [nontrivial A] [field K] [algebra A K] [is_fraction_ring A K] {M : matrix n n A} : (∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 := begin have : (∃ (v ≠ 0), mul_vec ((algebra_map A K).map_matrix M) v = 0) ↔ _ := exists_mul_vec_eq_zero_iff_aux, rw [← ring_hom.map_det, is_fraction_ring.to_map_eq_zero_iff] at this, refine iff.trans _ this, split; rintro ⟨v, hv, mul_eq⟩, { refine ⟨λ i, algebra_map _ _ (v i), mt (λ h, funext $ λ i, _) hv, _⟩, { exact is_fraction_ring.to_map_eq_zero_iff.mp (congr_fun h i) }, { ext i, refine (ring_hom.map_mul_vec _ _ _ i).symm.trans _, rw [mul_eq, pi.zero_apply, ring_hom.map_zero, pi.zero_apply] } }, { letI := classical.dec_eq K, obtain ⟨⟨b, hb⟩, ba_eq⟩ := is_localization.exist_integer_multiples_of_finset (non_zero_divisors A) (finset.univ.image v), choose f hf using ba_eq, refine ⟨λ i, f _ (finset.mem_image.mpr ⟨i, finset.mem_univ i, rfl⟩), mt (λ h, funext $ λ i, _) hv, _⟩, { have := congr_arg (algebra_map A K) (congr_fun h i), rw [hf, subtype.coe_mk, pi.zero_apply, ring_hom.map_zero, algebra.smul_def, mul_eq_zero, is_fraction_ring.to_map_eq_zero_iff] at this, exact this.resolve_left (non_zero_divisors.ne_zero hb), }, { ext i, refine is_fraction_ring.injective A K _, calc algebra_map A K (M.mul_vec (λ (i : n), f (v i) _) i) = ((algebra_map A K).map_matrix M).mul_vec (algebra_map _ K b • v) i : _ ... = 0 : _ ... = algebra_map A K 0 : (ring_hom.map_zero _).symm, { simp_rw [ring_hom.map_mul_vec, mul_vec, dot_product, function.comp_app, hf, subtype.coe_mk, ring_hom.map_matrix_apply, pi.smul_apply, smul_eq_mul, algebra.smul_def] }, { rw [mul_vec_smul, mul_eq, pi.smul_apply, pi.zero_apply, smul_zero] } } }, end lemma exists_mul_vec_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A] {M : matrix n n A} : (∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 := exists_mul_vec_eq_zero_iff' (fraction_ring A) lemma exists_vec_mul_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A] {M : matrix n n A} : (∃ (v ≠ 0), M.vec_mul v = 0) ↔ M.det = 0 := by simpa only [← M.det_transpose, ← mul_vec_transpose] using exists_mul_vec_eq_zero_iff theorem nondegenerate_iff_det_ne_zero {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A] {M : matrix n n A} : nondegenerate M ↔ M.det ≠ 0 := begin refine iff.trans _ (not_iff_not.mpr exists_vec_mul_eq_zero_iff), simp only [not_exists], split, { intros hM v hv hMv, obtain ⟨w, hwMv⟩ := hM.exists_not_ortho_of_ne_zero hv, simpa only [dot_product_mul_vec, hMv, zero_dot_product] using hwMv }, { intros h v hv, refine not_imp_not.mp (h v) (funext $ λ i, _), simpa only [dot_product_mul_vec, dot_product_single, mul_one] using hv (pi.single i 1) } end alias nondegenerate_iff_det_ne_zero ↔ nondegenerate.det_ne_zero nondegenerate.of_det_ne_zero end nondegenerate end matrix
4e2e7cb2e67965286b33657eb0343e293cc79c30
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/forthelean/ForTheLean/Demo.lean
22a45092e003f84e039c2ef23fae6bd1b8eacc0c
[ "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
3,099
lean
-- -*- origami-fold-style: triple-braces -*- import ForTheLean.Prelim open Lean open Lean.Elab.Command open Prelim -- {{{ [synonym] syntax variant := "-"? wlexem syntax [synonym] "[synonym " wlexem ("/" (wlexem <|> variant))+ "]" : command @[command_elab synonym] def elabSynonym : CommandElab := fun stx => match_syntax stx with | `([synonym $w:ident/ -$w':ident]) => modifyEnv $ fun env => addSynonym env w.getId (w.getId.appendAfter w'.getId.toString) | `([synonym $w:ident/$w':ident]) => modifyEnv $ fun env => addSynonym env w.getId w'.getId | _ => throwUnsupportedSyntax -- }}} [synonym number/numbers] -- {{{ syntax indef := "A" <|> "a" <|> "An" <|> "an" syntax art := "The" <|> "the" <|> indef syntax notionPattern := art wlexem+ -- all class nouns are added dynamically declare_syntax_cat classNoun syntax "Signature." notionPattern "is" indef (classNoun <|> "notion") "." : command macro_rules | `(Signature. The $words:wlexem* is a notion.) => let words := words.map Syntax.getId; let parsers := words.map mkSyntaxAtom; let desc := mkIdent $ mkNameSimple $ "_".intercalate $ words.toList.map toString; `(axiom $desc:ident : Type syntax_synonyms [$desc] $parsers:syntax* : classNoun @[macro $desc] def expandSig : Macro := fun _ => `($desc)) | `(Signature. The $words:wlexem* is a $n.) => let words := words.map Syntax.getId; let parsers := words.map mkSyntaxAtom; let desc := mkIdent $ mkNameSimple $ "_".intercalate $ words.toList.map toString; `(axiom $desc:ident : $n syntax_synonyms [$desc] $parsers:syntax* : classNoun @[macro $desc] def expandSig : Macro := fun _ => `($desc)) -- }}} Signature. A real number is a notion. -- {{{ -- TODO: should be single character syntax newVar := ident syntax standFor := "stand" "for" syntax standForDenote := standFor <|> "denote" syntax "Let" (sepBy newVar ",") standForDenote (indef)? classNoun "." : command macro_rules | `(Let $vs* denote $indef* $noun.) => `(variables ($(vs.getSepElems.map (fun v => v.getArg 0)):ident* : $noun)) -- }}} Let x,y stand for real numbers. -- {{{ syntax var := ident -- TODO: should be single character syntax uniPredPattern := var "is" wlexem+ var syntax predPattern := uniPredPattern syntax "Signature." predPattern "is" (indef)? "atom" "." : command macro_rules | `(Signature. $x:var is $words:wlexem* $y:var is an atom.) => let words := words.toList.map Syntax.getId; let desc := mkNameSimple $ "_".intercalate $ words.map toString; `(axiom $(mkIdent desc):ident : type_of $(x.getArg 0) → type_of $(y.getArg 0) → Prop) -- }}} Signature. x is greater than y is an atom. Signature. A packing of congruent balls in Euclidean three space is a notion. Signature. The face centered cubic packing is a packing of congruent balls in Euclidean three space. Let P denote a packing of congruent balls in Euclidean three space. -- incomplete from here on Signature. The density of P is a real number. Theorem The_Kepler_conjecture. No packing of congruent balls in Euclidean three space has density greater than the density of the face centered cubic packing.
a025664370d93ef129badccb7f9c49dc64104722
9dc8cecdf3c4634764a18254e94d43da07142918
/archive/100-theorems-list/73_ascending_descending_sequences.lean
532713d49e55298ec469b2942ee5cae1e352102e
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
8,044
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import tactic.basic import data.fintype.basic /-! # Erdős–Szekeres theorem This file proves Theorem 73 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as the Erdős–Szekeres theorem: given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. We use the proof outlined at https://en.wikipedia.org/wiki/Erdos-Szekeres_theorem#Pigeonhole_principle. ## Tags sequences, increasing, decreasing, Ramsey, Erdos-Szekeres, Erdős–Szekeres, Erdős-Szekeres -/ variables {α : Type*} [linear_order α] {β : Type*} open function finset open_locale classical /-- **Erdős–Szekeres Theorem**: Given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. Proof idea: We label each value in the sequence with two numbers specifying the longest increasing subsequence ending there, and the longest decreasing subsequence ending there. We then show the pair of labels must be unique. Now if there is no increasing sequence longer than `r` and no decreasing sequence longer than `s`, then there are at most `r * s` possible labels, which is a contradiction if there are more than `r * s` elements. -/ theorem erdos_szekeres {r s n : ℕ} {f : fin n → α} (hn : r * s < n) (hf : injective f) : (∃ (t : finset (fin n)), r < t.card ∧ strict_mono_on f ↑t) ∨ (∃ (t : finset (fin n)), s < t.card ∧ strict_anti_on f ↑t) := begin -- Given an index `i`, produce the set of increasing (resp., decreasing) subsequences which ends -- at `i`. let inc_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = i ∧ strict_mono_on f ↑t), let dec_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = i ∧ strict_anti_on f ↑t), -- The singleton sequence is in both of the above collections. -- (This is useful to show that the maximum length subsequence is at least 1, and that the set -- of subsequences is nonempty.) have inc_i : ∀ i, {i} ∈ inc_sequences_ending_in i := λ i, by simp [strict_mono_on], have dec_i : ∀ i, {i} ∈ dec_sequences_ending_in i := λ i, by simp [strict_anti_on], -- Define the pair of labels: at index `i`, the pair is the maximum length of an increasing -- subsequence ending at `i`, paired with the maximum length of a decreasing subsequence ending -- at `i`. -- We call these labels `(a_i, b_i)`. let ab : fin n → ℕ × ℕ, { intro i, apply (max' ((inc_sequences_ending_in i).image card) (nonempty.image ⟨{i}, inc_i i⟩ _), max' ((dec_sequences_ending_in i).image card) (nonempty.image ⟨{i}, dec_i i⟩ _)) }, -- It now suffices to show that one of the labels is 'big' somewhere. In particular, if the -- first in the pair is more than `r` somewhere, then we have an increasing subsequence in our -- set, and if the second is more than `s` somewhere, then we have a decreasing subsequence. rsuffices ⟨i, hi⟩ : ∃ i, r < (ab i).1 ∨ s < (ab i).2, { apply or.imp _ _ hi, work_on_goal 1 { have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 2 { have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { intro hi, rw mem_image at this, obtain ⟨t, ht₁, ht₂⟩ := this, refine ⟨t, by rwa ht₂, _⟩, rw mem_filter at ht₁, apply ht₁.2.2 } }, -- Show first that the pair of labels is unique. have : injective ab, { apply injective_of_lt_imp_ne, intros i j k q, injection q with q₁ q₂, -- We have two cases: `f i < f j` or `f j < f i`. -- In the former we'll show `a_i < a_j`, and in the latter we'll show `b_i < b_j`. cases lt_or_gt_of_ne (λ _, ne_of_lt ‹i < j› (hf ‹f i = f j›)), work_on_goal 1 { apply ne_of_lt _ q₁, have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 2 { apply ne_of_lt _ q₂, have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { -- Reduce to showing there is a subsequence of length `a_i + 1` which ends at `j`. rw nat.lt_iff_add_one_le, apply le_max', rw mem_image at this ⊢, -- In particular we take the subsequence `t` of length `a_i` which ends at `i`, by definition -- of `a_i` rcases this with ⟨t, ht₁, ht₂⟩, rw mem_filter at ht₁, -- Ensure `t` ends at `i`. have : t.max = i, simp [ht₁.2.1], -- Now our new subsequence is given by adding `j` at the end of `t`. refine ⟨insert j t, _, _⟩, -- First make sure it's valid, i.e., that this subsequence ends at `j` and is increasing { rw mem_filter, refine ⟨_, _, _⟩, { rw mem_powerset, apply subset_univ }, -- It ends at `j` since `i < j`. { convert max_insert, rw [ht₁.2.1, max_eq_left], apply with_bot.coe_le_coe.mpr (le_of_lt ‹i < j›) }, -- To show it's increasing (i.e., `f` is monotone increasing on `t.insert j`), we do cases -- on what the possibilities could be - either in `t` or equals `j`. simp only [strict_mono_on, strict_anti_on, coe_insert, set.mem_insert_iff, mem_coe], -- Most of the cases are just bashes. rintros x ⟨rfl | _⟩ y ⟨rfl | _⟩ _, { apply (irrefl _ ‹j < j›).elim }, { exfalso, apply not_le_of_lt (trans ‹i < j› ‹j < y›) (le_max_of_mem ‹y ∈ t› ‹t.max = i›) }, { apply lt_of_le_of_lt _ ‹f i < f j› <|> apply lt_of_lt_of_le ‹f j < f i› _, rcases lt_or_eq_of_le (le_max_of_mem ‹x ∈ t› ‹t.max = i›) with _ | rfl, { apply le_of_lt (ht₁.2.2 ‹x ∈ t› (mem_of_max ‹t.max = i›) ‹x < i›) }, { refl } }, { apply ht₁.2.2 ‹x ∈ t› ‹y ∈ t› ‹x < y› } }, -- Finally show that this new subsequence is one longer than the old one. { rw [card_insert_of_not_mem, ht₂], intro _, apply not_le_of_lt ‹i < j› (le_max_of_mem ‹j ∈ t› ‹t.max = i›) } } }, -- Finished both goals! -- Now that we have uniqueness of each label, it remains to do some counting to finish off. -- Suppose all the labels are small. by_contra q, push_neg at q, -- Then the labels `(a_i, b_i)` all fit in the following set: `{ (x,y) | 1 ≤ x ≤ r, 1 ≤ y ≤ s }` let ran : finset (ℕ × ℕ) := (range r).image nat.succ ×ˢ (range s).image nat.succ, -- which we prove here. have : image ab univ ⊆ ran, -- First some logical shuffling { rintro ⟨x₁, x₂⟩, simp only [mem_image, exists_prop, mem_range, mem_univ, mem_product, true_and, prod.mk.inj_iff], rintros ⟨i, rfl, rfl⟩, specialize q i, -- Show `1 ≤ a_i` and `1 ≤ b_i`, which is easy from the fact that `{i}` is a increasing and -- decreasing subsequence which we did right near the top. have z : 1 ≤ (ab i).1 ∧ 1 ≤ (ab i).2, { split; { apply le_max', rw mem_image, refine ⟨{i}, by solve_by_elim, card_singleton i⟩ } }, refine ⟨_, _⟩, -- Need to get `a_i ≤ r`, here phrased as: there is some `a < r` with `a+1 = a_i`. { refine ⟨(ab i).1 - 1, _, nat.succ_pred_eq_of_pos z.1⟩, rw tsub_lt_iff_right z.1, apply nat.lt_succ_of_le q.1 }, { refine ⟨(ab i).2 - 1, _, nat.succ_pred_eq_of_pos z.2⟩, rw tsub_lt_iff_right z.2, apply nat.lt_succ_of_le q.2 } }, -- To get our contradiction, it suffices to prove `n ≤ r * s` apply not_le_of_lt hn, -- Which follows from considering the cardinalities of the subset above, since `ab` is injective. simpa [nat.succ_injective, card_image_of_injective, ‹injective ab›] using card_le_of_subset this, end
8353ab3bd2757878e6e604fbe1c90b8e0f3054ef
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/basic_auto.lean
6bce73739d06a34057e6e74bd97a12f1423b405b
[]
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
99,234
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.perm import Mathlib.algebra.group_power.default import Mathlib.PostPort universes u u_1 u_4 u_2 u_3 namespace Mathlib /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def multiset (α : Type u) := quotient (list.is_setoid α) namespace multiset protected instance has_coe {α : Type u_1} : has_coe (List α) (multiset α) := has_coe.mk (Quot.mk setoid.r) @[simp] theorem quot_mk_to_coe {α : Type u_1} (l : List α) : quotient.mk l = ↑l := rfl @[simp] theorem quot_mk_to_coe' {α : Type u_1} (l : List α) : Quot.mk has_equiv.equiv l = ↑l := rfl @[simp] theorem quot_mk_to_coe'' {α : Type u_1} (l : List α) : Quot.mk setoid.r l = ↑l := rfl @[simp] theorem coe_eq_coe {α : Type u_1} {l₁ : List α} {l₂ : List α} : ↑l₁ = ↑l₂ ↔ l₁ ~ l₂ := quotient.eq protected instance has_decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (multiset α) := sorry /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof {α : Type u_1} [SizeOf α] (s : multiset α) : ℕ := quot.lift_on s sizeof sorry protected instance has_sizeof {α : Type u_1} [SizeOf α] : SizeOf (multiset α) := { sizeOf := multiset.sizeof } /-! ### Empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero {α : Type u_1} : multiset α := ↑[] protected instance has_zero {α : Type u_1} : HasZero (multiset α) := { zero := multiset.zero } protected instance has_emptyc {α : Type u_1} : has_emptyc (multiset α) := has_emptyc.mk 0 protected instance inhabited {α : Type u_1} : Inhabited (multiset α) := { default := 0 } @[simp] theorem coe_nil_eq_zero {α : Type u_1} : ↑[] = 0 := rfl @[simp] theorem empty_eq_zero {α : Type u_1} : ∅ = 0 := rfl theorem coe_eq_zero {α : Type u_1} (l : List α) : ↑l = 0 ↔ l = [] := iff.trans coe_eq_coe list.perm_nil /-! ### `multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons {α : Type u_1} (a : α) (s : multiset α) : multiset α := quot.lift_on s (fun (l : List α) => ↑(a :: l)) sorry infixr:67 " ::ₘ " => Mathlib.multiset.cons protected instance has_insert {α : Type u_1} : has_insert α (multiset α) := has_insert.mk cons @[simp] theorem insert_eq_cons {α : Type u_1} (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe {α : Type u_1} (a : α) (l : List α) : a ::ₘ ↑l = ↑(a :: l) := rfl theorem singleton_coe {α : Type u_1} (a : α) : a ::ₘ 0 = ↑[a] := rfl @[simp] theorem cons_inj_left {α : Type u_1} {a : α} {b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := sorry @[simp] theorem cons_inj_right {α : Type u_1} (a : α) {s : multiset α} {t : multiset α} : a ::ₘ s = a ::ₘ t ↔ s = t := sorry protected theorem induction {α : Type u_1} {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ {a : α} {s : multiset α}, p s → p (a ::ₘ s)) (s : multiset α) : p s := quot.induction_on s fun (l : List α) => List.rec h₁ (fun (l_hd : α) (l_tl : List α) (ih : p (Quot.mk setoid.r l_tl)) => h₂ ih) l protected theorem induction_on {α : Type u_1} {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ {a : α} {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap {α : Type u_1} (a : α) (b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s fun (l : List α) => quotient.sound (list.perm.swap b a l) /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec {α : Type u_1} {C : multiset α → Sort u_4} (C_0 : C 0) (C_cons : (a : α) → (m : multiset α) → C m → C (a ::ₘ m)) (C_cons_heq : ∀ (a a' : α) (m : multiset α) (b : C m), C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (List.rec C_0 fun (a : α) (l : List α) (b : C (quotient.mk l)) => C_cons a (quotient.mk l) b) sorry protected def rec_on {α : Type u_1} {C : multiset α → Sort u_4} (m : multiset α) (C_0 : C 0) (C_cons : (a : α) → (m : multiset α) → C m → C (a ::ₘ m)) (C_cons_heq : ∀ (a a' : α) (m : multiset α) (b : C m), C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m @[simp] theorem rec_on_0 {α : Type u_1} {C : multiset α → Sort u_4} {C_0 : C 0} {C_cons : (a : α) → (m : multiset α) → C m → C (a ::ₘ m)} {C_cons_heq : ∀ (a a' : α) (m : multiset α) (b : C m), C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} : multiset.rec_on 0 C_0 C_cons C_cons_heq = C_0 := rfl @[simp] theorem rec_on_cons {α : Type u_1} {C : multiset α → Sort u_4} {C_0 : C 0} {C_cons : (a : α) → (m : multiset α) → C m → C (a ::ₘ m)} {C_cons_heq : ∀ (a a' : α) (m : multiset α) (b : C m), C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} (a : α) (m : multiset α) : multiset.rec_on (a ::ₘ m) C_0 C_cons C_cons_heq = C_cons a m (multiset.rec_on m C_0 C_cons C_cons_heq) := quotient.induction_on m fun (l : List α) => rfl /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem {α : Type u_1} (a : α) (s : multiset α) := quot.lift_on s (fun (l : List α) => a ∈ l) sorry protected instance has_mem {α : Type u_1} : has_mem α (multiset α) := has_mem.mk mem @[simp] theorem mem_coe {α : Type u_1} {a : α} {l : List α} : a ∈ ↑l ↔ a ∈ l := iff.rfl protected instance decidable_mem {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : Decidable (a ∈ s) := quot.rec_on_subsingleton s (list.decidable_mem a) @[simp] theorem mem_cons {α : Type u_1} {a : α} {b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s fun (l : List α) => iff.rfl theorem mem_cons_of_mem {α : Type u_1} {a : α} {b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := iff.mpr mem_cons (Or.inr h) @[simp] theorem mem_cons_self {α : Type u_1} (a : α) (s : multiset α) : a ∈ a ::ₘ s := iff.mpr mem_cons (Or.inl rfl) theorem forall_mem_cons {α : Type u_1} {p : α → Prop} {a : α} {s : multiset α} : (∀ (x : α), x ∈ a ::ₘ s → p x) ↔ p a ∧ ∀ (x : α), x ∈ s → p x := quotient.induction_on' s fun (L : List α) => list.forall_mem_cons theorem exists_cons_of_mem {α : Type u_1} {s : multiset α} {a : α} : a ∈ s → ∃ (t : multiset α), s = a ::ₘ t := sorry @[simp] theorem not_mem_zero {α : Type u_1} (a : α) : ¬a ∈ 0 := id theorem eq_zero_of_forall_not_mem {α : Type u_1} {s : multiset α} : (∀ (x : α), ¬x ∈ s) → s = 0 := sorry theorem eq_zero_iff_forall_not_mem {α : Type u_1} {s : multiset α} : s = 0 ↔ ∀ (a : α), ¬a ∈ s := { mp := fun (h : s = 0) => Eq.symm h ▸ fun (_x : α) => not_false, mpr := eq_zero_of_forall_not_mem } theorem exists_mem_of_ne_zero {α : Type u_1} {s : multiset α} : s ≠ 0 → ∃ (a : α), a ∈ s := sorry @[simp] theorem zero_ne_cons {α : Type u_1} {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := fun (h : 0 = a ::ₘ m) => (fun (this : a ∈ 0) => not_mem_zero a this) (Eq.symm h ▸ mem_cons_self a m) @[simp] theorem cons_ne_zero {α : Type u_1} {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := ne.symm zero_ne_cons theorem cons_eq_cons {α : Type u_1} {a : α} {b : α} {as : multiset α} {bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ a = b ∧ as = bs ∨ a ≠ b ∧ ∃ (cs : multiset α), as = b ::ₘ cs ∧ bs = a ::ₘ cs := sorry /-! ### `multiset.subset` -/ /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset {α : Type u_1} (s : multiset α) (t : multiset α) := ∀ {a : α}, a ∈ s → a ∈ t protected instance has_subset {α : Type u_1} : has_subset (multiset α) := has_subset.mk multiset.subset @[simp] theorem coe_subset {α : Type u_1} {l₁ : List α} {l₂ : List α} : ↑l₁ ⊆ ↑l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl {α : Type u_1} (s : multiset α) : s ⊆ s := fun (a : α) (h : a ∈ s) => h theorem subset.trans {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := fun (h₁ : s ⊆ t) (h₂ : t ⊆ u) (a : α) (m : a ∈ s) => h₂ (h₁ m) theorem subset_iff {α : Type u_1} {s : multiset α} {t : multiset α} : s ⊆ t ↔ ∀ {x : α}, x ∈ s → x ∈ t := iff.rfl theorem mem_of_subset {α : Type u_1} {s : multiset α} {t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := h @[simp] theorem zero_subset {α : Type u_1} (s : multiset α) : 0 ⊆ s := fun (a : α) => not.elim (list.not_mem_nil a) @[simp] theorem cons_subset {α : Type u_1} {a : α} {s : multiset α} {t : multiset α} : a ::ₘ s ⊆ t ↔ a ∈ t ∧ s ⊆ t := sorry theorem eq_zero_of_subset_zero {α : Type u_1} {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {α : Type u_1} {s : multiset α} : s ⊆ 0 ↔ s = 0 := { mp := eq_zero_of_subset_zero, mpr := fun (xeq : s = 0) => Eq.symm xeq ▸ subset.refl 0 } /-- Produces a list of the elements in the multiset using choice. -/ def to_list {α : Type u_1} (s : multiset α) : List α := classical.some sorry @[simp] theorem to_list_zero {α : Type u_1} : to_list 0 = [] := iff.mp (coe_eq_zero (to_list 0)) (classical.some_spec (quotient.exists_rep multiset.zero)) theorem coe_to_list {α : Type u_1} (s : multiset α) : ↑(to_list s) = s := classical.some_spec (quotient.exists_rep s) theorem mem_to_list {α : Type u_1} (a : α) (s : multiset α) : a ∈ to_list s ↔ a ∈ s := eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ to_list s ↔ a ∈ s)) (Eq.symm (propext mem_coe)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ ↑(to_list s) ↔ a ∈ s)) (coe_to_list s))) (iff.refl (a ∈ s))) /-! ### Partial order on `multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le {α : Type u_1} (s : multiset α) (t : multiset α) := quotient.lift_on₂ s t list.subperm sorry protected instance partial_order {α : Type u_1} : partial_order (multiset α) := partial_order.mk multiset.le (preorder.lt._default multiset.le) sorry sorry sorry theorem subset_of_le {α : Type u_1} {s : multiset α} {t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.subperm.subset theorem mem_of_le {α : Type u_1} {s : multiset α} {t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {α : Type u_1} {l₁ : List α} {l₂ : List α} : ↑l₁ ≤ ↑l₂ ↔ l₁ <+~ l₂ := iff.rfl theorem le_induction_on {α : Type u_1} {C : multiset α → multiset α → Prop} {s : multiset α} {t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : List α}, l₁ <+ l₂ → C ↑l₁ ↑l₂) : C s t := sorry theorem zero_le {α : Type u_1} (s : multiset α) : 0 ≤ s := quot.induction_on s fun (l : List α) => list.sublist.subperm (list.nil_sublist l) theorem le_zero {α : Type u_1} {s : multiset α} : s ≤ 0 ↔ s = 0 := { mp := fun (h : s ≤ 0) => le_antisymm h (zero_le s), mpr := le_of_eq } theorem lt_cons_self {α : Type u_1} (s : multiset α) (a : α) : s < a ::ₘ s := sorry theorem le_cons_self {α : Type u_1} (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt (lt_cons_self s a) theorem cons_le_cons_iff {α : Type u_1} (a : α) {s : multiset α} {t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.subperm_cons a theorem cons_le_cons {α : Type u_1} (a : α) {s : multiset α} {t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t := iff.mpr (cons_le_cons_iff a) theorem le_cons_of_not_mem {α : Type u_1} {a : α} {s : multiset α} {t : multiset α} (m : ¬a ∈ s) : s ≤ a ::ₘ t ↔ s ≤ t := sorry /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add {α : Type u_1} (s₁ : multiset α) (s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (fun (l₁ l₂ : List α) => ↑(l₁ ++ l₂)) sorry protected instance has_add {α : Type u_1} : Add (multiset α) := { add := multiset.add } @[simp] theorem coe_add {α : Type u_1} (s : List α) (t : List α) : ↑s + ↑t = ↑(s ++ t) := rfl protected theorem add_comm {α : Type u_1} (s : multiset α) (t : multiset α) : s + t = t + s := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => quot.sound list.perm_append_comm protected theorem zero_add {α : Type u_1} (s : multiset α) : 0 + s = s := quot.induction_on s fun (l : List α) => rfl theorem singleton_add {α : Type u_1} (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl protected theorem add_le_add_left {α : Type u_1} (s : multiset α) {t : multiset α} {u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u fun (l₁ l₂ l₃ : List α) => list.subperm_append_left l₁ protected theorem add_left_cancel {α : Type u_1} (s : multiset α) {t : multiset α} {u : multiset α} (h : s + t = s + u) : t = u := le_antisymm (iff.mp (multiset.add_le_add_left s) (le_of_eq h)) (iff.mp (multiset.add_le_add_left s) (le_of_eq (Eq.symm h))) protected instance ordered_cancel_add_comm_monoid {α : Type u_1} : ordered_cancel_add_comm_monoid (multiset α) := ordered_cancel_add_comm_monoid.mk Add.add sorry multiset.add_left_cancel 0 multiset.zero_add sorry multiset.add_comm sorry partial_order.le partial_order.lt sorry sorry sorry sorry sorry theorem le_add_right {α : Type u_1} (s : multiset α) (t : multiset α) : s ≤ s + t := sorry theorem le_add_left {α : Type u_1} (s : multiset α) (t : multiset α) : s ≤ t + s := sorry theorem le_iff_exists_add {α : Type u_1} {s : multiset α} {t : multiset α} : s ≤ t ↔ ∃ (u : multiset α), t = s + u := sorry protected instance canonically_ordered_add_monoid {α : Type u_1} : canonically_ordered_add_monoid (multiset α) := canonically_ordered_add_monoid.mk ordered_cancel_add_comm_monoid.add sorry ordered_cancel_add_comm_monoid.zero sorry sorry sorry ordered_cancel_add_comm_monoid.le ordered_cancel_add_comm_monoid.lt sorry sorry sorry sorry sorry 0 zero_le le_iff_exists_add @[simp] theorem cons_add {α : Type u_1} (a : α) (s : multiset α) (t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := sorry @[simp] theorem add_cons {α : Type u_1} (a : α) (s : multiset α) (t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := eq.mpr (id (Eq._oldrec (Eq.refl (s + a ::ₘ t = a ::ₘ (s + t))) (add_comm s (a ::ₘ t)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ::ₘ t + s = a ::ₘ (s + t))) (cons_add a t s))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ::ₘ (t + s) = a ::ₘ (s + t))) (add_comm t s))) (Eq.refl (a ::ₘ (s + t))))) @[simp] theorem mem_add {α : Type u_1} {a : α} {s : multiset α} {t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.mem_append /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card {α : Type u_1} : multiset α →+ ℕ := add_monoid_hom.mk (fun (s : multiset α) => quot.lift_on s list.length sorry) sorry sorry @[simp] theorem coe_card {α : Type u_1} (l : List α) : coe_fn card ↑l = list.length l := rfl @[simp] theorem card_zero {α : Type u_1} : coe_fn card 0 = 0 := rfl theorem card_add {α : Type u_1} (s : multiset α) (t : multiset α) : coe_fn card (s + t) = coe_fn card s + coe_fn card t := add_monoid_hom.map_add card s t theorem card_smul {α : Type u_1} (s : multiset α) (n : ℕ) : coe_fn card (n •ℕ s) = n * coe_fn card s := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn card (n •ℕ s) = n * coe_fn card s)) (add_monoid_hom.map_nsmul card s n))) (eq.mpr (id (Eq._oldrec (Eq.refl (n •ℕ coe_fn card s = n * coe_fn card s)) (nat.nsmul_eq_mul n (coe_fn card s)))) (Eq.refl (n * coe_fn card s))) @[simp] theorem card_cons {α : Type u_1} (a : α) (s : multiset α) : coe_fn card (a ::ₘ s) = coe_fn card s + 1 := quot.induction_on s fun (l : List α) => rfl @[simp] theorem card_singleton {α : Type u_1} (a : α) : coe_fn card (a ::ₘ 0) = 1 := sorry theorem card_le_of_le {α : Type u_1} {s : multiset α} {t : multiset α} (h : s ≤ t) : coe_fn card s ≤ coe_fn card t := le_induction_on h fun (l₁ l₂ : List α) => list.length_le_of_sublist theorem eq_of_le_of_card_le {α : Type u_1} {s : multiset α} {t : multiset α} (h : s ≤ t) : coe_fn card t ≤ coe_fn card s → s = t := le_induction_on h fun (l₁ l₂ : List α) (s : l₁ <+ l₂) (h₂ : coe_fn card ↑l₂ ≤ coe_fn card ↑l₁) => congr_arg coe (list.eq_of_sublist_of_length_le s h₂) theorem card_lt_of_lt {α : Type u_1} {s : multiset α} {t : multiset α} (h : s < t) : coe_fn card s < coe_fn card t := lt_of_not_ge fun (h₂ : coe_fn card s ≥ coe_fn card t) => ne_of_lt h (eq_of_le_of_card_le (le_of_lt h) h₂) theorem lt_iff_cons_le {α : Type u_1} {s : multiset α} {t : multiset α} : s < t ↔ ∃ (a : α), a ::ₘ s ≤ t := sorry @[simp] theorem card_eq_zero {α : Type u_1} {s : multiset α} : coe_fn card s = 0 ↔ s = 0 := sorry theorem card_pos {α : Type u_1} {s : multiset α} : 0 < coe_fn card s ↔ s ≠ 0 := iff.trans pos_iff_ne_zero (not_congr card_eq_zero) theorem card_pos_iff_exists_mem {α : Type u_1} {s : multiset α} : 0 < coe_fn card s ↔ ∃ (a : α), a ∈ s := quot.induction_on s fun (l : List α) => list.length_pos_iff_exists_mem def strong_induction_on {α : Type u_1} {p : multiset α → Sort u_2} (s : multiset α) : ((s : multiset α) → ((t : multiset α) → t < s → p t) → p s) → p s := sorry theorem strong_induction_eq {α : Type u_1} {p : multiset α → Sort u_2} (s : multiset α) (H : (s : multiset α) → ((t : multiset α) → t < s → p t) → p s) : strong_induction_on s H = H s fun (t : multiset α) (h : t < s) => strong_induction_on t H := sorry theorem case_strong_induction_on {α : Type u_1} {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ (a : α) (s : multiset α), (∀ (t : multiset α), t ≤ s → p t) → p (a ::ₘ s)) : p s := sorry /-! ### Singleton -/ protected instance has_singleton {α : Type u_1} : has_singleton α (multiset α) := has_singleton.mk fun (a : α) => a ::ₘ 0 protected instance is_lawful_singleton {α : Type u_1} : is_lawful_singleton α (multiset α) := is_lawful_singleton.mk fun (a : α) => rfl @[simp] theorem singleton_eq_singleton {α : Type u_1} (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {α : Type u_1} {a : α} {b : α} : b ∈ a ::ₘ 0 ↔ b = a := sorry theorem mem_singleton_self {α : Type u_1} (a : α) : a ∈ a ::ₘ 0 := mem_cons_self a 0 theorem singleton_inj {α : Type u_1} {a : α} {b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left 0 @[simp] theorem singleton_ne_zero {α : Type u_1} (a : α) : a ::ₘ 0 ≠ 0 := ne_of_gt (lt_cons_self 0 a) @[simp] theorem singleton_le {α : Type u_1} {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s := sorry theorem card_eq_one {α : Type u_1} {s : multiset α} : coe_fn card s = 1 ↔ ∃ (a : α), s = a ::ₘ 0 := sorry /-! ### `multiset.repeat` -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat {α : Type u_1} (a : α) (n : ℕ) : multiset α := ↑(list.repeat a n) @[simp] theorem repeat_zero {α : Type u_1} (a : α) : repeat a 0 = 0 := rfl @[simp] theorem repeat_succ {α : Type u_1} (a : α) (n : ℕ) : repeat a (n + 1) = a ::ₘ repeat a n := sorry @[simp] theorem repeat_one {α : Type u_1} (a : α) : repeat a 1 = a ::ₘ 0 := sorry @[simp] theorem card_repeat {α : Type u_1} (a : α) (n : ℕ) : coe_fn card (repeat a n) = n := list.length_repeat theorem eq_of_mem_repeat {α : Type u_1} {a : α} {b : α} {n : ℕ} : b ∈ repeat a n → b = a := list.eq_of_mem_repeat theorem eq_repeat' {α : Type u_1} {a : α} {s : multiset α} : s = repeat a (coe_fn card s) ↔ ∀ (b : α), b ∈ s → b = a := sorry theorem eq_repeat_of_mem {α : Type u_1} {a : α} {s : multiset α} : (∀ (b : α), b ∈ s → b = a) → s = repeat a (coe_fn card s) := iff.mpr eq_repeat' theorem eq_repeat {α : Type u_1} {a : α} {n : ℕ} {s : multiset α} : s = repeat a n ↔ coe_fn card s = n ∧ ∀ (b : α), b ∈ s → b = a := sorry theorem repeat_subset_singleton {α : Type u_1} (a : α) (n : ℕ) : repeat a n ⊆ a ::ₘ 0 := list.repeat_subset_singleton theorem repeat_le_coe {α : Type u_1} {a : α} {n : ℕ} {l : List α} : repeat a n ≤ ↑l ↔ list.repeat a n <+ l := sorry /-! ### Erasing one copy of an element -/ /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase {α : Type u_1} [DecidableEq α] (s : multiset α) (a : α) : multiset α := quot.lift_on s (fun (l : List α) => ↑(list.erase l a)) sorry @[simp] theorem coe_erase {α : Type u_1} [DecidableEq α] (l : List α) (a : α) : erase (↑l) a = ↑(list.erase l a) := rfl @[simp] theorem erase_zero {α : Type u_1} [DecidableEq α] (a : α) : erase 0 a = 0 := rfl @[simp] theorem erase_cons_head {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : erase (a ::ₘ s) a = s := quot.induction_on s fun (l : List α) => congr_arg coe (list.erase_cons_head a l) @[simp] theorem erase_cons_tail {α : Type u_1} [DecidableEq α] {a : α} {b : α} (s : multiset α) (h : b ≠ a) : erase (b ::ₘ s) a = b ::ₘ erase s a := quot.induction_on s fun (l : List α) => congr_arg coe (list.erase_cons_tail l h) @[simp] theorem erase_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : ¬a ∈ s → erase s a = s := quot.induction_on s fun (l : List α) (h : ¬a ∈ Quot.mk setoid.r l) => congr_arg coe (list.erase_of_not_mem h) @[simp] theorem cons_erase {α : Type u_1} [DecidableEq α] {s : multiset α} {a : α} : a ∈ s → a ::ₘ erase s a = s := quot.induction_on s fun (l : List α) (h : a ∈ Quot.mk setoid.r l) => quot.sound (list.perm.symm (list.perm_cons_erase h)) theorem le_cons_erase {α : Type u_1} [DecidableEq α] (s : multiset α) (a : α) : s ≤ a ::ₘ erase s a := dite (a ∈ s) (fun (h : a ∈ s) => le_of_eq (Eq.symm (cons_erase h))) fun (h : ¬a ∈ s) => eq.mpr (id (Eq._oldrec (Eq.refl (s ≤ a ::ₘ erase s a)) (erase_of_not_mem h))) (le_cons_self s a) theorem erase_add_left_pos {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} (t : multiset α) : a ∈ s → erase (s + t) a = erase s a + t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) (h : a ∈ quotient.mk l₁) => congr_arg coe (list.erase_append_left l₂ h) theorem erase_add_right_pos {α : Type u_1} [DecidableEq α] {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : erase (s + t) a = s + erase t a := sorry theorem erase_add_right_neg {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} (t : multiset α) : ¬a ∈ s → erase (s + t) a = s + erase t a := quotient.induction_on₂ s t fun (l₁ l₂ : List α) (h : ¬a ∈ quotient.mk l₁) => congr_arg coe (list.erase_append_right l₂ h) theorem erase_add_left_neg {α : Type u_1} [DecidableEq α] {a : α} (s : multiset α) {t : multiset α} (h : ¬a ∈ t) : erase (s + t) a = erase s a + t := sorry theorem erase_le {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : erase s a ≤ s := quot.induction_on s fun (l : List α) => list.sublist.subperm (list.erase_sublist a l) @[simp] theorem erase_lt {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : erase s a < s ↔ a ∈ s := sorry theorem erase_subset {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : erase s a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : multiset α} (ab : a ≠ b) : a ∈ erase s b ↔ a ∈ s := quot.induction_on s fun (l : List α) => list.mem_erase_of_ne ab theorem mem_of_mem_erase {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : multiset α} : a ∈ erase s b → a ∈ s := mem_of_subset (erase_subset b s) theorem erase_comm {α : Type u_1} [DecidableEq α] (s : multiset α) (a : α) (b : α) : erase (erase s a) b = erase (erase s b) a := quot.induction_on s fun (l : List α) => congr_arg coe (list.erase_comm a b l) theorem erase_le_erase {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (a : α) (h : s ≤ t) : erase s a ≤ erase t a := le_induction_on h fun (l₁ l₂ : List α) (h : l₁ <+ l₂) => list.sublist.subperm (list.sublist.erase a h) theorem erase_le_iff_le_cons {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {a : α} : erase s a ≤ t ↔ s ≤ a ::ₘ t := sorry @[simp] theorem card_erase_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : a ∈ s → coe_fn card (erase s a) = Nat.pred (coe_fn card s) := quot.induction_on s fun (l : List α) => list.length_erase_of_mem theorem card_erase_lt_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : a ∈ s → coe_fn card (erase s a) < coe_fn card s := fun (h : a ∈ s) => card_lt_of_lt (iff.mpr erase_lt h) theorem card_erase_le {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : coe_fn card (erase s a) ≤ coe_fn card s := card_le_of_le (erase_le a s) @[simp] theorem coe_reverse {α : Type u_1} (l : List α) : ↑(list.reverse l) = ↑l := quot.sound (list.reverse_perm l) /-! ### `multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map {α : Type u_1} {β : Type u_2} (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (fun (l : List α) => ↑(list.map f l)) sorry theorem forall_mem_map_iff {α : Type u_1} {β : Type u_2} {f : α → β} {p : β → Prop} {s : multiset α} : (∀ (y : β), y ∈ map f s → p y) ↔ ∀ (x : α), x ∈ s → p (f x) := quotient.induction_on' s fun (L : List α) => list.forall_mem_map_iff @[simp] theorem coe_map {α : Type u_1} {β : Type u_2} (f : α → β) (l : List α) : map f ↑l = ↑(list.map f l) := rfl @[simp] theorem map_zero {α : Type u_1} {β : Type u_2} (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) (s : multiset α) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s fun (l : List α) => rfl theorem map_singleton {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) : map f (singleton a) = singleton (f a) := rfl theorem map_repeat {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) (k : ℕ) : map f (repeat a k) = repeat (f a) k := sorry @[simp] theorem map_add {α : Type u_1} {β : Type u_2} (f : α → β) (s : multiset α) (t : multiset α) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => congr_arg coe (list.map_append f l₁ l₂) protected instance map.is_add_monoid_hom {α : Type u_1} {β : Type u_2} (f : α → β) : is_add_monoid_hom (map f) := is_add_monoid_hom.mk (map_zero f) theorem map_nsmul {α : Type u_1} {β : Type u_2} (f : α → β) (n : ℕ) (s : multiset α) : map f (n •ℕ s) = n •ℕ map f s := add_monoid_hom.map_nsmul (add_monoid_hom.of (map f)) s n @[simp] theorem mem_map {α : Type u_1} {β : Type u_2} {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ (a : α), a ∈ s ∧ f a = b := quot.induction_on s fun (l : List α) => list.mem_map @[simp] theorem card_map {α : Type u_1} {β : Type u_2} (f : α → β) (s : multiset α) : coe_fn card (map f s) = coe_fn card s := quot.induction_on s fun (l : List α) => list.length_map f l @[simp] theorem map_eq_zero {α : Type u_1} {β : Type u_2} {s : multiset α} {f : α → β} : map f s = 0 ↔ s = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (map f s = 0 ↔ s = 0)) (Eq.symm (propext card_eq_zero)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn card (map f s) = 0 ↔ s = 0)) (card_map f s))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn card s = 0 ↔ s = 0)) (propext card_eq_zero))) (iff.refl (s = 0)))) theorem mem_map_of_mem {α : Type u_1} {β : Type u_2} (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := iff.mpr mem_map (Exists.intro a { left := h, right := rfl }) theorem mem_map_of_injective {α : Type u_1} {β : Type u_2} {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s fun (l : List α) => list.mem_map_of_injective H @[simp] theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.map_map g f l) theorem map_id {α : Type u_1} (s : multiset α) : map id s = s := quot.induction_on s fun (l : List α) => congr_arg coe (list.map_id l) @[simp] theorem map_id' {α : Type u_1} (s : multiset α) : map (fun (x : α) => x) s = s := map_id s @[simp] theorem map_const {α : Type u_1} {β : Type u_2} (s : multiset α) (b : β) : map (function.const α b) s = repeat b (coe_fn card s) := quot.induction_on s fun (l : List α) => congr_arg coe (list.map_const l b) theorem map_congr {α : Type u_1} {β : Type u_2} {f : α → β} {g : α → β} {s : multiset α} : (∀ (x : α), x ∈ s → f x = g x) → map f s = map g s := quot.induction_on s fun (l : List α) (H : ∀ (x : α), x ∈ Quot.mk setoid.r l → f x = g x) => congr_arg coe (list.map_congr H) theorem map_hcongr {α : Type u_1} {β : Type u_2} {β' : Type u_2} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀ (a : α), a ∈ m → f a == f' a) : map f m == map f' m := sorry theorem eq_of_mem_map_const {α : Type u_1} {β : Type u_2} {b₁ : β} {b₂ : β} {l : List α} (h : b₁ ∈ map (function.const α b₂) ↑l) : b₁ = b₂ := eq_of_mem_repeat (eq.mp (Eq._oldrec (Eq.refl (b₁ ∈ map (function.const α b₂) ↑l)) (map_const (↑l) b₂)) h) @[simp] theorem map_le_map {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} {t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h fun (l₁ l₂ : List α) (h : l₁ <+ l₂) => list.sublist.subperm (list.sublist.map f h) @[simp] theorem map_subset_map {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} {t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := sorry /-! ### `multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl {α : Type u_1} {β : Type u_2} (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (fun (l : List α) => list.foldl f b l) sorry @[simp] theorem foldl_zero {α : Type u_1} {β : Type u_2} (f : β → α → β) (H : right_commutative f) (b : β) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons {α : Type u_1} {β : Type u_2} (f : β → α → β) (H : right_commutative f) (b : β) (a : α) (s : multiset α) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s fun (l : List α) => rfl @[simp] theorem foldl_add {α : Type u_1} {β : Type u_2} (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) (t : multiset α) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.foldl_append f b l₁ l₂ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (fun (l : List α) => list.foldr f b l) sorry @[simp] theorem foldr_zero {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) (a : α) (s : multiset α) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s fun (l : List α) => rfl @[simp] theorem foldr_add {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) (t : multiset α) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.foldr_append f b l₁ l₂ @[simp] theorem coe_foldr {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) (l : List α) : foldr f H b ↑l = list.foldr f b l := rfl @[simp] theorem coe_foldl {α : Type u_1} {β : Type u_2} (f : β → α → β) (H : right_commutative f) (b : β) (l : List α) : foldl f H b ↑l = list.foldl f b l := rfl theorem coe_foldr_swap {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) (l : List α) : foldr f H b ↑l = list.foldl (fun (x : β) (y : α) => f y x) b l := Eq.trans (Eq.symm (congr_arg (foldr f H b) (coe_reverse l))) (list.foldr_reverse f b l) theorem foldr_swap {α : Type u_1} {β : Type u_2} (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (fun (x : β) (y : α) => f y x) (fun (x : β) (y z : α) => Eq.symm (H y z x)) b s := quot.induction_on s fun (l : List α) => coe_foldr_swap f H b l theorem foldl_swap {α : Type u_1} {β : Type u_2} (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (fun (x : α) (y : β) => f y x) (fun (x y : α) (z : β) => Eq.symm (H z x y)) b s := Eq.symm (foldr_swap (fun (y : α) (x : β) => f x y) (fun (x y : α) (z : β) => Eq.symm (H z x y)) b s) /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def sum {α : Type u_1} [add_comm_monoid α] : multiset α → α := foldr Add.add sorry 0 theorem prod_eq_foldr {α : Type u_1} [comm_monoid α] (s : multiset α) : prod s = foldr Mul.mul (fun (x y z : α) => eq.mpr (id (Eq.trans ((fun (a a_1 : α) (e_1 : a = a_1) (ᾰ ᾰ_1 : α) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (x * (y * z)) (x * (y * z)) (Eq.refl (x * (y * z))) (y * (x * z)) (x * (y * z)) (mul_left_comm y x z)) (propext (eq_self_iff_true (x * (y * z)))))) trivial) 1 s := rfl theorem sum_eq_foldl {α : Type u_1} [add_comm_monoid α] (s : multiset α) : sum s = foldl Add.add (fun (x y z : α) => eq.mpr (id (Eq.trans ((fun (a a_1 : α) (e_1 : a = a_1) (ᾰ ᾰ_1 : α) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (x + y + z) (x + y + z) (Eq.refl (x + y + z)) (x + z + y) (x + y + z) (add_right_comm x z y)) (propext (eq_self_iff_true (x + y + z))))) trivial) 0 s := sorry @[simp] theorem coe_sum {α : Type u_1} [add_comm_monoid α] (l : List α) : sum ↑l = list.sum l := sum_eq_foldl ↑l @[simp] theorem sum_zero {α : Type u_1} [add_comm_monoid α] : sum 0 = 0 := rfl @[simp] theorem sum_cons {α : Type u_1} [add_comm_monoid α] (a : α) (s : multiset α) : sum (a ::ₘ s) = a + sum s := foldr_cons Add.add sum._proof_1 0 a s theorem sum_singleton {α : Type u_1} [add_comm_monoid α] (a : α) : sum (a ::ₘ 0) = a := sorry @[simp] theorem sum_add {α : Type u_1} [add_comm_monoid α] (s : multiset α) (t : multiset α) : sum (s + t) = sum s + sum t := sorry protected instance sum.is_add_monoid_hom {α : Type u_1} [add_comm_monoid α] : is_add_monoid_hom sum := is_add_monoid_hom.mk sum_zero theorem prod_smul {α : Type u_1} [comm_monoid α] (m : multiset α) (n : ℕ) : prod (n •ℕ m) = prod m ^ n := sorry @[simp] theorem prod_repeat {α : Type u_1} [comm_monoid α] (a : α) (n : ℕ) : prod (repeat a n) = a ^ n := sorry @[simp] theorem sum_repeat {α : Type u_1} [add_comm_monoid α] (a : α) (n : ℕ) : sum (repeat a n) = n •ℕ a := prod_repeat theorem prod_map_one {α : Type u_1} {γ : Type u_3} [comm_monoid γ] {m : multiset α} : prod (map (fun (a : α) => 1) m) = 1 := sorry theorem sum_map_zero {α : Type u_1} {γ : Type u_3} [add_comm_monoid γ] {m : multiset α} : sum (map (fun (a : α) => 0) m) = 0 := sorry @[simp] theorem sum_map_add {α : Type u_1} {γ : Type u_3} [add_comm_monoid γ] {m : multiset α} {f : α → γ} {g : α → γ} : sum (map (fun (a : α) => f a + g a) m) = sum (map f m) + sum (map g m) := sorry theorem prod_map_prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (map (fun (a : α) => prod (map (fun (b : β) => f a b) n)) m) = prod (map (fun (b : β) => prod (map (fun (a : α) => f a b) m)) n) := sorry theorem sum_map_sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : sum (map (fun (a : α) => sum (map (fun (b : β) => f a b) n)) m) = sum (map (fun (b : β) => sum (map (fun (a : α) => f a b) m)) n) := prod_map_prod_map theorem sum_map_mul_left {α : Type u_1} {β : Type u_2} [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (map (fun (a : α) => b * f a) s) = b * sum (map f s) := sorry theorem sum_map_mul_right {α : Type u_1} {β : Type u_2} [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (map (fun (a : α) => f a * b) s) = sum (map f s) * b := sorry theorem prod_ne_zero {R : Type u_1} [comm_semiring R] [no_zero_divisors R] [nontrivial R] {m : multiset R} : (∀ (x : R), x ∈ m → x ≠ 0) → prod m ≠ 0 := sorry theorem prod_eq_zero {α : Type u_1} [comm_semiring α] {s : multiset α} (h : 0 ∈ s) : prod s = 0 := sorry theorem sum_hom {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [add_comm_monoid β] (s : multiset α) (f : α →+ β) : sum (map (⇑f) s) = coe_fn f (sum s) := sorry theorem prod_hom_rel {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀ {a : α} {b : β} {c : γ}, r b c → r (f a * b) (g a * c)) : r (prod (map f s)) (prod (map g s)) := sorry theorem dvd_prod {α : Type u_1} [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ prod s := sorry theorem prod_dvd_prod {α : Type u_1} [comm_monoid α] {s : multiset α} {t : multiset α} (h : s ≤ t) : prod s ∣ prod t := sorry theorem prod_eq_zero_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] {s : multiset α} : prod s = 0 ↔ 0 ∈ s := sorry theorem sum_nonneg {α : Type u_1} [ordered_add_comm_monoid α] {m : multiset α} : (∀ (x : α), x ∈ m → 0 ≤ x) → 0 ≤ sum m := sorry theorem single_le_prod {α : Type u_1} [ordered_comm_monoid α] {m : multiset α} : (∀ (x : α), x ∈ m → 1 ≤ x) → ∀ (x : α), x ∈ m → x ≤ prod m := sorry theorem all_one_of_le_one_le_of_prod_eq_one {α : Type u_1} [ordered_comm_monoid α] {m : multiset α} : (∀ (x : α), x ∈ m → 1 ≤ x) → prod m = 1 → ∀ (x : α), x ∈ m → x = 1 := sorry theorem sum_eq_zero_iff {α : Type u_1} [canonically_ordered_add_monoid α] {m : multiset α} : sum m = 0 ↔ ∀ (x : α), x ∈ m → x = 0 := sorry theorem le_sum_of_subadditive {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀ (x y : α), f (x + y) ≤ f x + f y) (s : multiset α) : f (sum s) ≤ sum (map f s) := sorry theorem abs_sum_le_sum_abs {α : Type u_1} [linear_ordered_field α] {s : multiset α} : abs (sum s) ≤ sum (map abs s) := le_sum_of_subadditive abs abs_zero abs_add s theorem dvd_sum {α : Type u_1} [comm_semiring α] {a : α} {s : multiset α} : (∀ (x : α), x ∈ s → a ∣ x) → a ∣ sum s := sorry @[simp] theorem sum_map_singleton {α : Type u_1} (s : multiset α) : sum (map (fun (a : α) => a ::ₘ 0) s) = s := sorry /-! ### Join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join {α : Type u_1} : multiset (multiset α) → multiset α := sum theorem coe_join {α : Type u_1} (L : List (List α)) : join ↑(list.map coe L) = ↑(list.join L) := sorry @[simp] theorem join_zero {α : Type u_1} : join 0 = 0 := rfl @[simp] theorem join_cons {α : Type u_1} (s : multiset α) (S : multiset (multiset α)) : join (s ::ₘ S) = s + join S := sum_cons s S @[simp] theorem join_add {α : Type u_1} (S : multiset (multiset α)) (T : multiset (multiset α)) : join (S + T) = join S + join T := sum_add S T @[simp] theorem mem_join {α : Type u_1} {a : α} {S : multiset (multiset α)} : a ∈ join S ↔ ∃ (s : multiset α), ∃ (H : s ∈ S), a ∈ s := sorry @[simp] theorem card_join {α : Type u_1} (S : multiset (multiset α)) : coe_fn card (join S) = sum (map (⇑card) S) := sorry /-! ### `multiset.bind` -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind {α : Type u_1} {β : Type u_2} (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind {α : Type u_1} {β : Type u_2} (l : List α) (f : α → List β) : (bind ↑l fun (a : α) => ↑(f a)) = ↑(list.bind l f) := sorry @[simp] theorem zero_bind {α : Type u_1} {β : Type u_2} (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind {α : Type u_1} {β : Type u_2} (a : α) (s : multiset α) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f := sorry @[simp] theorem add_bind {α : Type u_1} {β : Type u_2} (s : multiset α) (t : multiset α) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := sorry @[simp] theorem bind_zero {α : Type u_1} {β : Type u_2} (s : multiset α) : (bind s fun (a : α) => 0) = 0 := sorry @[simp] theorem bind_add {α : Type u_1} {β : Type u_2} (s : multiset α) (f : α → multiset β) (g : α → multiset β) : (bind s fun (a : α) => f a + g a) = bind s f + bind s g := sorry @[simp] theorem bind_cons {α : Type u_1} {β : Type u_2} (s : multiset α) (f : α → β) (g : α → multiset β) : (bind s fun (a : α) => f a ::ₘ g a) = map f s + bind s g := sorry @[simp] theorem mem_bind {α : Type u_1} {β : Type u_2} {b : β} {s : multiset α} {f : α → multiset β} : b ∈ bind s f ↔ ∃ (a : α), ∃ (H : a ∈ s), b ∈ f a := sorry @[simp] theorem card_bind {α : Type u_1} {β : Type u_2} (s : multiset α) (f : α → multiset β) : coe_fn card (bind s f) = sum (map (⇑card ∘ f) s) := sorry theorem bind_congr {α : Type u_1} {β : Type u_2} {f : α → multiset β} {g : α → multiset β} {m : multiset α} : (∀ (a : α), a ∈ m → f a = g a) → bind m f = bind m g := sorry theorem bind_hcongr {α : Type u_1} {β : Type u_2} {β' : Type u_2} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀ (a : α), a ∈ m → f a == f' a) : bind m f == bind m f' := sorry theorem map_bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m fun (a : α) => map f (n a) := sorry theorem bind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m fun (a : α) => n (f a) := sorry theorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : bind (bind s f) g = bind s fun (a : α) => bind (f a) g := sorry theorem bind_bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m fun (a : α) => bind n fun (b : β) => f a b) = bind n fun (b : β) => bind m fun (a : α) => f a b := sorry theorem bind_map_comm {α : Type u_1} {β : Type u_2} {γ : Type u_3} (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m fun (a : α) => map (fun (b : β) => f a b) n) = bind n fun (b : β) => map (fun (a : α) => f a b) m := sorry @[simp] theorem sum_bind {α : Type u_1} {β : Type u_2} [add_comm_monoid β] (s : multiset α) (t : α → multiset β) : sum (bind s t) = sum (map (fun (a : α) => sum (t a)) s) := sorry /-! ### Product of two `multiset`s -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product {α : Type u_1} {β : Type u_2} (s : multiset α) (t : multiset β) : multiset (α × β) := bind s fun (a : α) => map (Prod.mk a) t @[simp] theorem coe_product {α : Type u_1} {β : Type u_2} (l₁ : List α) (l₂ : List β) : product ↑l₁ ↑l₂ = ↑(list.product l₁ l₂) := sorry @[simp] theorem zero_product {α : Type u_1} {β : Type u_2} (t : multiset β) : product 0 t = 0 := rfl @[simp] theorem cons_product {α : Type u_1} {β : Type u_2} (a : α) (s : multiset α) (t : multiset β) : product (a ::ₘ s) t = map (Prod.mk a) t + product s t := sorry @[simp] theorem product_singleton {α : Type u_1} {β : Type u_2} (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a, b) ::ₘ 0 := rfl @[simp] theorem add_product {α : Type u_1} {β : Type u_2} (s : multiset α) (t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := sorry @[simp] theorem product_add {α : Type u_1} {β : Type u_2} (s : multiset α) (t : multiset β) (u : multiset β) : product s (t + u) = product s t + product s u := sorry @[simp] theorem mem_product {α : Type u_1} {β : Type u_2} {s : multiset α} {t : multiset β} {p : α × β} : p ∈ product s t ↔ prod.fst p ∈ s ∧ prod.snd p ∈ t := sorry @[simp] theorem card_product {α : Type u_1} {β : Type u_2} (s : multiset α) (t : multiset β) : coe_fn card (product s t) = coe_fn card s * coe_fn card t := sorry /-! ### Sigma multiset -/ /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma {α : Type u_1} {σ : α → Type u_4} (s : multiset α) (t : (a : α) → multiset (σ a)) : multiset (sigma fun (a : α) => σ a) := bind s fun (a : α) => map (sigma.mk a) (t a) @[simp] theorem coe_sigma {α : Type u_1} {σ : α → Type u_4} (l₁ : List α) (l₂ : (a : α) → List (σ a)) : (multiset.sigma ↑l₁ fun (a : α) => ↑(l₂ a)) = ↑(list.sigma l₁ l₂) := sorry @[simp] theorem zero_sigma {α : Type u_1} {σ : α → Type u_4} (t : (a : α) → multiset (σ a)) : multiset.sigma 0 t = 0 := rfl @[simp] theorem cons_sigma {α : Type u_1} {σ : α → Type u_4} (a : α) (s : multiset α) (t : (a : α) → multiset (σ a)) : multiset.sigma (a ::ₘ s) t = map (sigma.mk a) (t a) + multiset.sigma s t := sorry @[simp] theorem sigma_singleton {α : Type u_1} {β : Type u_2} (a : α) (b : α → β) : (multiset.sigma (a ::ₘ 0) fun (a : α) => b a ::ₘ 0) = sigma.mk a (b a) ::ₘ 0 := rfl @[simp] theorem add_sigma {α : Type u_1} {σ : α → Type u_4} (s : multiset α) (t : multiset α) (u : (a : α) → multiset (σ a)) : multiset.sigma (s + t) u = multiset.sigma s u + multiset.sigma t u := sorry @[simp] theorem sigma_add {α : Type u_1} {σ : α → Type u_4} (s : multiset α) (t : (a : α) → multiset (σ a)) (u : (a : α) → multiset (σ a)) : (multiset.sigma s fun (a : α) => t a + u a) = multiset.sigma s t + multiset.sigma s u := sorry @[simp] theorem mem_sigma {α : Type u_1} {σ : α → Type u_4} {s : multiset α} {t : (a : α) → multiset (σ a)} {p : sigma fun (a : α) => σ a} : p ∈ multiset.sigma s t ↔ sigma.fst p ∈ s ∧ sigma.snd p ∈ t (sigma.fst p) := sorry @[simp] theorem card_sigma {α : Type u_1} {σ : α → Type u_4} (s : multiset α) (t : (a : α) → multiset (σ a)) : coe_fn card (multiset.sigma s t) = sum (map (fun (a : α) => coe_fn card (t a)) s) := sorry /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (s : multiset α) : (∀ (a : α), a ∈ s → p a) → multiset β := quot.rec_on s (fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => ↑(list.pmap f l H)) sorry @[simp] theorem coe_pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (l : List α) (H : ∀ (a : α), a ∈ l → p a) : pmap f (↑l) H = ↑(list.pmap f l H) := rfl @[simp] theorem pmap_zero {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (h : ∀ (a : α), a ∈ 0 → p a) : pmap f 0 h = 0 := rfl @[simp] theorem pmap_cons {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (a : α) (m : multiset α) (h : ∀ (b : α), b ∈ a ::ₘ m → p b) : pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m fun (a_1 : α) (ha : a_1 ∈ m) => h a_1 (mem_cons_of_mem ha) := quotient.induction_on m fun (l : List α) (h : ∀ (b : α), b ∈ a ::ₘ quotient.mk l → p b) => rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach {α : Type u_1} (s : multiset α) : multiset (Subtype fun (x : α) => x ∈ s) := pmap Subtype.mk s sorry @[simp] theorem coe_attach {α : Type u_1} (l : List α) : attach ↑l = ↑(list.attach l) := rfl theorem sizeof_lt_sizeof_of_mem {α : Type u_1} [SizeOf α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := sorry theorem pmap_eq_map {α : Type u_1} {β : Type u_2} (p : α → Prop) (f : α → β) (s : multiset α) (H : ∀ (a : α), a ∈ s → p a) : pmap (fun (a : α) (_x : p a) => f a) s H = map f s := quot.induction_on s fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => congr_arg coe (list.pmap_eq_map p f l H) theorem pmap_congr {α : Type u_1} {β : Type u_2} {p : α → Prop} {q : α → Prop} {f : (a : α) → p a → β} {g : (a : α) → q a → β} (s : multiset α) {H₁ : ∀ (a : α), a ∈ s → p a} {H₂ : ∀ (a : α), a ∈ s → q a} (h : ∀ (a : α) (h₁ : p a) (h₂ : q a), f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := sorry theorem map_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (g : β → γ) (f : (a : α) → p a → β) (s : multiset α) (H : ∀ (a : α), a ∈ s → p a) : map g (pmap f s H) = pmap (fun (a : α) (h : p a) => g (f a h)) s H := quot.induction_on s fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => congr_arg coe (list.map_pmap g f l H) theorem pmap_eq_map_attach {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (s : multiset α) (H : ∀ (a : α), a ∈ s → p a) : pmap f s H = map (fun (x : Subtype fun (x : α) => x ∈ s) => f (subtype.val x) (H (subtype.val x) (subtype.property x))) (attach s) := quot.induction_on s fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => congr_arg coe (list.pmap_eq_map_attach f l H) theorem attach_map_val {α : Type u_1} (s : multiset α) : map subtype.val (attach s) = s := quot.induction_on s fun (l : List α) => congr_arg coe (list.attach_map_val l) @[simp] theorem mem_attach {α : Type u_1} (s : multiset α) (x : Subtype fun (x : α) => x ∈ s) : x ∈ attach s := quot.induction_on s fun (l : List α) => list.mem_attach l @[simp] theorem mem_pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {s : multiset α} {H : ∀ (a : α), a ∈ s → p a} {b : β} : b ∈ pmap f s H ↔ ∃ (a : α), ∃ (h : a ∈ s), f a (H a h) = b := quot.induction_on s (fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => list.mem_pmap) H @[simp] theorem card_pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (s : multiset α) (H : ∀ (a : α), a ∈ s → p a) : coe_fn card (pmap f s H) = coe_fn card s := quot.induction_on s (fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => list.length_pmap) H @[simp] theorem card_attach {α : Type u_1} {m : multiset α} : coe_fn card (attach m) = coe_fn card m := card_pmap Subtype.mk m (attach._proof_1 m) @[simp] theorem attach_zero {α : Type u_1} : attach 0 = 0 := rfl theorem attach_cons {α : Type u_1} (a : α) (m : multiset α) : attach (a ::ₘ m) = { val := a, property := mem_cons_self a m } ::ₘ map (fun (p : Subtype fun (x : α) => x ∈ m) => { val := subtype.val p, property := mem_cons_of_mem (subtype.property p) }) (attach m) := sorry protected def decidable_forall_multiset {α : Type u_1} {m : multiset α} {p : α → Prop} [hp : (a : α) → Decidable (p a)] : Decidable (∀ (a : α), a ∈ m → p a) := quotient.rec_on_subsingleton m fun (l : List α) => decidable_of_iff (∀ (a : α), a ∈ l → p a) sorry protected instance decidable_dforall_multiset {α : Type u_1} {m : multiset α} {p : (a : α) → a ∈ m → Prop} [hp : (a : α) → (h : a ∈ m) → Decidable (p a h)] : Decidable (∀ (a : α) (h : a ∈ m), p a h) := decidable_of_decidable_of_iff multiset.decidable_forall_multiset sorry /-- decidable equality for functions whose domain is bounded by multisets -/ protected instance decidable_eq_pi_multiset {α : Type u_1} {m : multiset α} {β : α → Type u_2} [h : (a : α) → DecidableEq (β a)] : DecidableEq ((a : α) → a ∈ m → β a) := fun (f g : (a : α) → a ∈ m → β a) => decidable_of_iff (∀ (a : α) (h : a ∈ m), f a h = g a h) sorry def decidable_exists_multiset {α : Type u_1} {m : multiset α} {p : α → Prop} [decidable_pred p] : Decidable (∃ (x : α), ∃ (H : x ∈ m), p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem protected instance decidable_dexists_multiset {α : Type u_1} {m : multiset α} {p : (a : α) → a ∈ m → Prop} [hp : (a : α) → (h : a ∈ m) → Decidable (p a h)] : Decidable (∃ (a : α), ∃ (h : a ∈ m), p a h) := decidable_of_decidable_of_iff decidable_exists_multiset sorry /-! ### Subtraction -/ /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : multiset α := quotient.lift_on₂ s t (fun (l₁ l₂ : List α) => ↑(list.diff l₁ l₂)) sorry protected instance has_sub {α : Type u_1} [DecidableEq α] : Sub (multiset α) := { sub := multiset.sub } @[simp] theorem coe_sub {α : Type u_1} [DecidableEq α] (s : List α) (t : List α) : ↑s - ↑t = ↑(list.diff s t) := rfl theorem sub_eq_fold_erase {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s - t = foldl erase erase_comm s t := sorry @[simp] theorem sub_zero {α : Type u_1} [DecidableEq α] (s : multiset α) : s - 0 = s := quot.induction_on s fun (l : List α) => rfl @[simp] theorem sub_cons {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : s - a ::ₘ t = erase s a - t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => congr_arg coe (list.diff_cons l₁ l₂ a) theorem add_sub_of_le {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : s ≤ t) : s + (t - s) = t := sorry theorem sub_add' {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} : s - (t + u) = s - t - u := quotient.induction_on₃ s t u fun (l₁ l₂ l₃ : List α) => congr_arg coe (list.diff_append l₁ l₂ l₃) theorem sub_add_cancel {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : t ≤ s) : s - t + t = s := eq.mpr (id (Eq._oldrec (Eq.refl (s - t + t = s)) (add_comm (s - t) t))) (eq.mpr (id (Eq._oldrec (Eq.refl (t + (s - t) = s)) (add_sub_of_le h))) (Eq.refl s)) @[simp] theorem add_sub_cancel_left {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s + t - s = t := sorry @[simp] theorem add_sub_cancel {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s + t - t = s := eq.mpr (id (Eq._oldrec (Eq.refl (s + t - t = s)) (add_comm s t))) (eq.mpr (id (Eq._oldrec (Eq.refl (t + s - t = s)) (add_sub_cancel_left t s))) (Eq.refl s)) theorem sub_le_sub_right {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : s ≤ t) (u : multiset α) : s - u ≤ t - u := sorry theorem sub_le_sub_left {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : s ≤ t) (u : multiset α) : u - t ≤ u - s := sorry theorem sub_le_iff_le_add {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} : s - t ≤ u ↔ s ≤ u + t := sorry theorem le_sub_add {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ≤ s - t + t := iff.mp sub_le_iff_le_add (le_refl (s - t)) theorem sub_le_self {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s - t ≤ s := iff.mpr sub_le_iff_le_add (le_add_right s t) @[simp] theorem card_sub {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : t ≤ s) : coe_fn card (s - t) = coe_fn card s - coe_fn card t := sorry /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : multiset α := s - t + t protected instance has_union {α : Type u_1} [DecidableEq α] : has_union (multiset α) := has_union.mk union theorem union_def {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ≤ s ∪ t := le_sub_add s t theorem le_union_right {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : t ≤ s ∪ t := le_add_left t (s - t) theorem eq_union_left {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : s ≤ t) (u : multiset α) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h u) u theorem union_le {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := eq.mpr (id (Eq._oldrec (Eq.refl (s ∪ t ≤ u)) (Eq.symm (eq_union_left h₂)))) (union_le_union_right h₁ t) @[simp] theorem mem_union {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {a : α} : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := { mp := fun (h : a ∈ s ∪ t) => or.imp_left (mem_of_le (sub_le_self s t)) (iff.mp mem_add h), mpr := Or._oldrec (mem_of_le (le_union_left s t)) (mem_of_le (le_union_right s t)) } @[simp] theorem map_union {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] {f : α → β} (finj : function.injective f) {s : multiset α} {t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := sorry /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : multiset α := quotient.lift_on₂ s t (fun (l₁ l₂ : List α) => ↑(list.bag_inter l₁ l₂)) sorry protected instance has_inter {α : Type u_1} [DecidableEq α] : has_inter (multiset α) := has_inter.mk inter @[simp] theorem inter_zero {α : Type u_1} [DecidableEq α] (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s fun (l : List α) => congr_arg coe (list.bag_inter_nil l) @[simp] theorem zero_inter {α : Type u_1} [DecidableEq α] (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s fun (l : List α) => congr_arg coe (list.nil_bag_inter l) @[simp] theorem cons_inter_of_pos {α : Type u_1} [DecidableEq α] {a : α} (s : multiset α) {t : multiset α} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ erase t a := quotient.induction_on₂ s t fun (l₁ l₂ : List α) (h : a ∈ quotient.mk l₂) => congr_arg coe (list.cons_bag_inter_of_pos l₁ h) @[simp] theorem cons_inter_of_neg {α : Type u_1} [DecidableEq α] {a : α} (s : multiset α) {t : multiset α} : ¬a ∈ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) (h : ¬a ∈ quotient.mk l₂) => congr_arg coe (list.cons_bag_inter_of_neg l₁ h) theorem inter_le_left {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.sublist.subperm (list.bag_inter_sublist_left l₁ l₂) theorem inter_le_right {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∩ t ≤ t := sorry theorem le_inter {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := sorry @[simp] theorem mem_inter {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {a : α} : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := sorry protected instance lattice {α : Type u_1} [DecidableEq α] : lattice (multiset α) := lattice.mk has_union.union partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry has_inter.inter sorry sorry sorry @[simp] theorem sup_eq_union {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff protected instance semilattice_inf_bot {α : Type u_1} [DecidableEq α] : semilattice_inf_bot (multiset α) := semilattice_inf_bot.mk 0 lattice.le lattice.lt sorry sorry sorry zero_le lattice.inf sorry sorry sorry theorem union_comm {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : s ≤ t) : s ∪ t = t := eq.mpr (id (Eq._oldrec (Eq.refl (s ∪ t = t)) (union_comm s t))) (eq.mpr (id (Eq._oldrec (Eq.refl (t ∪ s = t)) (eq_union_left h))) (Eq.refl t)) theorem union_le_union_left {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} (h : s ≤ t) (u : multiset α) : u ∪ s ≤ u ∪ t := sup_le_sup_left h u theorem union_le_add {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right s t) (le_add_left t s) theorem union_add_distrib {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) (u : multiset α) : s ∪ t + u = s + u ∪ (t + u) := sorry theorem add_union_distrib {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) (u : multiset α) : s + (t ∪ u) = s + t ∪ (s + u) := sorry theorem cons_union_distrib {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : a ::ₘ (s ∪ t) = a ::ₘ s ∪ a ::ₘ t := sorry theorem inter_add_distrib {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) (u : multiset α) : s ∩ t + u = (s + u) ∩ (t + u) := sorry theorem add_inter_distrib {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) (u : multiset α) : s + t ∩ u = (s + t) ∩ (s + u) := sorry theorem cons_inter_distrib {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : a ::ₘ s ∩ t = (a ::ₘ s) ∩ (a ::ₘ t) := sorry theorem union_add_inter {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s ∪ t + s ∩ t = s + t := sorry theorem sub_add_inter {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s - t + s ∩ t = s := sorry theorem sub_inter {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : s - s ∩ t = s - t := add_right_cancel (eq.mpr (id (Eq._oldrec (Eq.refl (s - s ∩ t + s ∩ t = s - t + s ∩ t)) (sub_add_inter s t))) (eq.mpr (id (Eq._oldrec (Eq.refl (s - s ∩ t + s ∩ t = s)) (sub_add_cancel (inter_le_left s t)))) (Eq.refl s))) /-! ### `multiset.filter` -/ /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (fun (l : List α) => ↑(list.filter p l)) sorry @[simp] theorem coe_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : List α) : filter p ↑l = ↑(list.filter p l) := rfl @[simp] theorem filter_zero {α : Type u_1} (p : α → Prop) [decidable_pred p] : filter p 0 = 0 := rfl theorem filter_congr {α : Type u_1} {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ (x : α), x ∈ s → (p x ↔ q x)) → filter p s = filter q s := quot.induction_on s fun (l : List α) (h : ∀ (x : α), x ∈ Quot.mk setoid.r l → (p x ↔ q x)) => congr_arg coe (list.filter_congr h) @[simp] theorem filter_add {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) (t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => congr_arg coe (list.filter_append l₁ l₂) @[simp] theorem filter_le {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) : filter p s ≤ s := quot.induction_on s fun (l : List α) => list.sublist.subperm (list.filter_sublist l) @[simp] theorem filter_subset {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) : filter p s ⊆ s := subset_of_le (filter_le p s) theorem filter_le_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] {s : multiset α} {t : multiset α} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h fun (l₁ l₂ : List α) (h : l₁ <+ l₂) => list.sublist.subperm (list.filter_sublist_filter p h) @[simp] theorem filter_cons_of_pos {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} (s : multiset α) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s fun (l : List α) (h : p a) => congr_arg coe (list.filter_cons_of_pos l h) @[simp] theorem filter_cons_of_neg {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} (s : multiset α) : ¬p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s fun (l : List α) (h : ¬p a) => congr_arg coe (list.filter_cons_of_neg l h) @[simp] theorem mem_filter {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {s : multiset α} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s fun (l : List α) => list.mem_filter theorem of_mem_filter {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {s : multiset α} (h : a ∈ filter p s) : p a := and.right (iff.mp mem_filter h) theorem mem_of_mem_filter {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {s : multiset α} (h : a ∈ filter p s) : a ∈ s := and.left (iff.mp mem_filter h) theorem mem_filter_of_mem {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {l : multiset α} (m : a ∈ l) (h : p a) : a ∈ filter p l := iff.mpr mem_filter { left := m, right := h } theorem filter_eq_self {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : multiset α} : filter p s = s ↔ ∀ (a : α), a ∈ s → p a := sorry theorem filter_eq_nil {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : multiset α} : filter p s = 0 ↔ ∀ (a : α), a ∈ s → ¬p a := sorry theorem le_filter {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : multiset α} {t : multiset α} : s ≤ filter p t ↔ s ≤ t ∧ ∀ (a : α), a ∈ s → p a := sorry @[simp] theorem filter_sub {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s : multiset α) (t : multiset α) : filter p (s - t) = filter p s - filter p t := sorry @[simp] theorem filter_union {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s : multiset α) (t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := sorry @[simp] theorem filter_inter {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s : multiset α) (t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := sorry @[simp] theorem filter_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (q : α → Prop) [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (fun (a : α) => p a ∧ q a) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_filter p q l) theorem filter_add_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (q : α → Prop) [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (fun (a : α) => p a ∨ q a) s + filter (fun (a : α) => p a ∧ q a) s := sorry theorem filter_add_not {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) : filter p s + filter (fun (a : α) => ¬p a) s = s := sorry /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) (s : multiset α) : multiset β := quot.lift_on s (fun (l : List α) => ↑(list.filter_map f l)) sorry @[simp] theorem coe_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) (l : List α) : filter_map f ↑l = ↑(list.filter_map f l) := rfl @[simp] theorem filter_map_zero {α : Type u_1} {β : Type u_2} (f : α → Option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {α : Type u_1} {β : Type u_2} {f : α → Option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_map_cons_none a l h) @[simp] theorem filter_map_cons_some {α : Type u_1} {β : Type u_2} (f : α → Option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_map_cons_some f a l h) theorem filter_map_eq_map {α : Type u_1} {β : Type u_2} (f : α → β) : filter_map (some ∘ f) = map f := funext fun (s : multiset α) => quot.induction_on s fun (l : List α) => congr_arg coe (congr_fun (list.filter_map_eq_map f) l) theorem filter_map_eq_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext fun (s : multiset α) => quot.induction_on s fun (l : List α) => congr_arg coe (congr_fun (list.filter_map_eq_filter p) l) theorem filter_map_filter_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → Option β) (g : β → Option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (fun (x : α) => option.bind (f x) g) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_map_filter_map f g l) theorem map_filter_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → Option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (fun (x : α) => option.map g (f x)) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.map_filter_map f g l) theorem filter_map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : β → Option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_map_map f g l) theorem filter_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (fun (x : α) => option.filter p (f x)) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_filter_map f p l) theorem filter_map_filter {α : Type u_1} {β : Type u_2} (p : α → Prop) [decidable_pred p] (f : α → Option β) (s : multiset α) : filter_map f (filter p s) = filter_map (fun (x : α) => ite (p x) (f x) none) s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_map_filter p f l) @[simp] theorem filter_map_some {α : Type u_1} (s : multiset α) : filter_map some s = s := quot.induction_on s fun (l : List α) => congr_arg coe (list.filter_map_some l) @[simp] theorem mem_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ (a : α), a ∈ s ∧ f a = some b := quot.induction_on s fun (l : List α) => list.mem_filter_map f l theorem map_filter_map_of_inv {α : Type u_1} {β : Type u_2} (f : α → Option β) (g : β → α) (H : ∀ (x : α), option.map g (f x) = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s fun (l : List α) => congr_arg coe (list.map_filter_map_of_inv f g H l) theorem filter_map_le_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) {s : multiset α} {t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h fun (l₁ l₂ : List α) (h : l₁ <+ l₂) => list.sublist.subperm (list.sublist.filter_map f h) /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (list.countp p) sorry @[simp] theorem coe_countp {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : List α) : countp p ↑l = list.countp p l := rfl @[simp] theorem countp_zero {α : Type u_1} (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} (s : multiset α) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s (list.countp_cons_of_pos p) @[simp] theorem countp_cons_of_neg {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} (s : multiset α) : ¬p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s (list.countp_cons_of_neg p) theorem countp_eq_card_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) : countp p s = coe_fn card (filter p s) := quot.induction_on s fun (l : List α) => list.countp_eq_length_filter p l @[simp] theorem countp_add {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : multiset α) (t : multiset α) : countp p (s + t) = countp p s + countp p t := sorry protected instance countp.is_add_monoid_hom {α : Type u_1} (p : α → Prop) [decidable_pred p] : is_add_monoid_hom (countp p) := is_add_monoid_hom.mk (countp_zero p) @[simp] theorem countp_sub {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] {s : multiset α} {t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := sorry theorem countp_le_of_le {α : Type u_1} (p : α → Prop) [decidable_pred p] {s : multiset α} {t : multiset α} (h : s ≤ t) : countp p s ≤ countp p t := sorry @[simp] theorem countp_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (q : α → Prop) [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (fun (a : α) => p a ∧ q a) s := sorry theorem countp_pos {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : multiset α} : 0 < countp p s ↔ ∃ (a : α), ∃ (H : a ∈ s), p a := sorry theorem countp_pos_of_mem {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : multiset α} {a : α} (h : a ∈ s) (pa : p a) : 0 < countp p s := iff.mpr countp_pos (Exists.intro a (Exists.intro h pa)) /-! ### Multiplicity of an element -/ /-- `count a s` is the multiplicity of `a` in `s`. -/ def count {α : Type u_1} [DecidableEq α] (a : α) : multiset α → ℕ := countp (Eq a) @[simp] theorem coe_count {α : Type u_1} [DecidableEq α] (a : α) (l : List α) : count a ↑l = list.count a l := coe_countp (Eq a) l @[simp] theorem count_zero {α : Type u_1} [DecidableEq α] (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : count a (a ::ₘ s) = Nat.succ (count a s) := countp_cons_of_pos s rfl @[simp] theorem count_cons_of_ne {α : Type u_1} [DecidableEq α] {a : α} {b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg s h theorem count_le_of_le {α : Type u_1} [DecidableEq α] (a : α) {s : multiset α} {t : multiset α} : s ≤ t → count a s ≤ count a t := countp_le_of_le (Eq a) theorem count_le_count_cons {α : Type u_1} [DecidableEq α] (a : α) (b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le a (le_cons_self s b) theorem count_cons {α : Type u_1} [DecidableEq α] (a : α) (b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + ite (a = b) 1 0 := sorry theorem count_singleton {α : Type u_1} [DecidableEq α] (a : α) : count a (a ::ₘ 0) = 1 := sorry @[simp] theorem count_add {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : count a (s + t) = count a s + count a t := countp_add (Eq a) protected instance count.is_add_monoid_hom {α : Type u_1} [DecidableEq α] (a : α) : is_add_monoid_hom (count a) := countp.is_add_monoid_hom (Eq a) @[simp] theorem count_smul {α : Type u_1} [DecidableEq α] (a : α) (n : ℕ) (s : multiset α) : count a (n •ℕ s) = n * count a s := sorry theorem count_pos {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := sorry @[simp] theorem count_eq_zero_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} (h : ¬a ∈ s) : count a s = 0 := by_contradiction fun (h' : ¬count a s = 0) => h (iff.mp count_pos (nat.pos_of_ne_zero h')) @[simp] theorem count_eq_zero {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : count a s = 0 ↔ ¬a ∈ s := iff.mp iff_not_comm (iff.trans (iff.symm count_pos) pos_iff_ne_zero) theorem count_ne_zero {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := sorry @[simp] theorem count_repeat_self {α : Type u_1} [DecidableEq α] (a : α) (n : ℕ) : count a (repeat a n) = n := sorry theorem count_repeat {α : Type u_1} [DecidableEq α] (a : α) (b : α) (n : ℕ) : count a (repeat b n) = ite (a = b) n 0 := sorry @[simp] theorem count_erase_self {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : count a (erase s a) = Nat.pred (count a s) := sorry @[simp] theorem count_erase_of_ne {α : Type u_1} [DecidableEq α] {a : α} {b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := sorry @[simp] theorem count_sub {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : count a (s - t) = count a s - count a t := sorry @[simp] theorem count_union {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := sorry @[simp] theorem count_inter {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) (t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := sorry theorem count_sum {α : Type u_1} {β : Type u_2} [DecidableEq α] {m : multiset β} {f : β → multiset α} {a : α} : count a (sum (map f m)) = sum (map (fun (b : β) => count a (f b)) m) := sorry theorem count_bind {α : Type u_1} {β : Type u_2} [DecidableEq α] {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (map (fun (b : β) => count a (f b)) m) := count_sum theorem le_count_iff_repeat_le {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s fun (l : List α) => iff.trans list.le_count_iff_repeat_sublist (iff.symm repeat_le_coe) @[simp] theorem count_filter_of_pos {α : Type u_1} [DecidableEq α] {p : α → Prop} [decidable_pred p] {a : α} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s fun (l : List α) => list.count_filter h @[simp] theorem count_filter_of_neg {α : Type u_1} [DecidableEq α] {p : α → Prop} [decidable_pred p] {a : α} {s : multiset α} (h : ¬p a) : count a (filter p s) = 0 := count_eq_zero_of_not_mem fun (t : a ∈ filter p s) => h (of_mem_filter t) theorem ext {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : s = t ↔ ∀ (a : α), count a s = count a t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => iff.trans quotient.eq list.perm_iff_count theorem ext' {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : (∀ (a : α), count a s = count a t) → s = t := iff.mpr ext @[simp] theorem coe_inter {α : Type u_1} [DecidableEq α] (s : List α) (t : List α) : ↑s ∩ ↑t = ↑(list.bag_inter s t) := sorry theorem le_iff_count {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : s ≤ t ↔ ∀ (a : α), count a s ≤ count a t := sorry protected instance distrib_lattice {α : Type u_1} [DecidableEq α] : distrib_lattice (multiset α) := distrib_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry sorry protected instance semilattice_sup_bot {α : Type u_1} [DecidableEq α] : semilattice_sup_bot (multiset α) := semilattice_sup_bot.mk 0 lattice.le lattice.lt sorry sorry sorry zero_le lattice.sup sorry sorry sorry @[simp] theorem mem_nsmul {α : Type u_1} {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n •ℕ s ↔ a ∈ s := sorry /-! ### Lift a relation to `multiset`s -/ /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ theorem rel_iff {α : Type u_1} {β : Type u_2} (r : α → β → Prop) : ∀ (ᾰ : multiset α) (ᾰ_1 : multiset β), rel r ᾰ ᾰ_1 ↔ ᾰ = 0 ∧ ᾰ_1 = 0 ∨ Exists fun {a : α} => Exists fun {b : β} => Exists fun {as : multiset α} => Exists fun {bs : multiset β} => r a b ∧ rel r as bs ∧ ᾰ = a ::ₘ as ∧ ᾰ_1 = b ::ₘ bs := sorry theorem rel_flip {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {s : multiset β} {t : multiset α} : rel (flip r) s t ↔ rel r t s := { mp := rel_flip_aux, mpr := rel_flip_aux } theorem rel_eq_refl {α : Type u_1} {s : multiset α} : rel Eq s s := multiset.induction_on s rel.zero fun (a : α) (s : multiset α) => rel.cons rfl theorem rel_eq {α : Type u_1} {s : multiset α} {t : multiset α} : rel Eq s t ↔ s = t := sorry theorem rel.mono {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {p : α → β → Prop} {s : multiset α} {t : multiset β} (h : ∀ (a : α) (b : β), r a b → p a b) (hst : rel r s t) : rel p s t := sorry theorem rel.add {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {s : multiset α} {t : multiset β} {u : multiset α} {v : multiset β} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := sorry theorem rel_flip_eq {α : Type u_1} {s : multiset α} {t : multiset α} : rel (fun (a b : α) => b = a) s t ↔ s = t := sorry @[simp] theorem rel_zero_left {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {b : multiset β} : rel r 0 b ↔ b = 0 := sorry @[simp] theorem rel_zero_right {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {a : multiset α} : rel r a 0 ↔ a = 0 := sorry theorem rel_cons_left {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {a : α} {as : multiset α} {bs : multiset β} : rel r (a ::ₘ as) bs ↔ ∃ (b : β), ∃ (bs' : multiset β), r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs' := sorry theorem rel_cons_right {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {as : multiset α} {b : β} {bs : multiset β} : rel r as (b ::ₘ bs) ↔ ∃ (a : α), ∃ (as' : multiset α), r a b ∧ rel r as' bs ∧ as = a ::ₘ as' := sorry theorem rel_add_left {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {as₀ : multiset α} {as₁ : multiset α} {bs : multiset β} : rel r (as₀ + as₁) bs ↔ ∃ (bs₀ : multiset β), ∃ (bs₁ : multiset β), rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁ := sorry theorem rel_add_right {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {as : multiset α} {bs₀ : multiset β} {bs₁ : multiset β} : rel r as (bs₀ + bs₁) ↔ ∃ (as₀ : multiset α), ∃ (as₁ : multiset α), rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁ := sorry theorem rel_map_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} {r : α → β → Prop} {s : multiset γ} {f : γ → α} {t : multiset β} : rel r (map f s) t ↔ rel (fun (a : γ) (b : β) => r (f a) b) s t := sorry theorem rel_map_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} {r : α → β → Prop} {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (map f t) ↔ rel (fun (a : α) (b : γ) => r a (f b)) s t := sorry theorem rel_join {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {s : multiset (multiset α)} {t : multiset (multiset β)} (h : rel (rel r) s t) : rel r (join s) (join t) := sorry theorem rel_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {r : α → β → Prop} {p : γ → δ → Prop} {s : multiset α} {t : multiset β} {f : α → γ} {g : β → δ} (h : relator.lift_fun r p f g) (hst : rel r s t) : rel p (map f s) (map g t) := eq.mpr (id (Eq._oldrec (Eq.refl (rel p (map f s) (map g t))) (propext rel_map_left))) (eq.mpr (id (Eq._oldrec (Eq.refl (rel (fun (a : α) (b : δ) => p (f a) b) s (map g t))) (propext rel_map_right))) (rel.mono h hst)) theorem rel_bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {r : α → β → Prop} {p : γ → δ → Prop} {s : multiset α} {t : multiset β} {f : α → multiset γ} {g : β → multiset δ} (h : relator.lift_fun r (rel p) f g) (hst : rel r s t) : rel p (bind s f) (bind t g) := rel_join (rel_map h hst) theorem card_eq_card_of_rel {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : coe_fn card s = coe_fn card t := sorry theorem exists_mem_of_rel_of_mem {α : Type u_1} {β : Type u_2} {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) {a : α} (ha : a ∈ s) : ∃ (b : β), ∃ (H : b ∈ t), r a b := sorry theorem map_eq_map {α : Type u_1} {β : Type u_2} {f : α → β} (hf : function.injective f) {s : multiset α} {t : multiset α} : map f s = map f t ↔ s = t := sorry theorem map_injective {α : Type u_1} {β : Type u_2} {f : α → β} (hf : function.injective f) : function.injective (map f) := fun (x y : multiset α) => iff.mp (map_eq_map hf) theorem map_mk_eq_map_mk_of_rel {α : Type u_1} {r : α → α → Prop} {s : multiset α} {t : multiset α} (hst : rel r s t) : map (Quot.mk r) s = map (Quot.mk r) t := sorry theorem exists_multiset_eq_map_quot_mk {α : Type u_1} {r : α → α → Prop} (s : multiset (Quot r)) : ∃ (t : multiset α), s = map (Quot.mk r) t := sorry theorem induction_on_multiset_quot {α : Type u_1} {r : α → α → Prop} {p : multiset (Quot r) → Prop} (s : multiset (Quot r)) : (∀ (s : multiset α), p (map (Quot.mk r) s)) → p s := sorry /-! ### Disjoint multisets -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint {α : Type u_1} (s : multiset α) (t : multiset α) := ∀ {a : α}, a ∈ s → a ∈ t → False @[simp] theorem coe_disjoint {α : Type u_1} (l₁ : List α) (l₂ : List α) : disjoint ↑l₁ ↑l₂ ↔ list.disjoint l₁ l₂ := iff.rfl theorem disjoint.symm {α : Type u_1} {s : multiset α} {t : multiset α} (d : disjoint s t) : disjoint t s := fun {a : α} (ᾰ : a ∈ t) (ᾰ_1 : a ∈ s) => idRhs False (d ᾰ_1 ᾰ) theorem disjoint_comm {α : Type u_1} {s : multiset α} {t : multiset α} : disjoint s t ↔ disjoint t s := { mp := disjoint.symm, mpr := disjoint.symm } theorem disjoint_left {α : Type u_1} {s : multiset α} {t : multiset α} : disjoint s t ↔ ∀ {a : α}, a ∈ s → ¬a ∈ t := iff.rfl theorem disjoint_right {α : Type u_1} {s : multiset α} {t : multiset α} : disjoint s t ↔ ∀ {a : α}, a ∈ t → ¬a ∈ s := disjoint_comm theorem disjoint_iff_ne {α : Type u_1} {s : multiset α} {t : multiset α} : disjoint s t ↔ ∀ (a : α), a ∈ s → ∀ (b : α), b ∈ t → a ≠ b := sorry theorem disjoint_of_subset_left {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := fun {a : α} (ᾰ : a ∈ s) => idRhs (a ∈ t → False) (d (h ᾰ)) theorem disjoint_of_subset_right {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := fun {a : α} (ᾰ : a ∈ s) (ᾰ_1 : a ∈ t) => idRhs False (d ᾰ (h ᾰ_1)) theorem disjoint_of_le_left {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint {α : Type u_1} (l : multiset α) : disjoint 0 l := fun {a : α} => idRhs (a ∈ [] → a ∈ l → False) (not.elim (list.not_mem_nil a)) @[simp] theorem singleton_disjoint {α : Type u_1} {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ ¬a ∈ l := sorry @[simp] theorem disjoint_singleton {α : Type u_1} {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ ¬a ∈ l := sorry @[simp] theorem disjoint_add_left {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := sorry @[simp] theorem disjoint_add_right {α : Type u_1} {s : multiset α} {t : multiset α} {u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := sorry @[simp] theorem disjoint_cons_left {α : Type u_1} {a : α} {s : multiset α} {t : multiset α} : disjoint (a ::ₘ s) t ↔ ¬a ∈ t ∧ disjoint s t := sorry @[simp] theorem disjoint_cons_right {α : Type u_1} {a : α} {s : multiset α} {t : multiset α} : disjoint s (a ::ₘ t) ↔ ¬a ∈ s ∧ disjoint s t := sorry theorem inter_eq_zero_iff_disjoint {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : s ∩ t = 0 ↔ disjoint s t := sorry @[simp] theorem disjoint_union_left {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := sorry @[simp] theorem disjoint_union_right {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} {u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := sorry theorem disjoint_map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (map f s) (map g t) ↔ ∀ (a : α), a ∈ s → ∀ (b : β), b ∈ t → f a ≠ g b := sorry /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise {α : Type u_1} (r : α → α → Prop) (m : multiset α) := ∃ (l : List α), m = ↑l ∧ list.pairwise r l theorem pairwise_coe_iff_pairwise {α : Type u_1} {r : α → α → Prop} (hr : symmetric r) {l : List α} : pairwise r ↑l ↔ list.pairwise r l := sorry end multiset namespace multiset /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def choose_x {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : multiset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : Subtype fun (a : α) => a ∈ l ∧ p a := quotient.rec_on l (fun (l' : List α) (ex_unique : exists_unique fun (a : α) => a ∈ quotient.mk l' ∧ p a) => list.choose_x p l' sorry) sorry /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : multiset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : α := ↑(choose_x p l hp) theorem choose_spec {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : multiset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := subtype.property (choose_x p l hp) theorem choose_mem {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : multiset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : choose p l hp ∈ l := and.left (choose_spec p l hp) theorem choose_property {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : multiset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : p (choose p l hp) := and.right (choose_spec p l hp) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv (α : Type u_1) [subsingleton α] : List α ≃ multiset α := equiv.mk coe (Quot.lift id sorry) sorry sorry end multiset theorem add_monoid_hom.map_multiset_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [add_comm_monoid β] (f : α →+ β) (s : multiset α) : coe_fn f (multiset.sum s) = multiset.sum (multiset.map (⇑f) s) := Eq.symm (multiset.sum_hom s f) end Mathlib
9085e8933a6b29a2f493539d5c64b11e5aabb832
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/EqnCompiler/MatchPattern.lean
c89ffd702d40b2a57ece4e49e1ce342f3712847c
[ "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
699
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.Attributes namespace Lean namespace EqnCompiler def mkMatchPatternAttr : IO TagAttribute := registerTagAttribute `matchPattern "mark that a definition can be used in a pattern (remark: the dependent pattern matching compiler will unfold the definition)" @[init mkMatchPatternAttr] constant matchPatternAttr : TagAttribute := arbitrary _ @[export lean_has_match_pattern_attribute] def hasMatchPatternAttribute (env : Environment) (n : Name) : Bool := matchPatternAttr.hasTag env n end EqnCompiler end Lean
3b031d1f2f6fb66b5c7f6437cdbc5ab76f285d28
367134ba5a65885e863bdc4507601606690974c1
/src/topology/path_connected.lean
d0546994fd64cf96f9bcb52f48e2276f1765420a
[ "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
34,293
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.instances.real import topology.algebra.ordered.proj_Icc /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `set.Icc_extend` that will extend any continuous map `γ : I → X` into a continuous map `Icc_extend zero_le_one γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter open filter set function variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*} /-! ### The unit interval -/ local notation `I` := Icc (0 : ℝ) 1 lemma Icc_zero_one_symm {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance I_has_zero : has_zero I := ⟨⟨0, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_zero : ((0 : I) : ℝ) = 0 := rfl instance I_has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_one : ((1 : I) : ℝ) = 1 := rfl /-- Unit interval central symmetry. -/ def I_symm : I → I := λ t, ⟨1 - t.val, Icc_zero_one_symm.mp t.property⟩ local notation `σ` := I_symm @[simp] lemma I_symm_zero : σ 0 = 1 := subtype.ext $ by simp [I_symm] @[simp] lemma I_symm_one : σ 1 = 0 := subtype.ext $ by simp [I_symm] @[continuity] lemma continuous_I_symm : continuous σ := by continuity! instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_inhabited_instance] structure path (x y : X) := (to_fun : I → X) (continuous' : continuous to_fun) (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) := ⟨_, path.to_fun⟩ @[ext] protected lemma path.ext {X : Type*} [topological_space X] {x y : X} : ∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂ | ⟨x, h11, h12, h13⟩ ⟨.(x), h21, h22, h23⟩ rfl := rfl namespace path @[simp] lemma coe_mk (f : I → X) (h₁ h₂ h₃) : ⇑(mk f h₁ h₂ h₃ : path x y) = f := rfl variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous' @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/ instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} : has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X := ⟨λ φ p, φ p.1 p.2⟩ /-- The constant path from a point to itself -/ @[refl] def refl (x : X) : path x x := { to_fun := λ t, x, continuous' := continuous_const, source' := rfl, target' := rfl } @[simp] lemma refl_range {X : Type*} [topological_space X] {a : X} : range (path.refl a) = {a} := by simp [path.refl, has_coe_to_fun.coe, coe_fn] /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous' := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } @[simp] lemma refl_symm {X : Type*} [topological_space X] {a : X} : (path.refl a).symm = path.refl a := by { ext, refl } @[simp] lemma symm_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.symm = range γ := begin ext x, simp only [ mem_range, path.symm, has_coe_to_fun.coe, coe_fn, I_symm, set_coe.exists, comp_app, subtype.coe_mk, subtype.val_eq_coe ], split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, Icc_zero_one_symm.mp hy, _⟩; convert hxy, simp end /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := Icc_extend zero_le_one γ lemma continuous_extend : continuous γ.extend := γ.continuous.Icc_extend @[simp] lemma extend_zero : γ.extend 0 = x := (Icc_extend_left _ _).trans γ.source @[simp] lemma extend_one : γ.extend 1 = y := (Icc_extend_right _ _).trans γ.target @[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ := Icc_extend_of_mem _ γ ht @[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend t = γ t := Icc_extend_coe _ γ t @[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.extend = range γ := Icc_extend_range _ γ lemma extend_of_le_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a := (Icc_extend_of_le_left _ _ ht).trans γ.source lemma extend_of_one_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b := (Icc_extend_of_right_le _ _ ht).trans γ.target @[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} : (path.refl a).extend = λ _, a := rfl /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous' := hf.comp_continuous continuous_subtype_coe subtype.prop, source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous' := begin refine (continuous.if_le _ _ continuous_id continuous_const (by norm_num)).comp continuous_subtype_coe, -- TODO: the following are provable by `continuity` but it is too slow exacts [γ.continuous_extend.comp (continuous_const.mul continuous_id), γ'.continuous_extend.comp ((continuous_const.mul continuous_id).sub continuous_const)] end, source' := by norm_num, target' := by norm_num } @[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} : (path.refl a).trans (path.refl a) = path.refl a := begin ext, simp only [path.trans, if_t_t, one_div, path.refl_extend], refl end lemma trans_range {X : Type*} [topological_space X] {a b c : X} (γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ := begin rw path.trans, apply eq_of_subset_of_subset, { rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩, by_cases h : t ≤ 1/2, { left, use [2*t, ⟨by linarith, by linarith⟩], rw ← γ₁.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_true] at hxt, exact hxt }, { right, use [2*t-1, ⟨by linarith, by linarith⟩], rw ← γ₂.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_false] at hxt, exact hxt } }, { rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩), { use ⟨t/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, have : t/2 ≤ 1/2 := by linarith, simp only [this, comp_app, if_true], ring, rwa γ₁.extend_extends }, { by_cases h : t = 0, { use ⟨1/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (@two_ne_zero ℝ _ _)], rw γ₁.extend_one, rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt }, { use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, change t ≠ 0 at h, have ht0 := lt_of_le_of_ne ht0 h.symm, have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith}, simp only [comp_app, if_false, this], ring, rwa γ₂.extend_extends } } } end /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous' := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous' := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X} (γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) : (γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl @[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X} (γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) : (γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).symm) := h.comp (continuous_id.prod_map continuous_I_symm) lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).extend) := h.comp (continuous_id.prod_map continuous_proj_Icc) lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b c : ι → X} (γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁) (γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) : continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) := begin have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁, have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂, simp only [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans, (∘)], refine continuous.if_le _ _ (continuous_subtype_coe.comp continuous_snd) continuous_const _, { change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))), exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) }, { change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))), exact h₂'.comp (continuous_id.prod_map $ (continuous_const.mul continuous_subtype_coe).sub continuous_const) }, { rintros st hst, simp [hst, mul_inv_cancel (@two_ne_zero ℝ _ _)] } end /-! #### Truncating a path -/ /-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the time interval `[t₀, t₁]` and stays still otherwise. -/ def truncate {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) := { to_fun := λ s, γ.extend (min (max s t₀) t₁), continuous' := γ.continuous_extend.comp ((continuous_subtype_coe.max continuous_const).min continuous_const), source' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃ h₄, { simp [γ.extend_of_le_zero h₁] }, { congr, linarith }, { have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂), simp [γ.extend_of_le_zero h₄, γ.extend_of_le_zero h₁] }, all_goals { refl } end, target' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃, { simp [γ.extend_of_one_le h₂] }, { refl }, { have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁), simp [γ.extend_of_one_le h₄, γ.extend_of_one_le (h₄.trans h₃)] }, { refl } end } /-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁` casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/ def truncate_of_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) := (γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl lemma truncate_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ := begin rw ← γ.extend_range, simp only [range_subset_iff, set_coe.exists, set_coe.forall], intros x hx, simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self] end /-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/ lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) := γ.continuous_extend.comp (((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min (continuous_fst.comp continuous_snd)) /- TODO : When `continuity` gets quicker, change the proof back to : `begin` `simp only [has_coe_to_fun.coe, coe_fn, path.truncate],` `continuity,` `exact continuous_subtype_coe` `end` -/ lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) := have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id, by convert γ.truncate_continuous_family.comp key @[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min, max], split_ifs with h₁ h₂; congr, linarith end @[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero := by convert γ.truncate_self 0; exact γ.extend_zero.symm @[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one := by convert γ.truncate_self 1; exact γ.extend_one.symm @[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) := begin ext x, rw cast_coe, have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2, rw [truncate, coe_mk, max_eq_left this.1, min_eq_left this.2, extend_extends'] end end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous' := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, (is_connected_range h.some_path.continuous).subset_connected_component ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x y x_in y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x y xU yU).mono (subset_union_left U V) }, { exact (hV.joined_in x y xV yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end lemma is_path_connected.exists_path_through_family {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) := begin let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩, obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s, { have hp' : ∀ i ≤ n, p' i ∈ s, { intros i hi, simp [p', nat.lt_succ_of_le hi, hp] }, clear_value p', clear hp p, induction n with n hn, { use (λ _, p' 0), { continuity }, { split, { rintros i hi, rw nat.le_zero_iff.mp hi, exact ⟨0, rfl⟩ }, { rw range_subset_iff, rintros x, exact hp' 0 (le_refl _) } } }, { rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩, rcases h.joined_in (p' n) (p' $ n+1) (hp' n n.le_succ) (hp' (n+1) $ le_refl _) with ⟨γ₁, hγ₁⟩, let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁, use γ, have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁, split, { rintros i hi, by_cases hi' : i ≤ n, { rw range_eq, left, exact hγ₀.1 i hi' }, { rw [not_le, ← nat.succ_le_iff] at hi', have : i = n.succ := by linarith, rw this, use 1, exact γ.target } }, { rw range_eq, apply union_subset hγ₀.2, rw range_subset_iff, exact hγ₁ } } }, have hpp' : ∀ k < n+1, p k = p' k, { intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast }, use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self), simp only [γ.cast_coe], refine and.intro hγ.2 _, rintros ⟨i, hi⟩, convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi, congr, ext, rw fin.coe_coe_of_lt hi, norm_cast end lemma is_path_connected.exists_path_through_family' {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := begin rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩, rcases hγ with ⟨h₁, h₂⟩, simp only [range, mem_set_of_eq] at h₂, rw range_subset_iff at h₁, choose! t ht using h₂, exact ⟨γ, t, h₁, ht⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) attribute [instance, priority 50] path_connected_space.nonempty lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y z y_in z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, inhabit X, refine ⟨default X, mem_univ _, _⟩, simpa using path_connected_space.joined (default X) }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end namespace path_connected_space variables [path_connected_space X] lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) : ∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩, exact ⟨γ, h⟩ end lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩, exact ⟨γ, t, h⟩ end end path_connected_space /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, inhabit X, let x₀ := default X, rw path_connected_space_iff_eq, use x₀, refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩, { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_sets_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z y hz $ mem_of_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (mem_nhds_sets h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_sets (mem_nhds_sets h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
7896c2ad2fd18ea65ecae7e056ca96202f01ed44
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/periodic.lean
46ee5dbca1e23c78fd34c34fd21ee2c7c5b6dea3
[ "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
18,262
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import algebra.field.opposite import algebra.module.basic import algebra.order.archimedean import data.int.parity import group_theory.coset /-! # Periodicity In this file we define and then prove facts about periodic and antiperiodic functions. ## Main definitions * `function.periodic`: A function `f` is *periodic* if `∀ x, f (x + c) = f x`. `f` is referred to as periodic with period `c` or `c`-periodic. * `function.antiperiodic`: A function `f` is *antiperiodic* if `∀ x, f (x + c) = -f x`. `f` is referred to as antiperiodic with antiperiod `c` or `c`-antiperiodic. Note that any `c`-antiperiodic function will necessarily also be `2*c`-periodic. ## Tags period, periodic, periodicity, antiperiodic -/ variables {α β γ : Type*} {f g : α → β} {c c₁ c₂ x : α} open_locale big_operators namespace function /-! ### Periodicity -/ /-- A function `f` is said to be `periodic` with period `c` if for all `x`, `f (x + c) = f x`. -/ @[simp] def periodic [has_add α] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = f x lemma periodic.funext [has_add α] (h : periodic f c) : (λ x, f (x + c)) = f := funext h lemma periodic.comp [has_add α] (h : periodic f c) (g : β → γ) : periodic (g ∘ f) c := by simp * at * lemma periodic.comp_add_hom [has_add α] [has_add γ] (h : periodic f c) (g : add_hom γ α) (g_inv : α → γ) (hg : right_inverse g_inv g) : periodic (f ∘ g) (g_inv c) := λ x, by simp only [hg c, h (g x), add_hom.map_add, comp_app] @[to_additive] lemma periodic.mul [has_add α] [has_mul β] (hf : periodic f c) (hg : periodic g c) : periodic (f * g) c := by simp * at * @[to_additive] lemma periodic.div [has_add α] [has_div β] (hf : periodic f c) (hg : periodic g c) : periodic (f / g) c := by simp * at * @[to_additive] lemma _root_.list.periodic_prod [has_add α] [comm_monoid β] (l : list (α → β)) (hl : ∀ f ∈ l, periodic f c) : periodic l.prod c := begin induction l with g l ih hl, { simp, }, { simp only [list.mem_cons_iff, forall_eq_or_imp] at hl, obtain ⟨hg, hl⟩ := hl, simp only [list.prod_cons], exact hg.mul (ih hl), }, end @[to_additive] lemma _root_.multiset.periodic_prod [has_add α] [comm_monoid β] (s : multiset (α → β)) (hs : ∀ f ∈ s, periodic f c) : periodic s.prod c := s.prod_to_list ▸ s.to_list.periodic_prod $ λ f hf, hs f $ (multiset.mem_to_list f s).mp hf @[to_additive] lemma _root_.finset.periodic_prod [has_add α] [comm_monoid β] {ι : Type*} {f : ι → α → β} (s : finset ι) (hs : ∀ i ∈ s, periodic (f i) c) : periodic (∏ i in s, f i) c := s.prod_to_list f ▸ (s.to_list.map f).periodic_prod (by simpa [-periodic]) @[to_additive] lemma periodic.smul [has_add α] [has_smul γ β] (h : periodic f c) (a : γ) : periodic (a • f) c := by simp * at * lemma periodic.const_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma periodic.const_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := begin intro x, by_cases ha : a = 0, { simp only [ha, zero_smul] }, simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x), end lemma periodic.const_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ a lemma periodic.const_inv_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma periodic.const_inv_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ a⁻¹ lemma periodic.const_inv_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ a lemma periodic.mul_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ mul_opposite.op a lemma periodic.mul_const' [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const a lemma periodic.mul_const_inv [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ mul_opposite.op a lemma periodic.div_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv a lemma periodic.add_period [add_semigroup α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_eq [add_group α] (h : periodic f c) (x : α) : f (x - c) = f x := by simpa only [sub_add_cancel] using (h (x - c)).symm lemma periodic.sub_eq' [add_comm_group α] (h : periodic f c) : f (c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma periodic.neg [add_group α] (h : periodic f c) : periodic f (-c) := by simpa only [sub_eq_add_neg, periodic] using h.sub_eq lemma periodic.sub_period [add_comm_group α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.nsmul [add_monoid α] (h : periodic f c) (n : ℕ) : periodic f (n • c) := by induction n; simp [nat.succ_eq_add_one, add_nsmul, ← add_assoc, zero_nsmul, *] at * lemma periodic.nat_mul [semiring α] (h : periodic f c) (n : ℕ) : periodic f (n * c) := by simpa only [nsmul_eq_mul] using h.nsmul n lemma periodic.neg_nsmul [add_group α] (h : periodic f c) (n : ℕ) : periodic f (-(n • c)) := (h.nsmul n).neg lemma periodic.neg_nat_mul [ring α] (h : periodic f c) (n : ℕ) : periodic f (-(n * c)) := (h.nat_mul n).neg lemma periodic.sub_nsmul_eq [add_group α] (h : periodic f c) (n : ℕ) : f (x - n • c) = f x := by simpa only [sub_eq_add_neg] using h.neg_nsmul n x lemma periodic.sub_nat_mul_eq [ring α] (h : periodic f c) (n : ℕ) : f (x - n * c) = f x := by simpa only [nsmul_eq_mul] using h.sub_nsmul_eq n lemma periodic.nsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℕ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nsmul n (-x) lemma periodic.nat_mul_sub_eq [ring α] (h : periodic f c) (n : ℕ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nat_mul n (-x) lemma periodic.zsmul [add_group α] (h : periodic f c) (n : ℤ) : periodic f (n • c) := begin cases n, { simpa only [int.of_nat_eq_coe, coe_nat_zsmul] using h.nsmul n }, { simpa only [zsmul_neg_succ_of_nat] using (h.nsmul n.succ).neg }, end lemma periodic.int_mul [ring α] (h : periodic f c) (n : ℤ) : periodic f (n * c) := by simpa only [zsmul_eq_mul] using h.zsmul n lemma periodic.sub_zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (x - n • c) = f x := (h.zsmul n).sub_eq x lemma periodic.sub_int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (x - n * c) = f x := (h.int_mul n).sub_eq x lemma periodic.zsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℤ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.zsmul n (-x) lemma periodic.int_mul_sub_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.int_mul n (-x) lemma periodic.eq [add_zero_class α] (h : periodic f c) : f c = f 0 := by simpa only [zero_add] using h 0 lemma periodic.neg_eq [add_group α] (h : periodic f c) : f (-c) = f 0 := h.neg.eq lemma periodic.nsmul_eq [add_monoid α] (h : periodic f c) (n : ℕ) : f (n • c) = f 0 := (h.nsmul n).eq lemma periodic.nat_mul_eq [semiring α] (h : periodic f c) (n : ℕ) : f (n * c) = f 0 := (h.nat_mul n).eq lemma periodic.zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (n • c) = f 0 := (h.zsmul n).eq lemma periodic.int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c) = f 0 := (h.int_mul n).eq /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico 0 c` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico₀ [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x) : ∃ y ∈ set.Ico 0 c, f x = f y := let ⟨n, H, _⟩ := exists_unique_zsmul_near_of_pos' hc x in ⟨x - n • c, H, (h.sub_zsmul_eq n).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ico a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ico hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ioc a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ioc a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ioc hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ lemma periodic.image_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (a : α) : f '' set.Ioc a (a + c) = set.range f := (set.image_subset_range _ _).antisymm $ set.range_subset_iff.2 $ λ x, let ⟨y, hy, hyx⟩ := h.exists_mem_Ioc hc x a in ⟨y, hy, hyx.symm⟩ lemma periodic_with_period_zero [add_zero_class α] (f : α → β) : periodic f 0 := λ x, by rw add_zero lemma periodic.map_vadd_zmultiples [add_comm_group α] (hf : periodic f c) (a : add_subgroup.zmultiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_subgroup.vadd_def, add_comm _ x, hf.zsmul m x] } lemma periodic.map_vadd_multiples [add_comm_monoid α] (hf : periodic f c) (a : add_submonoid.multiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_submonoid.vadd_def, add_comm _ x, hf.nsmul m x] } /-- Lift a periodic function to a function from the quotient group. -/ def periodic.lift [add_group α] (h : periodic f c) (x : α ⧸ add_subgroup.zmultiples c) : β := quotient.lift_on' x f $ λ a b h', (begin rw quotient_add_group.left_rel_apply at h', obtain ⟨k, hk⟩ := h', exact (h.zsmul k _).symm.trans (congr_arg f (add_eq_of_eq_neg_add hk)), end) @[simp] lemma periodic.lift_coe [add_group α] (h : periodic f c) (a : α) : h.lift (a : α ⧸ add_subgroup.zmultiples c) = f a := rfl /-! ### Antiperiodicity -/ /-- A function `f` is said to be `antiperiodic` with antiperiod `c` if for all `x`, `f (x + c) = -f x`. -/ @[simp] def antiperiodic [has_add α] [has_neg β] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = -f x lemma antiperiodic.funext [has_add α] [has_neg β] (h : antiperiodic f c) : (λ x, f (x + c)) = -f := funext h lemma antiperiodic.funext' [has_add α] [add_group β] (h : antiperiodic f c) : (λ x, -f (x + c)) = f := (eq_neg_iff_eq_neg.mp h.funext).symm /-- If a function is `antiperiodic` with antiperiod `c`, then it is also `periodic` with period `2 * c`. -/ lemma antiperiodic.periodic [semiring α] [add_group β] (h : antiperiodic f c) : periodic f (2 * c) := by simp [two_mul, ← add_assoc, h _] lemma antiperiodic.eq [add_zero_class α] [has_neg β] (h : antiperiodic f c) : f c = -f 0 := by simpa only [zero_add] using h 0 lemma antiperiodic.nat_even_mul_periodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : periodic f (n * (2 * c)) := h.periodic.nat_mul n lemma antiperiodic.nat_odd_mul_antiperiodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.nat_mul] lemma antiperiodic.int_even_mul_periodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : periodic f (n * (2 * c)) := h.periodic.int_mul n lemma antiperiodic.int_odd_mul_antiperiodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.int_mul] lemma antiperiodic.nat_mul_eq_of_eq_zero [comm_semiring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℕ) : f (n * c) = 0 := begin rcases nat.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.nat_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.nat_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.int_mul_eq_of_eq_zero [comm_ring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℤ) : f (n * c) = 0 := begin rcases int.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.int_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.int_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.sub_eq [add_group α] [add_group β] (h : antiperiodic f c) (x : α) : f (x - c) = -f x := by simp only [eq_neg_iff_eq_neg.mp (h (x - c)), sub_add_cancel] lemma antiperiodic.sub_eq' [add_comm_group α] [add_group β] (h : antiperiodic f c) : f (c - x) = -f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma antiperiodic.neg [add_group α] [add_group β] (h : antiperiodic f c) : antiperiodic f (-c) := by simpa only [sub_eq_add_neg, antiperiodic] using h.sub_eq lemma antiperiodic.neg_eq [add_group α] [add_group β] (h : antiperiodic f c) : f (-c) = -f 0 := by simpa only [zero_add] using h.neg 0 lemma antiperiodic.smul [has_add α] [monoid γ] [add_group β] [distrib_mul_action γ β] (h : antiperiodic f c) (a : γ) : antiperiodic (a • f) c := by simp * at * lemma antiperiodic.const_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma antiperiodic.const_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x) lemma antiperiodic.const_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ ha lemma antiperiodic.const_inv_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma antiperiodic.const_inv_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ (inv_ne_zero ha) lemma antiperiodic.const_inv_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ ha lemma antiperiodic.mul_const [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.mul_const' [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const ha lemma antiperiodic.mul_const_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.div_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv ha lemma antiperiodic.add [add_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma antiperiodic.sub [add_comm_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_antiperiod [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod_eq [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ + c₂) = -f 0 := (h1.add_antiperiod h2).eq lemma periodic.sub_antiperiod_eq [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ - c₂) = -f 0 := (h1.sub_antiperiod h2).eq lemma antiperiodic.mul [has_add α] [ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f * g) c := by simp * at * lemma antiperiodic.div [has_add α] [division_ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f / g) c := by simp [*, neg_div_neg_eq] at * end function
5df3f221a1e5d1a53ac3ad07f8b03b4081642fc3
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/field_theory/polynomial_galois_group.lean
c22d1f10f9e02003f91d6b76e6a3208fe8c22181
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,987
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import analysis.complex.polynomial import field_theory.galois import group_theory.perm.cycle_type import ring_theory.eisenstein_criterion /-! # Galois Groups of Polynomials In this file, we introduce the Galois group of a polynomial `p` over a field `F`, defined as the automorphism group of its splitting field. We also provide some results about some extension `E` above `p.splitting_field`, and some specific results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots. ## Main definitions - `polynomial.gal p`: the Galois group of a polynomial p. - `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful. - `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. - `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. - `polynomial.gal.gal_action_hom_bijective_of_prime_degree`: An irreducible polynomial of prime degree with two non-real roots has full Galois group. ## Other results - `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ noncomputable theory open_locale classical open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : polynomial F) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial. -/ @[derive [group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal instance : has_coe_to_fun p.gal (λ _, p.splitting_field → p.splitting_field) := alg_equiv.has_coe_to_fun @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], end /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := unique_gal_of_splits _ (h.1) instance unique_gal_zero : unique (0 : polynomial F).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : polynomial F).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : polynomial F).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : polynomial F).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) -- The `algebra p.splitting_field E` instance above behaves badly when -- `E := p.splitting_field`, since it may result in a unification problem -- `is_splitting_field.lift.to_ring_hom.to_algebra =?= algebra.id`, -- which takes an extremely long time to resolve, causing timeouts. -- Since we don't really care about this definition, marking it as irreducible -- causes that unification to error out early. attribute [irreducible] gal.algebra /-- Restrict from a superfield automorphism into a member of `gal p`. -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection, see `polynomial.gal.map_roots_bijective`. -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin have key := subtype.mem x, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, -- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ x, ⟨ϕ x, begin have key := subtype.mem x, --simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw mem_root_set h, change aeval (ϕ.to_alg_hom x) p = 0, rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } /-- The action of `gal p` on the roots of `p` in `E`. -/ instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} /-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/ @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `polynomial.gal.gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := { to_fun := λ ϕ, equiv.mk (λ x, ϕ • x) (λ x, ϕ⁻¹ • x) (λ x, inv_smul_smul ϕ x) (λ x, smul_inv_smul ϕ x), map_one' := by { ext1 x, exact mul_action.one_smul x }, map_mul' := λ x y, by { ext1 z, exact mul_action.mul_smul x y z } } lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x := restrict_smul ϕ x /-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/ lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw monoid_hom.injective_iff, intros ϕ hϕ, ext x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by simp only [restrict_dvd, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product maps into the product of the Galois groups. -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) /-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/ lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal, { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, dsimp only [restrict_prod, restrict_dvd] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, ext x hx, rw [root_set, map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : polynomial F} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁, }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂, }, end /-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/ lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : polynomial F → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : polynomial F}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) ((minpoly.irreducible qx_int).dvd_symm hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : polynomial F}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- `polynomial.gal.restrict` for the composition of polynomials. -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := @restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩ lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} /-- For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. -/ lemma card_of_separable (hp : p.separable) : fintype.card p.gal = finrank F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_finrank F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := (is_algebraic_iff_is_integral F).mp (algebra.is_algebraic_of_finite α), use finite_dimensional.finrank F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.finrank hα, this] }, suffices : minpoly F α ∣ p, { have key := (minpoly.irreducible hα).dvd_symm p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end section rationals lemma splits_ℚ_ℂ {p : polynomial ℚ} : fact (p.splits (algebra_map ℚ ℂ)) := ⟨is_alg_closed.splits_codomain p⟩ local attribute [instance] splits_ℚ_ℂ /-- The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : polynomial ℚ) : (p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card + (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card := begin by_cases hp : p = 0, { simp_rw [hp, root_set_zero, set.to_finset_eq_empty_iff.mpr rfl, finset.card_empty, zero_add], refine eq.symm (nat.le_zero_iff.mp ((finset.card_le_univ _).trans (le_of_eq _))), simp_rw [hp, root_set_zero, fintype.card_eq_zero_iff], apply_instance }, have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective, rw [←finset.card_image_of_injective _ subtype.coe_injective, ←finset.card_image_of_injective _ inj], let a : finset ℂ := _, let b : finset ℂ := _, let c : finset ℂ := _, change a.card = b.card + c.card, have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0 := λ z, by rw [set.mem_to_finset, mem_root_set hp], have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0, { intro z, simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set hp], split, { rintros ⟨w, hw, rfl⟩, exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ }, { rintros ⟨hz1, hz2⟩, have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl }, exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } }, have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ)) w = w ↔ w.val.im = 0, { intro w, rw [subtype.ext_iff, gal_action_hom_restrict], exact complex.eq_conj_iff_im }, have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0, { intro z, simp_rw [finset.mem_image, exists_prop], split, { rintros ⟨w, hw, rfl⟩, exact ⟨(mem_root_set hp).mp w.2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ }, { rintros ⟨hz1, hz2⟩, exact ⟨⟨z, (mem_root_set hp).mpr hz1⟩, equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } }, rw ← finset.card_disjoint_union, { apply congr_arg finset.card, simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc], tauto }, { intro z, rw [finset.inf_eq_inter, finset.mem_inter, hb, hc], tauto }, { apply_instance }, end /-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree {p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) : function.bijective (gal_action_hom p ℂ) := begin have h1 : fintype.card (p.root_set ℂ) = p.nat_degree, { simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots], { exact is_alg_closed.splits_codomain p }, { exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } }, have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range := fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv, let conj := restrict p ℂ (complex.conj_ae.restrict_scalars ℚ), refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x) (show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩, apply equiv.perm.subgroup_eq_top_of_swap_mem, { rwa h1 }, { rw h1, convert prime_degree_dvd_card p_irr p_deg using 1, convert h2.symm }, { exact ⟨conj, rfl⟩ }, { rw ← equiv.perm.card_support_eq_two, apply nat.add_left_cancel, rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)], exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm }, end /-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree' {p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ)) (p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) : function.bijective (gal_action_hom p ℂ) := begin apply gal_action_hom_bijective_of_prime_degree p_irr p_deg, let n := (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card, have hn : 2 ∣ n := equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow, show alg_equiv.restrict_scalars ℚ complex.conj_ae ^ 2 = 1, from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]), have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p, simp_rw [set.to_finset_card] at key, rw [key, add_le_add_iff_left] at p_roots1 p_roots2, rw [key, add_right_inj], suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2, { exact this n hn p_roots1 p_roots2 }, rintros m ⟨k, rfl⟩ h2 h3, exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1, from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2 (show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))), end end rationals end gal end polynomial
92d535468393bd15d71920059fae0141f8fe6a43
80746c6dba6a866de5431094bf9f8f841b043d77
/src/category/traversable/basic.lean
5a59b9592f5dd942d0bf13a0fabc405a21398ff0
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
3,613
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Type classes for traversing collections. The concepts and laws are taken from http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html -/ import tactic.cache import category.applicative open function (hiding comp) universes u v w section applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] structure applicative_transformation : Type (max (u+1) v w) := (app : ∀ {α : Type u}, F α → G α) (preserves_pure' : ∀ {α : Type u} (x : α), app (pure x) = pure x) (preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app (x <*> y) = app x <*> app y) end applicative_transformation namespace applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] instance : has_coe_to_fun (applicative_transformation F G) := ⟨_, λ m, m.app⟩ variables {F G} variables (η : applicative_transformation F G) @[functor_norm] lemma preserves_pure : ∀ {α} (x : α), η (pure x) = pure x := η.preserves_pure' @[functor_norm] lemma preserves_seq : ∀ {α β : Type u} (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y := η.preserves_seq' @[functor_norm] lemma preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y := by rw [← pure_seq_eq_map, η.preserves_seq]; simp with functor_norm end applicative_transformation open applicative_transformation class traversable (t : Type u → Type u) extends functor t := (traverse : Π {m : Type u → Type u} [applicative m] {α β}, (α → m β) → t α → m (t β)) open functor export traversable (traverse) section functions variables {t : Type u → Type u} variables {m : Type u → Type v} [applicative m] variables {α β : Type u} variables {f : Type u → Type u} [applicative f] def sequence [traversable t] : t (f α) → f (t α) := traverse id end functions class is_lawful_traversable (t : Type u → Type u) [traversable t] extends is_lawful_functor t : Type (u+1) := (id_traverse : ∀ {α} (x : t α), traverse id.mk x = x ) (comp_traverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α β γ} (f : β → F γ) (g : α → G β) (x : t α), traverse (comp.mk ∘ map f ∘ g) x = comp.mk (map (traverse f) (traverse g x))) (traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α), traverse (id.mk ∘ f) x = id.mk (f <$> x)) (naturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α β} (f : α → F β) (x : t α), η (traverse f x) = traverse (@η _ ∘ f) x) instance : traversable id := ⟨λ _ _ _ _, id⟩ instance : is_lawful_traversable id := by refine {..}; intros; refl section variables {F : Type u → Type v} [applicative F] instance : traversable option := ⟨@option.traverse⟩ instance : traversable list := ⟨@list.traverse⟩ end namespace sum variables {σ : Type u} variables {F : Type u → Type u} variables [applicative F] protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) | (sum.inl x) := pure (sum.inl x) | (sum.inr x) := sum.inr <$> f x end sum instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩
00ba1150f539fb1c18bd1764c04580bf90d63b2c
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/ite_simp.lean
2675a7d5f803ae23b67b2036712dd6f2955dd45f
[ "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
901
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.bool /-! # Simplification lemmas for ite. We don't prove them at logic.lean because it is easier to prove them using the tactic framework. -/ @[simp] lemma if_true_right_eq_or (p : Prop) [h : decidable p] (q : Prop) : (if p then q else true) = (¬p ∨ q) := by by_cases p; simp [h] @[simp] lemma if_true_left_eq_or (p : Prop) [h : decidable p] (q : Prop) : (if p then true else q) = (p ∨ q) := by by_cases p; simp [h] @[simp] lemma if_false_right_eq_and (p : Prop) [h : decidable p] (q : Prop) : (if p then q else false) = (p ∧ q) := by by_cases p; simp [h] @[simp] lemma if_false_left_eq_and (p : Prop) [h : decidable p] (q : Prop) : (if p then false else q) = (¬p ∧ q) := by by_cases p; simp [h]
76b81092276de3a2a38b0046f7460276e58424ba
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/integrable_on.lean
63a9af38d5522f64e364d7eced6dbdce578335c8
[ "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
30,646
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.function.l1_space import analysis.normed_space.indicator_function /-! # Functions integrable on a set and at a filter > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topology interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section variables [topological_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is strongly measurable at a filter `l` w.r.t. a measure `μ` if it is ae strongly measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def strongly_measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_strongly_measurable f (μ.restrict s) @[simp] lemma strongly_measurable_at_bot {f : α → β} : strongly_measurable_at_filter f ⊥ μ := ⟨∅, mem_bot, by simp⟩ protected lemma strongly_measurable_at_filter.eventually (h : strongly_measurable_at_filter f l μ) : ∀ᶠ s in l.small_sets, ae_strongly_measurable f (μ.restrict s) := (eventually_small_sets' $ λ s t, ae_strongly_measurable.mono_set).2 h protected lemma strongly_measurable_at_filter.filter_mono (h : strongly_measurable_at_filter f l μ) (h' : l' ≤ l) : strongly_measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma measure_theory.ae_strongly_measurable.strongly_measurable_at_filter (h : ae_strongly_measurable f μ) : strongly_measurable_at_filter f l μ := ⟨univ, univ_mem, by rwa measure.restrict_univ⟩ lemma ae_strongly_measurable.strongly_measurable_at_filter_of_mem {s} (h : ae_strongly_measurable f (μ.restrict s)) (hl : s ∈ l) : strongly_measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measure_theory.strongly_measurable.strongly_measurable_at_filter (h : strongly_measurable f) : strongly_measurable_at_filter f l μ := h.ae_strongly_measurable.strongly_measurable_at_filter end namespace measure_theory section normed_add_comm_group lemma has_finite_integral_restrict_of_bounded [normed_add_comm_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ‖f x‖ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : is_finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_add_comm_group E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is almost everywhere strongly measurable on `s` and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ @[simp] lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst le_rfl lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ measure.restrict_mono_ae hst lemma integrable_on.congr_set_ae (h : integrable_on f t μ) (hst : s =ᵐ[μ] t) : integrable_on f s μ := h.mono_set_ae hst.le lemma integrable_on.congr_fun_ae (h : integrable_on f s μ) (hst : f =ᵐ[μ.restrict s] g) : integrable_on g s μ := integrable.congr h hst lemma integrable_on_congr_fun_ae (hst : f =ᵐ[μ.restrict s] g) : integrable_on f s μ ↔ integrable_on g s μ := ⟨λ h, h.congr_fun_ae hst, λ h, h.congr_fun_ae hst.symm⟩ lemma integrable_on.congr_fun (h : integrable_on f s μ) (hst : eq_on f g s) (hs : measurable_set s) : integrable_on g s μ := h.congr_fun_ae ((ae_restrict_iff' hs).2 (eventually_of_forall hst)) lemma integrable_on_congr_fun (hst : eq_on f g s) (hs : measurable_set s) : integrable_on f s μ ↔ integrable_on g s μ := ⟨λ h, h.congr_fun hst hs, λ h, h.congr_fun hst.symm hs⟩ lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) : integrable_on f s (μ.restrict t) := by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) } lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α] : integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ := begin have : f =ᵐ[μ.restrict {x}] (λ y, f x), { filter_upwards [ae_restrict_mem (measurable_set_singleton x)] with _ ha, simp only [mem_singleton_iff.1 ha], }, rw [integrable_on, integrable_congr this, integrable_const_iff], simp, end @[simp] lemma integrable_on_finite_bUnion {s : set β} (hs : s.finite) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_Union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_bUnion s.finite_to_set @[simp] lemma integrable_on_finite_Union [finite β] {t : β → set α} : integrable_on f (⋃ i, t i) μ ↔ ∀ i, integrable_on f (t i) μ := by { casesI nonempty_fintype β, simpa using @integrable_on_finset_Union _ _ _ _ _ f μ finset.univ t } lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right le_rfl), h.mono_measure (measure.le_add_left le_rfl)⟩, λ h, h.1.add_measure h.2⟩ lemma _root_.measurable_embedding.integrable_on_map_iff [measurable_space β] {e : α → β} (he : measurable_embedding e) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, he.restrict_map, he.integrable_map_iff] lemma integrable_on_map_equiv [measurable_space β] (e : α ≃ᵐ β) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, e.restrict_map, integrable_map_equiv e] lemma measure_preserving.integrable_on_comp_preimage [measurable_space β] {e : α → β} {ν} (h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set β} : integrable_on (f ∘ e) (e ⁻¹' s) μ ↔ integrable_on f s ν := (h₁.restrict_preimage_emb h₂ s).integrable_comp_emb h₂ lemma measure_preserving.integrable_on_image [measurable_space β] {e : α → β} {ν} (h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set α} : integrable_on f (e '' s) ν ↔ integrable_on (f ∘ e) s μ := ((h₁.restrict_image_emb h₂ s).integrable_comp_emb h₂).symm lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_strongly_measurable_indicator_iff hs] lemma integrable_on.integrable_indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.integrable_indicator hs lemma integrable_on.indicator (h : integrable_on f s μ) (ht : measurable_set t) : integrable_on (indicator t f) s μ := integrable.indicator h ht lemma integrable_indicator_const_Lp {E} [normed_add_comm_group E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : integrable (indicator_const_Lp p hs hμs c) μ := begin rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on, integrable_const_iff, lt_top_iff_ne_top], right, simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs, end /-- If a function is integrable on a set `s` and nonzero there, then the measurable hull of `s` is well behaved: the restriction of the measure to `to_measurable μ s` coincides with its restriction to `s`. -/ lemma integrable_on.restrict_to_measurable (hf : integrable_on f s μ) (h's : ∀ x ∈ s, f x ≠ 0) : μ.restrict (to_measurable μ s) = μ.restrict s := begin rcases exists_seq_strict_anti_tendsto (0 : ℝ) with ⟨u, u_anti, u_pos, u_lim⟩, let v := λ n, to_measurable (μ.restrict s) {x | u n ≤ ‖f x‖}, have A : ∀ n, μ (s ∩ v n) ≠ ∞, { assume n, rw [inter_comm, ← measure.restrict_apply (measurable_set_to_measurable _ _), measure_to_measurable], exact (hf.measure_ge_lt_top (u_pos n)).ne }, apply measure.restrict_to_measurable_of_cover _ A, assume x hx, have : 0 < ‖f x‖, by simp only [h's x hx, norm_pos_iff, ne.def, not_false_iff], obtain ⟨n, hn⟩ : ∃ n, u n < ‖f x‖, from ((tendsto_order.1 u_lim).2 _ this).exists, refine mem_Union.2 ⟨n, _⟩, exact subset_to_measurable _ _ hn.le end /-- If a function is integrable on a set `s`, and vanishes on `t \ s`, then it is integrable on `t` if `t` is null-measurable. -/ lemma integrable_on.of_ae_diff_eq_zero (hf : integrable_on f s μ) (ht : null_measurable_set t μ) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0) : integrable_on f t μ := begin let u := {x ∈ s | f x ≠ 0}, have hu : integrable_on f u μ := hf.mono_set (λ x hx, hx.1), let v := to_measurable μ u, have A : integrable_on f v μ, { rw [integrable_on, hu.restrict_to_measurable], { exact hu }, { assume x hx, exact hx.2 } }, have B : integrable_on f (t \ v) μ, { apply integrable_on_zero.congr, filter_upwards [ae_restrict_of_ae h't, ae_restrict_mem₀ (ht.diff (measurable_set_to_measurable μ u).null_measurable_set)] with x hxt hx, by_cases h'x : x ∈ s, { by_contra H, exact hx.2 (subset_to_measurable μ u ⟨h'x, ne.symm H⟩) }, { exact (hxt ⟨hx.1, h'x⟩).symm, } }, apply (A.union B).mono_set _, rw union_diff_self, exact subset_union_right _ _ end /-- If a function is integrable on a set `s`, and vanishes on `t \ s`, then it is integrable on `t` if `t` is measurable. -/ lemma integrable_on.of_forall_diff_eq_zero (hf : integrable_on f s μ) (ht : measurable_set t) (h't : ∀ x ∈ t \ s, f x = 0) : integrable_on f t μ := hf.of_ae_diff_eq_zero ht.null_measurable_set (eventually_of_forall h't) /-- If a function is integrable on a set `s` and vanishes almost everywhere on its complement, then it is integrable. -/ lemma integrable_on.integrable_of_ae_not_mem_eq_zero (hf : integrable_on f s μ) (h't : ∀ᵐ x ∂μ, x ∉ s → f x = 0) : integrable f μ := begin rw ← integrable_on_univ, apply hf.of_ae_diff_eq_zero null_measurable_set_univ, filter_upwards [h't] with x hx h'x using hx h'x.2, end /-- If a function is integrable on a set `s` and vanishes everywhere on its complement, then it is integrable. -/ lemma integrable_on.integrable_of_forall_not_mem_eq_zero (hf : integrable_on f s μ) (h't : ∀ x ∉ s, f x = 0) : integrable f μ := hf.integrable_of_ae_not_mem_eq_zero (eventually_of_forall (λ x hx, h't x hx)) lemma integrable_on_iff_integrable_of_support_subset (h1s : support f ⊆ s) : integrable_on f s μ ↔ integrable f μ := begin refine ⟨λ h, _, λ h, h.integrable_on⟩, apply h.integrable_of_forall_not_mem_eq_zero (λ x hx, _), contrapose! hx, exact h1s (mem_support.2 hx), end lemma integrable_on_Lp_of_measure_ne_top {E} [normed_add_comm_group E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) : integrable_on f s μ := begin refine mem_ℒp_one_iff_integrable.mp _, have hμ_restrict_univ : (μ.restrict s) set.univ < ∞, by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top], haveI hμ_finite : is_finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩, exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp, end lemma integrable.lintegral_lt_top {f : α → ℝ} (hf : integrable f μ) : ∫⁻ x, ennreal.of_real (f x) ∂μ < ∞ := calc ∫⁻ x, ennreal.of_real (f x) ∂μ ≤ ∫⁻ x, ↑‖f x‖₊ ∂μ : lintegral_of_real_le_lintegral_nnnorm f ... < ∞ : hf.2 lemma integrable_on.set_lintegral_lt_top {f : α → ℝ} {s : set α} (hf : integrable_on f s μ) : ∫⁻ x in s, ennreal.of_real (f x) ∂μ < ∞ := integrable.lintegral_lt_top hf /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.small_sets`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} lemma integrable.integrable_at_filter (h : integrable f μ) (l : filter α) : integrable_at_filter f l μ := ⟨univ, filter.univ_mem, integrable_on_univ.2 h⟩ protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.small_sets, integrable_on f s μ := iff.mpr (eventually_small_sets' $ λ s t hst ht, ht.mono_set hst) h lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in l.small_sets, ∀ x ∈ s, ‖f x‖ ≤ C, from hf.imp (λ C hC, eventually_small_sets.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_small_sets with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← _root_.filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← _root_.filter.tendsto.integrable_at_filter lemma integrable_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : strongly_measurable f) (hg : strongly_measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator hf.measurable_set_support }, { rw ← indicator_add_eq_right h, exact hfg.indicator hg.measurable_set_support } end end normed_add_comm_group end measure_theory open measure_theory variables [normed_add_comm_group E] /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin nontriviality α, inhabit α, have : piecewise s f (λ _, f default) =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs, refine ⟨piecewise s f (λ _, f default), _, this.symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [piecewise_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_const ht.measurable_set).diff hs) end /-- A function which is continuous on a separable set `s` is almost everywhere strongly measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_strongly_measurable_of_is_separable [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (h's : topological_space.is_separable s) : ae_strongly_measurable f (μ.restrict s) := begin letI := pseudo_metrizable_space_pseudo_metric α, borelize β, rw ae_strongly_measurable_iff_ae_measurable_separable, refine ⟨hf.ae_measurable hs, f '' s, hf.is_separable_image h's, _⟩, exact mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _), end /-- A function which is continuous on a set `s` is almost everywhere strongly measurable with respect to `μ.restrict s` when either the source space or the target space is second-countable. -/ lemma continuous_on.ae_strongly_measurable [topological_space α] [topological_space β] [h : second_countable_topology_either α β] [opens_measurable_space α] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_strongly_measurable f (μ.restrict s) := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨hf.ae_measurable hs, f '' s, _, mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _)⟩, casesI h.out, { let f' : s → β := s.restrict f, have A : continuous f' := continuous_on_iff_continuous_restrict.1 hf, have B : is_separable (univ : set s) := is_separable_of_separable_space _, convert is_separable.image B A using 1, ext x, simp }, { exact is_separable_of_separable_space _ } end /-- A function which is continuous on a compact set `s` is almost everywhere strongly measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_strongly_measurable_of_is_compact [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : is_compact s) (h's : measurable_set s) : ae_strongly_measurable f (μ.restrict s) := begin letI := pseudo_metrizable_space_pseudo_metric β, borelize β, rw ae_strongly_measurable_iff_ae_measurable_separable, refine ⟨hf.ae_measurable h's, f '' s, _, _⟩, { exact (hs.image_of_continuous_on hf).is_separable }, { exact mem_of_superset (self_mem_ae_restrict h's) (subset_preimage_image _ _) } end lemma continuous_on.integrable_at_nhds_within_of_is_separable [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (h't : topological_space.is_separable t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := begin haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _, exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable_of_is_separable ht h't⟩ (μ.finite_at_nhds_within _ _), end lemma continuous_on.integrable_at_nhds_within [topological_space α] [second_countable_topology_either α E] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := begin haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _, exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩ (μ.finite_at_nhds_within _ _), end lemma continuous.integrable_at_nhds [topological_space α] [second_countable_topology_either α E] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {f : α → E} (hf : continuous f) (a : α) : integrable_at_filter f (𝓝 a) μ := begin rw ← nhds_within_univ, exact hf.continuous_on.integrable_at_nhds_within measurable_set.univ (mem_univ a), end /-- If a function is continuous on an open set `s`, then it is strongly measurable at the filter `𝓝 x` for all `x ∈ s` if either the source space or the target space is second-countable. -/ lemma continuous_on.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α} (hs : is_open s) (hf : continuous_on f s) : ∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ := λ x hx, ⟨s, is_open.mem_nhds hs hx, hf.ae_strongly_measurable hs.measurable_set⟩ lemma continuous_at.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [second_countable_topology_either α E] {f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : ∀ x ∈ s, continuous_at f x) : ∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ := continuous_on.strongly_measurable_at_filter hs $ continuous_at.continuous_on hf lemma continuous.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} (hf : continuous f) (μ : measure α) (l : filter α) : strongly_measurable_at_filter f l μ := hf.strongly_measurable.strongly_measurable_at_filter /-- If a function is continuous on a measurable set `s`, then it is measurable at the filter `𝓝[s] x` for all `x`. -/ lemma continuous_on.strongly_measurable_at_filter_nhds_within {α β : Type*} [measurable_space α] [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (x : α) : strongly_measurable_at_filter f (𝓝[s] x) μ := ⟨s, self_mem_nhds_within, hf.ae_strongly_measurable hs⟩ /-! ### Lemmas about adding and removing interval boundaries The primed lemmas take explicit arguments about the measure being finite at the endpoint, while the unprimed ones use `[has_no_atoms μ]`. -/ section partial_order variables [partial_order α] [measurable_singleton_class α] {f : α → E} {μ : measure α} {a b : α} lemma integrable_on_Icc_iff_integrable_on_Ioc' (ha : μ {a} ≠ ∞) : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := begin by_cases hab : a ≤ b, { rw [←Ioc_union_left hab, integrable_on_union, eq_true_intro (integrable_on_singleton_iff.mpr $ or.inr ha.lt_top), and_true] }, { rw [Icc_eq_empty hab, Ioc_eq_empty], contrapose! hab, exact hab.le } end lemma integrable_on_Icc_iff_integrable_on_Ico' (hb : μ {b} ≠ ∞) : integrable_on f (Icc a b) μ ↔ integrable_on f (Ico a b) μ := begin by_cases hab : a ≤ b, { rw [←Ico_union_right hab, integrable_on_union, eq_true_intro (integrable_on_singleton_iff.mpr $ or.inr hb.lt_top), and_true] }, { rw [Icc_eq_empty hab, Ico_eq_empty], contrapose! hab, exact hab.le } end lemma integrable_on_Ico_iff_integrable_on_Ioo' (ha : μ {a} ≠ ∞) : integrable_on f (Ico a b) μ ↔ integrable_on f (Ioo a b) μ := begin by_cases hab : a < b, { rw [←Ioo_union_left hab, integrable_on_union, eq_true_intro (integrable_on_singleton_iff.mpr $ or.inr ha.lt_top), and_true] }, { rw [Ioo_eq_empty hab, Ico_eq_empty hab] } end lemma integrable_on_Ioc_iff_integrable_on_Ioo' (hb : μ {b} ≠ ∞) : integrable_on f (Ioc a b) μ ↔ integrable_on f (Ioo a b) μ := begin by_cases hab : a < b, { rw [←Ioo_union_right hab, integrable_on_union, eq_true_intro (integrable_on_singleton_iff.mpr $ or.inr hb.lt_top), and_true] }, { rw [Ioo_eq_empty hab, Ioc_eq_empty hab] } end lemma integrable_on_Icc_iff_integrable_on_Ioo' (ha : μ {a} ≠ ∞) (hb : μ {b} ≠ ∞) : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioo a b) μ := by rw [integrable_on_Icc_iff_integrable_on_Ioc' ha, integrable_on_Ioc_iff_integrable_on_Ioo' hb] lemma integrable_on_Ici_iff_integrable_on_Ioi' (hb : μ {b} ≠ ∞) : integrable_on f (Ici b) μ ↔ integrable_on f (Ioi b) μ := by rw [←Ioi_union_left, integrable_on_union, eq_true_intro (integrable_on_singleton_iff.mpr $ or.inr hb.lt_top), and_true] lemma integrable_on_Iic_iff_integrable_on_Iio' (hb : μ {b} ≠ ∞) : integrable_on f (Iic b) μ ↔ integrable_on f (Iio b) μ := by rw [←Iio_union_right, integrable_on_union, eq_true_intro (integrable_on_singleton_iff.mpr $ or.inr hb.lt_top), and_true] variables [has_no_atoms μ] lemma integrable_on_Icc_iff_integrable_on_Ioc : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := integrable_on_Icc_iff_integrable_on_Ioc' (by { rw measure_singleton, exact ennreal.zero_ne_top }) lemma integrable_on_Icc_iff_integrable_on_Ico : integrable_on f (Icc a b) μ ↔ integrable_on f (Ico a b) μ := integrable_on_Icc_iff_integrable_on_Ico' (by { rw measure_singleton, exact ennreal.zero_ne_top }) lemma integrable_on_Ico_iff_integrable_on_Ioo : integrable_on f (Ico a b) μ ↔ integrable_on f (Ioo a b) μ := integrable_on_Ico_iff_integrable_on_Ioo' (by { rw measure_singleton, exact ennreal.zero_ne_top }) lemma integrable_on_Ioc_iff_integrable_on_Ioo : integrable_on f (Ioc a b) μ ↔ integrable_on f (Ioo a b) μ := integrable_on_Ioc_iff_integrable_on_Ioo' (by { rw measure_singleton, exact ennreal.zero_ne_top }) lemma integrable_on_Icc_iff_integrable_on_Ioo : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioo a b) μ := by rw [integrable_on_Icc_iff_integrable_on_Ioc, integrable_on_Ioc_iff_integrable_on_Ioo] lemma integrable_on_Ici_iff_integrable_on_Ioi : integrable_on f (Ici b) μ ↔ integrable_on f (Ioi b) μ := integrable_on_Ici_iff_integrable_on_Ioi' (by { rw measure_singleton, exact ennreal.zero_ne_top }) lemma integrable_on_Iic_iff_integrable_on_Iio : integrable_on f (Iic b) μ ↔ integrable_on f (Iio b) μ := integrable_on_Iic_iff_integrable_on_Iio' (by { rw measure_singleton, exact ennreal.zero_ne_top }) end partial_order
a5b61a3bef27a6d67e3c843d064a70106f0e49b6
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/extern.lean
474a56e84d9cd0abc51dc1ce186880b6f2ce0c8a
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
306
lean
@[extern] def foo (x : Nat) := x @[extern "bla"] def foo2 (x : Nat) := x @[extern 2 "boo"] def foo3 (x : Nat) := x @[extern cpp "Lean::bla" llvm "lean_bla"] def foo4 (x : Bool) := x @[extern cpp inline "#1 && #2"] def foo5 (x y : Bool) := x @[extern cpp adhoc llvm "foo"] def foo6 (x y : Bool) := x
2adf3151b9d424b6fc9eec2f0b979d63eb25a8fc
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/measure_theory/integration.lean
1b371bd3e22238c3a70c49f40185092c3a522c7e
[ "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
76,090
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 -/ import measure_theory.measure_space import measure_theory.borel_space import data.indicator_function import data.support /-! # Lebesgue integral for `ennreal`-valued functions We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ennreal`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal open_locale classical topological_space big_operators nnreal namespace measure_theory variables {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite_range' : (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⟩ lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range' lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) := f.is_measurable_fiber' x /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) : (const α b).range = {b} := finset.coe_injective $ by simp lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ }, rw this, exact is_measurable.bUnion f.finite_range.countable (λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _)) end theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s)) /-- A simple function is measurable -/ protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, is_measurable_preimage f s protected theorem ae_measurable [measurable_space β] {μ : measure α} (f : α →ₛ β) : ae_measurable f μ := f.measurable.ae_measurable protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) : ∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_fiber _) lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) : ∑ y in f.range, μ (f ⁻¹' {y}) = μ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] /-- If-then-else as a `simple_func`. -/ def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, λ x, by letI : measurable_space β := ⊤; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g := coe_injective $ by simp lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) := λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c}, (f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) 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 @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp [range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) } @[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : (f.comp g hgm).range ⊆ f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ 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 lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } 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, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl @[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl @[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} := finset.ext $ λ x, by simp [eq_comm] lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := forall_range_iff.2 $ λ x, rfl lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl 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 mul_eq_map₂ [has_mul β] (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 (α →ₛ β) := function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl instance [has_sub β] : has_sub (α →ₛ β) := ⟨λf g, (f.map (has_sub.sub)).seq g⟩ @[simp, norm_cast] lemma coe_sub [add_group β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl instance [add_group β] : add_group (α →ₛ β) := function.injective.add_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub instance [add_comm_group β] : add_comm_group (α →ₛ β) := function.injective.add_comm_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩ @[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl 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.semilattice_sup,.. simple_func.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.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 restrict variables [has_zero β] /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α} (hs : ¬is_measurable s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) : (f.restrict s).map g = (f.map g).restrict s := ext $ λ x, if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ennreal) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by simp only [hs, coe_restrict] theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht] theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : 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 is_measurable_Ici) 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 [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] [measurable_space β] [opens_measurable_space β] (i : ℕ → β) (f : α → β) (a : α) (hf : 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 /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ennreal := ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `α → ennreal` by a sequence of simple functions. -/ 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 : 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], 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 : measurable f) (hg : 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 [measurable_space α] {μ : measure α} /-- Integral of a simple function whose codomain is `ennreal`. -/ def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal := ∑ x in f.range, x * μ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) + ∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ : by rw [map_lintegral, map_lintegral] ... = lintegral f μ + lintegral g μ : rfl lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) : map_lintegral _ _ ... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral μ : finset.mul_sum.symm /-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/ def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal := { to_fun := λ f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g), map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 := linear_map.ext_iff.1 lintegralₗ.map_zero μ lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) : f.lintegral (c • μ) = c • f.lintegral μ := (lintegralₗ f).map_smul c μ @[simp] lemma lintegral_zero (f : α →ₛ ennreal) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) : f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) := begin simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) : f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ := begin rw [lintegral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } end lemma const_lintegral_restrict (c : ennreal) (s : set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter] lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := calc f.lintegral μ ⊔ g.lintegral μ = ((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl ... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], 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).lintegral μ : by rw [sup_eq_map₂, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left ... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _ ... = g.lintegral μ : by rw [sup_of_le_right hfg] ... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $ hμν _ (g.is_measurable_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal} {ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero ‹_› end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage $ λ y, measure_congr $ eventually.set_eq $ h.mono $ λ x hx, by simp [hx] lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage $ λ y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm } end measure section fin_meas_supp variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α} open finset ennreal function lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} := set.ext $ λ x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage, finset.mem_coe, mem_filter, mem_range_self, true_and] /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop := f =ᶠ[μ.cofinite] 0 lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ μ (support f) < ⊤ := iff.rfl lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ := begin split, { refine λ h y hy, lt_of_le_of_lt (measure_mono _) h, exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact λ y hy, H y (finset.mem_filter.1 hy).2 } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ⊤ := fin_meas_supp_iff.1 h y hy protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) : (f.map g).fin_meas_supp μ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) : f.fin_meas_supp μ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ := ⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩ protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (pair f g).fin_meas_supp μ := calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g ... ≤ μ (support f) + μ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ) {g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp μ := (hf.pair hg).map H protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f + g).fin_meas_supp μ := by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) } protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f * g).fin_meas_supp μ := by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) } lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.lintegral μ < ⊤ := begin refine sum_lt_top (λ a ha, _), rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha, { simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } } end lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ := begin refine fin_meas_supp_iff.2 (λ b hb, _), rw [lintegral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, measure_empty], exact with_top.zero_lt_top } end lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ := ⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop} (h_ind : ∀ c {s} (hs : is_measurable s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g)) (f : simple_func α γ) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 is_measurable.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.is_measurable_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_sum _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, { rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } } end end simple_func section lintegral open simple_func variables [measurable_space α] {μ : measure α} /-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/ def lintegral (μ : measure α) (f : α → ennreal) : ennreal := ⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := le_antisymm (bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _) (le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _)) @[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩ lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := begin refine lintegral_mono _, intro a, rw ennreal.coe_le_coe, exact h a, end lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] @[simp] lemma lintegral_one : ∫⁻ a, (1 : ennreal) ∂μ = μ univ := by rw [lintegral_const, one_mul] lemma set_lintegral_const (s : set α) (c : ennreal) : ∫⁻ a in s, c ∂μ = c * μ s := by rw [lintegral_const, measure.restrict_apply_univ] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [set_lintegral_const, one_mul] /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : ℝ≥0 → ennreal)).lintegral μ) := begin refine le_antisymm (bsupr_le $ assume φ hφ, _) (supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] } /-- Monotone convergence theorem -- sometimes 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 ∂μ) := begin set c : ℝ≥0 → ennreal := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_le (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, ← 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 (pos_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, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr], { assume i, refine ((rs.map c).is_measurable_preimage _).inter _, exact hf i is_measurable_Ici } end) ... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((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 _) (measure_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with 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_lintegral], refine lintegral_mono (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := 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).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_is_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 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, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [restrict_congr_set h] @[simp] 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).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], 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).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_add' {f g : α → ennreal} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, hf.mk f a + hg.mk g a ∂μ) : lintegral_congr_ae (eventually_eq.add hf.ae_eq_mk hg.ae_eq_mk) ... = (∫⁻ a, hf.mk f a ∂μ) + (∫⁻ a, hg.mk g a ∂μ) : lintegral_add hf.measurable_mk hg.measurable_mk ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : begin congr' 1, { exact lintegral_congr_ae hf.ae_eq_mk.symm }, { exact lintegral_congr_ae hg.ae_eq_mk.symm }, end lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp lemma lintegral_zero_fun : (∫⁻ a:α, (0 : α → ennreal) a ∂μ) = 0 := by simp @[simp] lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _)) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩ end @[simp] lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 := bot_unique $ by simp [lintegral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp only [finset.sum_insert has], rw [lintegral_add (hf _) (s.measurable_sum hf), ih] } end @[simp] 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).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { 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_lintegral hf] lemma lintegral_const_mul'' (r : ennreal) {f : α → ennreal} (hf : ae_measurable f μ) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ := lintegral_congr_ae (eventually_eq.fun_comp hf.ae_eq_mk _), rw [A, B, lintegral_const_mul _ hf.measurable_mk], end lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_lintegral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_mul_const (r : ennreal) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul r hf] lemma lintegral_mul_const'' (r : ennreal) {f : α → ennreal} (hf : ae_measurable f μ) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul'' r hf] lemma lintegral_mul_const_le (r : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] lemma lintegral_mul_const' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤): ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] /- A double integral of a product where each factor contains only one variable is a product of integrals -/ lemma lintegral_lintegral_mul {β} [measurable_space β] {ν : measure β} {f : α → ennreal} {g : β → ennreal} (hf : measurable f) (hg : measurable g) : ∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_const_mul _ hg, lintegral_mul_const _ hf] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) (le_refl _), by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩, simp [hφ x, hs, indicator_le_indicator] } end /-- Chebyshev's inequality -/ lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := begin have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (λ a, _), simp only [restrict_apply _ this], split_ifs; [assumption, exact zero_le _] end lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal} (hε : ε ≠ 0) (hε' : ε ≠ ⊤) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε } @[simp] lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹, { assume n, rw [ae_iff, ← nonpos_iff_eq_zero, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (λ 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 ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h ... = 0 : lintegral_zero } end @[simp] lemma lintegral_eq_zero_iff' {f : α → ennreal} (hf : ae_measurable f μ) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin have : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, rw [this, lintegral_eq_zero_iff hf.measurable_mk], exact ⟨λ H, hf.ae_eq_mk.trans H, λ H, hf.ae_eq_mk.symm.trans H⟩ end lemma lintegral_pos_iff_support {f : α → ennreal} (hf : measurable f) : 0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) := by simp [pos_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_null (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin rw [← ennreal.add_left_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.ennreal_sub hg) hg], refine lintegral_congr_ae (h_le.mono $ λ x hx, _), exact ennreal.sub_add_cancel_of_le hx end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _), (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (calc (∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _) ... < ⊤ : h_fin ) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).ennreal_sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc ∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := calc ∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr (assume n, measurable_binfi _ (countable_encodable _) h_meas) (assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_le_supr $ λ n, le_infi2_lintegral _ ... = liminf at_top (λ n, ∫⁻ a, f n a ∂μ) : liminf_eq_supr_infi_of_nat.symm lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) : limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ := calc limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin, refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas) (calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for nonnegative functions which are just almost everywhere measurable. -/ lemma tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, ae_measurable (F n) μ) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := begin have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := λ n, lintegral_congr_ae (hF_meas n).ae_eq_mk, simp_rw this, apply tendsto_lintegral_of_dominated_convergence bound (λ n, (hF_meas n).measurable_mk) _ h_fin, { have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := λ n, (hF_meas n).ae_eq_mk.symm, have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this, filter_upwards [this, h_lim], assume a H H', simp_rw H, exact H' }, { assume n, filter_upwards [h_bound n, (hF_meas n).ae_eq_mk], assume a H H', rwa H' at H } end /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, 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 β, swap, { simp [supr_of_empty hβ] }, resetI, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f 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) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence 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 finset.measurable_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 open measure lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i)) (hd : pairwise (disjoint on s)) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le (le_refl _) end lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], { congr, funext n, symmetry, apply simple_func.lintegral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, end lemma lintegral_map' [measurable_space β] {f : β → ennreal} {g : α → β} (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) : ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, hf.mk f a ∂(measure.map g μ) : lintegral_congr_ae hf.ae_eq_mk ... = ∫⁻ a, hf.mk f (g a) ∂μ : lintegral_map hf.measurable_mk hg ... = ∫⁻ a, f (g a) ∂μ : lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) lemma lintegral_comp [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) := (lintegral_map hf hg).symm lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (eventually_eq_dirac hf)] lemma ae_lt_top {f : α → ennreal} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ < ⊤) : ∀ᵐ x ∂μ, f x < ⊤ := begin simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, rw [← not_le] at h2f, apply h2f, have : (f ⁻¹' {⊤}).indicator ⊤ ≤ f, { intro x, by_cases hx : x ∈ f ⁻¹' {⊤}; [simpa [hx], simp [hx]] }, convert lintegral_mono this, rw [lintegral_indicator _ (hf (is_measurable_singleton ⊤))], simp [ennreal.top_mul, preimage, h] end /-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density (μ : measure α) (f : α → ennreal) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop} (h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c))) (h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g → P f → P g → P (f + g)) (h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f) (hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x)) ⦃f : α → ennreal⦄ (hf : measurable f) : P f := begin convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact λ n, simple_func.induction (λ c s hs, h_ind c hs) (λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) } end namespace measure_theory /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(μ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul {α} [measurable_space α] (μ : measure α) {f : α → ennreal} (h_mf : measurable f) : ∀ {g : α → ennreal}, measurable g → ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c] }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.ennreal_mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x), simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] } end end measure_theory
7d439f8ee96465020a76e0ed5716bb5a019cf761
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/simp2.lean
2963e6d42b5efd2a5c8701558acf793e0f2479b6
[ "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
274
lean
def p (x : Prop) := x @[simp] theorem lemma1 (x : Prop) : p x = x := rfl theorem ex1 (x : Prop) (h : x) : p x := by simp assumption #print ex1 theorem ex2 (x : Prop) (q : Prop → Prop) (h₁ : x) (h₂ : q x = x) : q x := by simp [h₂] assumption #print ex2
06f3cd2a7a2c8ac9ecfd189ff478c3686b42623f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/sheaves/presheaf_of_functions.lean
dc45e84c8b10de9b0f5a9038cd629b962c17d666
[ "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,392
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.yoneda import topology.sheaves.presheaf import topology.category.TopCommRing import topology.continuous_function.algebra /-! # Presheaves of functions We construct some simple examples of presheaves of functions on a topological space. * `presheaf_to_Types X T`, where `T : X → Type`, is the presheaf of dependently-typed (not-necessarily continuous) functions * `presheaf_to_Type X T`, where `T : Type`, is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T` * `presheaf_to_Top X T`, where `T : Top`, is the presheaf of continuous functions into a topological space `T` * `presheaf_To_TopCommRing X R`, where `R : TopCommRing` is the presheaf valued in `CommRing` of functions functions into a topological ring `R` * as an example of the previous construction, `presheaf_to_TopCommRing X (TopCommRing.of ℂ)` is the presheaf of rings of continuous complex-valued functions on `X`. -/ universes v u open category_theory open topological_space open opposite namespace Top variables (X : Top.{v}) /-- The presheaf of dependently typed functions on `X`, with fibres given by a type family `T`. There is no requirement that the functions are continuous, here. -/ def presheaf_to_Types (T : X → Type v) : X.presheaf (Type v) := { obj := λ U, Π x : (unop U), T x, map := λ U V i g, λ (x : unop V), g (i.unop x) } @[simp] lemma presheaf_to_Types_obj {T : X → Type v} {U : (opens X)ᵒᵖ} : (presheaf_to_Types X T).obj U = Π x : (unop U), T x := rfl @[simp] lemma presheaf_to_Types_map {T : X → Type v} {U V : (opens X)ᵒᵖ} {i : U ⟶ V} {f} : (presheaf_to_Types X T).map i f = λ x, f (i.unop x) := rfl /-- The presheaf of functions on `X` with values in a type `T`. There is no requirement that the functions are continuous, here. -/ -- We don't just define this in terms of `presheaf_to_Types`, -- as it's helpful later to see (at a syntactic level) that `(presheaf_to_Type X T).obj U` -- is a non-dependent function. -- We don't use `@[simps]` to generate the projection lemmas here, -- as it turns out to be useful to have `presheaf_to_Type_map` -- written as an equality of functions (rather than being applied to some argument). def presheaf_to_Type (T : Type v) : X.presheaf (Type v) := { obj := λ U, (unop U) → T, map := λ U V i g, g ∘ i.unop } @[simp] lemma presheaf_to_Type_obj {T : Type v} {U : (opens X)ᵒᵖ} : (presheaf_to_Type X T).obj U = ((unop U) → T) := rfl @[simp] lemma presheaf_to_Type_map {T : Type v} {U V : (opens X)ᵒᵖ} {i : U ⟶ V} {f} : (presheaf_to_Type X T).map i f = f ∘ i.unop := rfl /-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/ def presheaf_to_Top (T : Top.{v}) : X.presheaf (Type v) := (opens.to_Top X).op ⋙ (yoneda.obj T) @[simp] lemma presheaf_to_Top_obj (T : Top.{v}) (U : (opens X)ᵒᵖ) : (presheaf_to_Top X T).obj U = ((opens.to_Top X).obj (unop U) ⟶ T) := rfl /-- The (bundled) commutative ring of continuous functions from a topological space to a topological commutative ring, with pointwise multiplication. -/ -- TODO upgrade the result to TopCommRing? def continuous_functions (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) : CommRing.{v} := CommRing.of (unop X ⟶ (forget₂ TopCommRing Top).obj R) namespace continuous_functions /-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/ def pullback {X Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) : continuous_functions X R ⟶ continuous_functions Y R := { to_fun := λ g, f.unop ≫ g, map_one' := rfl, map_zero' := rfl, map_add' := by tidy, map_mul' := by tidy } /-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`; this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/ def map (X : Top.{u}ᵒᵖ) {R S : TopCommRing.{u}} (φ : R ⟶ S) : continuous_functions X R ⟶ continuous_functions X S := { to_fun := λ g, g ≫ ((forget₂ TopCommRing Top).map φ), map_one' := by ext; exact φ.1.map_one, map_zero' := by ext; exact φ.1.map_zero, map_add' := by intros; ext; apply φ.1.map_add, map_mul' := by intros; ext; apply φ.1.map_mul } end continuous_functions /-- An upgraded version of the Yoneda embedding, observing that the continuous maps from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/ def CommRing_yoneda : TopCommRing.{u} ⥤ (Top.{u}ᵒᵖ ⥤ CommRing.{u}) := { obj := λ R, { obj := λ X, continuous_functions X R, map := λ X Y f, continuous_functions.pullback f R }, map := λ R S φ, { app := λ X, continuous_functions.map X φ } } /-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with values in some topological commutative ring `T`. For example, we could construct the presheaf of continuous complex valued functions of `X` as ``` presheaf_to_TopCommRing X (TopCommRing.of ℂ) ``` (this requires `import topology.instances.complex`). -/ def presheaf_to_TopCommRing (T : TopCommRing.{v}) : X.presheaf CommRing.{v} := (opens.to_Top X).op ⋙ (CommRing_yoneda.obj T) end Top
b7548323162d21d560335a231ba23f02784b8626
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Init/Data/Array/Basic.lean
7a169dac23b3d1e00e1f8c46fef5d9964c115302
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
27,589
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Util universe u v w namespace Array variable {α : Type u} @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { data := List.replicate n v } @[simp] theorem size_mkArray (n : Nat) (v : α) : (mkArray n v).size = n := List.length_replicate .. instance : EmptyCollection (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) where default := Array.empty def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def back? (a : Array α) : Option α := a.get? (a.size - 1) -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ @[simp] theorem size_set (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := List.length_set .. @[simp] theorem size_push (a : Array α) (v : α) : (push a v).size = a.size + 1 := List.length_concat .. /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i let v₂ := a.get j let a' := a.set i v₂ a'.set (size_set a i v₂ ▸ j) v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i let a := a.set i v (e, a) @[inline] def swapAt! (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else have : Inhabited α := ⟨v⟩ panic! ("index " ++ toString i ++ " out of bounds") @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { data := a.data.dropLast } def shrink (a : Array α) (n : Nat) : Array α := let rec loop | 0, a => a | n+1, a => loop n a.pop loop (a.size - n) a @[inline] def modifyM [Monad m] [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := do if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩ let v := a.get idx let a' := a.set idx arbitrary let v ← f v pure <| a'.set (size_set a .. ▸ idx) v else pure a @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run <| a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/ @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b -- Move? private theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b | 0, _, h => h | a+1, b, h => have : a < b := Nat.ltTrans (Nat.ltSuccSelf _) h zeroLtOfLt this /- Reference implementation for `forIn` -/ @[implementedBy Array.forInUnsafe] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have : as.size - 1 < as.size := Nat.subLt (zeroLtOfLt h') (by decide) have : as.size - 1 - i < as.size := Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b instance : ForIn m (Array α) α where forIn := Array.forIn /- See comment at forInUnsafe -/ @[inline] unsafe def foldlMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.leRefl _) /- See comment at forInUnsafe -/ @[inline] unsafe def foldrMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i-1) stop (← f (as.uget (i-1) lcProof) b) if start ≤ as.size then if stop < start then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else if stop < as.size then fold (USize.ofNat as.size) (USize.ofNat stop) init else pure init /- Reference implementation for `foldrM` -/ @[implementedBy foldrMUnsafe] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec fold (i : Nat) (h : i ≤ as.size) (b : β) : m β := do if i == stop then pure b else match i, h with | 0, _ => pure b | i+1, h => have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h fold i (Nat.leOfLt this) (← f (as.get ⟨i, this⟩) b) if h : start ≤ as.size then if stop < start then fold start h init else pure init else if stop < as.size then fold as.size (Nat.leRefl _) init else pure init /- See comment at forInUnsafe -/ @[inline] unsafe def mapMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := let sz := USize.ofNat as.size let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do if i < sz then let v := r.uget i lcProof let r := r.uset i arbitrary lcProof let vNew ← f (unsafeCast v) map (i+1) (r.uset i (unsafeCast vNew) lcProof) else pure (unsafeCast r) unsafeCast <| map 0 (unsafeCast as) /- Reference implementation for `mapM` -/ @[implementedBy mapMUnsafe] def mapM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do let b ← f a; pure (bs.push b)) (mkEmpty as.size) @[inline] def mapIdxM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : Fin as.size → α → m β) : m (Array β) := let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array β) : m (Array β) := do match i, inv with | 0, _ => pure bs | i+1, inv => have : j < as.size := by rw [← inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_left_comm]; apply Nat.leAddRight let idx : Fin as.size := ⟨j, this⟩ have : i + (j + 1) = as.size := by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] map i (j+1) this (bs.push (← f idx (as.get idx))) map as.size 0 rfl (mkEmpty as.size) @[inline] def findSomeM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := do for a in as do match (← f a) with | some b => return b | _ => pure ⟨⟩ return none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := do for a in as do if (← p a) then return a return none @[inline] def findIdxM? [Monad m] (as : Array α) (p : α → m Bool) : m (Option Nat) := do let mut i := 0 for a in as do if (← p a) then return some i i := i + 1 return none @[inline] unsafe def anyMUnsafe {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do if i == stop then pure false else if (← p (as.uget i lcProof)) then pure true else any (i+1) stop if start < stop then if stop ≤ as.size then any (USize.ofNat start) (USize.ofNat stop) else pure false else pure false @[implementedBy anyMUnsafe] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let any (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) : m Bool := do if hlt : j < stop then match i with | 0 => pure false | i'+1 => if (← p (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) then pure true else loop i' (j+1) else pure false loop (stop - start) start if h : stop ≤ as.size then any stop h else any as.size (Nat.leRefl _) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := return !(← as.anyM fun v => return !(← p v)) @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, h => pure none | i+1, h => do have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h let r ← f (as.get ⟨i, this⟩) match r with | some v => pure r | none => have : i ≤ as.size := Nat.leOfLt this find i this find as.size (Nat.leRefl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := 0) (stop := as.size) : m PUnit := as.foldlM (fun _ => f) ⟨⟩ start stop @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := as.size) (stop := 0) : m PUnit := as.foldrM (fun a _ => f a) ⟨⟩ start stop @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Array α) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Array α) (start := as.size) (stop := 0) : β := Id.run <| as.foldrM f init start stop @[inline] def map {α : Type u} {β : Type v} (f : α → β) (as : Array α) : Array β := Id.run <| as.mapM f @[inline] def mapIdx {α : Type u} {β : Type v} (as : Array α) (f : Fin as.size → α → β) : Array β := Id.run <| as.mapIdxM f @[inline] def find? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findM? p @[inline] def findSome? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeM? f @[inline] def findSome! {α : Type u} {β : Type v} [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeRevM? f @[inline] def findRev? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p @[inline] def findIdx? {α : Type u} (as : Array α) (p : α → Bool) : Option Nat := let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat := if hlt : j < as.size then match i, inv with | 0, inv => by apply False.elim rw [Nat.zero_add] at inv rw [inv] at hlt exact absurd hlt (Nat.ltIrrefl _) | i+1, inv => if p (as.get ⟨j, hlt⟩) then some j else have : i + (j+1) = as.size := by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] loop i (j+1) this else none loop as.size 0 rfl def getIdx? [BEq α] (a : Array α) (v : α) : Option Nat := a.findIdx? fun a => a == v @[inline] def any (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.anyM p start stop @[inline] def all (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.allM p start stop def contains [BEq α] (as : Array α) (a : α) : Bool := as.any fun b => a == b def elem [BEq α] (a : α) (as : Array α) : Bool := as.contains a -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverse (as : Array α) : Array α := let n := as.size let mid := n / 2 let rec rev (as : Array α) (i : Nat) := if i < mid then rev (as.swap! i (n - i - 1)) (i+1) else as rev as 0 @[inline] def getEvenElems (as : Array α) : Array α := (·.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a => if even then (false, r.push a) else (true, r) @[export lean_array_to_list] def toList (as : Array α) : List α := as.foldr List.cons [] instance {α : Type u} [Repr α] : Repr (Array α) where reprPrec a _ := if a.size == 0 then "#[]" else Std.Format.bracketFill "#[" (@Std.Format.joinSep _ ⟨repr⟩ (toList a) ("," ++ Std.Format.line)) "]" instance [ToString α] : ToString (Array α) where toString a := "#" ++ toString a.toList protected def append (as : Array α) (bs : Array α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : Append (Array α) := ⟨Array.append⟩ protected def appendList (as : Array α) (bs : List α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : HAppend (Array α) (List α) (Array α) := ⟨Array.appendList⟩ @[inline] def concatMapM [Monad m] (f : α → m (Array β)) (as : Array α) : m (Array β) := as.foldlM (init := empty) fun bs a => do return bs ++ (← f a) @[inline] def concatMap (f : α → Array β) (as : Array α) : Array β := as.foldl (init := empty) fun bs a => bs ++ f a end Array export Array (mkArray) syntax "#[" sepBy(term, ", ") "]" : term macro_rules | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ]) namespace Array -- TODO(Leo): cleanup @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [BEq α] : BEq (Array α) := ⟨fun a b => isEqv a b BEq.beq⟩ @[inline] def filter (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Array α := as.foldl (init := #[]) (start := start) (stop := stop) fun r a => if p a then r.push a else r @[inline] def filterM [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m (Array α) := as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do if (← p a) then r.push a else r @[specialize] def filterMapM [Monad m] (f : α → m (Option β)) (as : Array α) (start := 0) (stop := as.size) : m (Array β) := as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do match (← f a) with | some b => pure (bs.push b) | none => pure bs @[inline] def filterMap (f : α → Option β) (as : Array α) (start := 0) (stop := as.size) : Array β := Id.run <| as.filterMapM f (start := start) (stop := stop) @[specialize] def getMax? (as : Array α) (lt : α → α → Bool) : Option α := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩ some <| as.foldl (init := a0) (start := 1) fun best a => if lt best a then a else best else none @[inline] def partition (p : α → Bool) (as : Array α) : Array α × Array α := do let mut bs := #[] let mut cs := #[] for a in as do if p a then bs := bs.push a else cs := cs.push a return (bs, cs) theorem ext (a b : Array α) (h₁ : a.size = b.size) (h₂ : (i : Nat) → (hi₁ : i < a.size) → (hi₂ : i < b.size) → a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) : a = b := by let rec extAux (a b : List α) (h₁ : a.length = b.length) (h₂ : (i : Nat) → (hi₁ : i < a.length) → (hi₂ : i < b.length) → a.get i hi₁ = b.get i hi₂) : a = b := by induction a generalizing b with | nil => cases b with | nil => rfl | cons b bs => rw [List.length_cons] at h₁; injection h₁ | cons a as ih => cases b with | nil => rw [List.length_cons] at h₁; injection h₁ | cons b bs => have hz₁ : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zeroLtSucc have hz₂ : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zeroLtSucc have headEq : a = b := h₂ 0 hz₁ hz₂ have h₁' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h₁; injection h₁; assumption have h₂' : (i : Nat) → (hi₁ : i < as.length) → (hi₂ : i < bs.length) → as.get i hi₁ = bs.get i hi₂ := by intro i hi₁ hi₂ have hi₁' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have hi₂' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have : (a::as).get (i+1) hi₁' = (b::bs).get (i+1) hi₂' := h₂ (i+1) hi₁' hi₂' apply this have tailEq : as = bs := ih bs h₁' h₂' rw [headEq, tailEq] cases a; cases b apply congrArg apply extAux assumption assumption theorem extLit {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : (i : Nat) → (hi : i < n) → a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array -- CLEANUP the following code namespace Array partial def indexOfAux [BEq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux a v (i+1) else none def indexOf? [BEq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a @[simp] theorem size_swap (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := by show ((a.set i (a.get j)).set (size_set a i _ ▸ j) (a.get i)).size = a.size rw [size_set, size_set] @[simp] theorem size_pop (a : Array α) : a.pop.size = a.size - 1 := List.length_dropLast .. section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } where default := ⟨a.pop, size_pop a⟩ partial def eraseIdxSzAux (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq) else ⟨r.pop, (size_pop r).trans (heq ▸ rfl)⟩ end def eraseIdx' (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def erase [BEq α] (as : Array α) (a : α) : Array α := match as.indexOf? a with | none => as | some i => as.feraseIdx i partial def insertAtAux (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux i as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size def toListLitAux (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc) def toArrayLit (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray <| toListLitAux a n hsz n (hsz ▸ Nat.leRefl _) [] theorem toArrayLitEq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove ∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List α) (hi : 0 ≤ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List α) (hi : i+1 ≤ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have ∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ [] -/ partial def isPrefixOfAux [BEq α] (as bs : Array α) (hle : as.size ≤ bs.size) : Nat → Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.ltOfLtOfLe h hle⟩; if a == b then isPrefixOfAux as bs hle (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf [BEq α] (as bs : Array α) : Bool := if h : as.size ≤ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux [BEq α] (as : Array α) (a : α) : forall (i : Nat), i < as.size → Bool | 0, h => true | i+1, h => have : i < as.size := Nat.ltTrans (Nat.ltSuccSelf _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux as a i this private partial def allDiffAux [BEq α] (as : Array α) : Nat → Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux as (i+1) else true def allDiff [BEq α] (as : Array α) : Bool := allDiffAux as 0 @[specialize] partial def zipWithAux (f : α → β → γ) (as : Array α) (bs : Array β) : Nat → Array γ → Array γ | i, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; if h : i < bs.size then let b := bs.get ⟨i, h⟩; zipWithAux f as bs (i+1) <| cs.push <| f a b else cs else cs @[inline] def zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : Array γ := zipWithAux f as bs 0 #[] def zip (as : Array α) (bs : Array β) : Array (α × β) := zipWith as bs Prod.mk def unzip (as : Array (α × β)) : Array α × Array β := as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b) def split (as : Array α) (p : α → Bool) : Array α × Array α := as.foldl (init := (#[], #[])) fun (as, bs) a => if p a then (as.push a, bs) else (as, bs.push a) end Array
29fd7239932feda166c8aaa8281a632602319258
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/polynomial.lean
80cf1f4c89d0720dfa137611072cd6a8d34ddbe3
[ "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
97,008
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, Jens Wagemaker Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring. -/ import data.finsupp algebra.gcd_domain ring_theory.euclidean_domain tactic.ring ring_theory.multiplicity local attribute [instance, priority 0] nat.cast_coe /-- `polynomial α` is the type of univariate polynomials over `α`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from α is called `C`. -/ def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α open finsupp finset lattice namespace polynomial universes u v variables {α : Type u} {β : Type v} {a b : α} {m n : ℕ} section comm_semiring variables [comm_semiring α] [decidable_eq α] {p q r : polynomial α} instance : has_zero (polynomial α) := finsupp.has_zero instance : has_one (polynomial α) := finsupp.has_one instance : has_add (polynomial α) := finsupp.has_add instance : has_mul (polynomial α) := finsupp.has_mul instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring instance : decidable_eq (polynomial α) := finsupp.decidable_eq def polynomial.has_coe_to_fun : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun local attribute [instance] finsupp.to_comm_semiring polynomial.has_coe_to_fun @[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl /-- `C a` is the constant polynomial `a`. -/ def C (a : α) : polynomial α := single 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial α := single 1 1 /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial α) := p.to_fun @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial α) = f := rfl instance [has_repr α] : has_repr (polynomial α) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ theorem ext {p q : polynomial α} : p = q ↔ ∀ n, coeff p n = coeff q n := ⟨λ h n, h ▸ rfl, finsupp.ext⟩ /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) @[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by simpa only [C, single_zero], h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X], h_add _ _ this hp) @[simp] lemma C_0 : C (0 : α) = 0 := single_zero @[simp] lemma C_1 : C (1 : α) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := (@single_mul_single _ _ _ _ _ _ 0 0 a b).symm @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_pow : C (a ^ n) = C a ^ n := is_semiring_hom.map_pow _ _ _ section coeff lemma apply_eq_coeff : p n = coeff p n := rfl @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial α) n = 0 := rfl @[simp] lemma coeff_one_zero (n : ℕ) : coeff (1 : polynomial α) 0 = 1 := rfl @[simp] lemma coeff_add (p q : polynomial α) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by simp [coeff, eq_comm, C, single]; congr @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := rfl @[simp] lemma coeff_X_one : coeff (X : polynomial α) 1 = 1 := rfl @[simp] lemma coeff_X_zero : coeff (X : polynomial α) 0 = 0 := rfl lemma coeff_X : coeff (X : polynomial α) n = if 1 = n then 1 else 0 := rfl @[simp] lemma coeff_C_mul_X (x : α) (k n : ℕ) : coeff (C x * X^k : polynomial α) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [single, eq_comm, coeff]; congr lemma coeff_sum [comm_semiring β] [decidable_eq β] (n : ℕ) (f : ℕ → α → polynomial β) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := rfl @[simp] lemma coeff_C_mul (p : polynomial α) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, coeff_sum] }, rw [mul_def, C, sum_single_index], { simp [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, simp end @[simp] lemma coeff_one (n : ℕ) : coeff (1 : polynomial α) n = if 0 = n then 1 else 0 := rfl @[simp] lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial α) n = if n = k then 1 else 0 := by simpa only [C_1, one_mul] using coeff_C_mul_X (1:α) k n lemma coeff_mul_left (p q : polynomial α) (n : ℕ) : coeff (p * q) n = (range (n+1)).sum (λ k, coeff p k * coeff q (n-k)) := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : α)) (by rwa if_neg h at ha)), calc coeff (p * q) n = sum (p.support) (λ a, sum (q.support) (λ b, ite (a + b = n) (coeff p a * coeff q b) 0)) : by simp only [finsupp.mul_def, coeff_sum, coeff_single]; refl ... = (p.support.product q.support).sum (λ v : ℕ × ℕ, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0) : by rw sum_product ... = (range (n+1)).sum (λ k, coeff p k * coeff q (n-k)) : sum_bij_ne_zero (λ a _ _, a.1) (λ a _ ha, mem_range.2 (nat.lt_succ_of_le (hite a ha ▸ le_add_right (le_refl _)))) (λ a₁ a₂ _ h₁ _ h₂ h, prod.ext h ((add_left_inj a₁.1).1 (by rw [hite a₁ h₁, h, hite a₂ h₂]))) (λ a h₁ h₂, ⟨(a, n - a), mem_product.2 ⟨mem_support_iff.2 (ne_zero_of_mul_ne_zero_right h₂), mem_support_iff.2 (ne_zero_of_mul_ne_zero_left h₂)⟩, by simpa [nat.add_sub_cancel' (nat.le_of_lt_succ (mem_range.1 h₁))], rfl⟩) (λ a _ ha, by rw [← hite a ha, if_pos rfl, nat.add_sub_cancel_left]) lemma coeff_mul_right (p q : polynomial α) (n : ℕ) : coeff (p * q) n = (range (n+1)).sum (λ k, coeff p (n-k) * coeff q k) := by rw [mul_comm, coeff_mul_left]; simp only [mul_comm] theorem coeff_mul_X_pow (p : polynomial α) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul_right, sum_eq_single n, coeff_X_pow, if_pos rfl, mul_one, nat.add_sub_cancel], { intros b h1 h2, rw [coeff_X_pow, if_neg h2, mul_zero] }, { exact λ h1, (h1 (mem_range.2 (nat.le_add_left _ _))).elim } end theorem coeff_mul_X (p : polynomial α) (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 α} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext.2 $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext.1 H (k+n) end coeff lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ section eval₂ variables [semiring β] variables (f : α → β) (x : β) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial α) : β := p.sum (λ e a, f a * x ^ e) variables [is_semiring_hom f] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one] @[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [map_zero f, zero_mul]) (λ _ _ _, by rw [map_add f, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } end eval₂ section eval₂ variables [comm_semiring β] variables (f : α → β) [is_semiring_hom f] (x : β) open is_semiring_hom @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, map_mul f, pow_add], { simp only [mul_assoc, mul_left_comm] }, { rw [map_zero f, zero_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ lemma eval₂_sum (p : polynomial α) (g : ℕ → α → polynomial α) (x : β) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) end eval₂ section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : α → polynomial α → α := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval_sum (p : polynomial α) (f : ℕ → α → polynomial α) (x : α) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval₂_hom [comm_semiring β] (f : α → β) [is_semiring_hom f] (x : α) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, eval_pow, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma coeff_zero_eq_eval_zero (p : polynomial α) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) end eval section comp def comp (p q : polynomial α) : polynomial α := p.eval₂ C q lemma eval₂_comp [comm_semiring β] (f : α → β) [is_semiring_hom f] {x : β} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q), by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ @[simp] lemma comp_X : p.comp X = p := begin refine polynomial.ext.2 (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, rw finsupp.sum_single end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← sum_hom (@C α _ _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial α) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial α) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial α) p = 1 := by rw [← C_1, C_comp] instance : is_semiring_hom (λ q : polynomial α, q.comp p) := by unfold comp; apply_instance @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp section map variables [comm_semiring β] [decidable_eq β] variables (f : α → β) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial α → polynomial β := eval₂ (C ∘ f) X variables [is_semiring_hom f] @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← finset.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map {γ : Type*} [comm_semiring γ] [decidable_eq γ] (g : β → γ) [is_semiring_hom g] (p : polynomial α) : (p.map f).map g = p.map (λ x, g (f x)) := polynomial.ext.2 (by simp [coeff_map]) lemma eval₂_map {γ : Type*} [comm_semiring γ] (g : β → γ) [is_semiring_hom g] (x : γ) : (p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma eval_map (x : β) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _ @[simp] lemma map_id : p.map id = p := by simp [id, polynomial.ext, coeff_map] end map /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := rfl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma nat_degree_eq_of_degree_eq_some {p : polynomial α} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [comm_semiring β] [decidable_eq β] {q : polynomial β} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial α) = 0 := nat_degree_C 1 @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine polynomial.ext.2 (λ n, _), cases n, { refl }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h) lemma degree_sum_le [decidable_eq β] (s : finset β) (f : β → polynomial α) : degree (s.sum f) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ _ _ n a } end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial α) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial α) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = (range (nat_degree p + nat_degree q + 1)).sum (λ k, coeff p k * coeff q (nat_degree p + nat_degree q - k)) : coeff_mul_left _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree p + nat_degree q - nat_degree p) : finset.sum_eq_single _ (λ n hn₁ hn₂, (le_total n (nat_degree p)).elim (λ h, have degree q < (nat_degree p + nat_degree q - n : ℕ), from lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_sub_left_iff_add_lt.2 (add_lt_add_right (lt_of_le_of_ne h hn₂) _))), by simp [coeff_eq_zero_of_degree_lt this]) (λ h, have degree p < n, from lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (lt_of_le_of_ne h hn₂.symm)), by simp [coeff_eq_zero_of_degree_lt this])) (λ h, false.elim (h (mem_range.2 (lt_of_le_of_lt (nat.le_add_right _ _) (nat.lt_succ_self _))))) ... = _ : by simp [leading_coeff, nat.add_sub_cancel_left] lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁] lemma nat_degree_pow_eq' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow_eq' h, degree_eq_nat_degree hp0, ← with_bot.coe_smul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : α) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (degree q) : add_le_add' degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (nat_degree q) : add_le_add_left' (add_monoid.smul_le_smul_of_le_right (@degree_le_nat_degree _ _ _ q) n) ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_smul, add_monoid.smul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] : degree (p.map f) ≤ degree p := if h : p.map f = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) : (∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma degree_map_eq_of_leading_coeff_ne_zero [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma degree_map_eq_of_injective [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hf : function.injective f) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma monic_map [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hp : monic p) : monic (p.map f) := if h : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map, ← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f] lemma zero_le_degree_iff {p : polynomial α} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial @[simp] lemma coeff_mul_X_zero (p : polynomial α) : coeff (p * X) 0 = 0 := by rw [coeff_mul_left, sum_range_succ]; simp instance [subsingleton α] : subsingleton (polynomial α) := ⟨λ _ _, polynomial.ext.2 (λ _, subsingleton.elim _ _)⟩ lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : α) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := polynomial.ext.2 (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : α) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial α) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:α) n theorem degree_X_le : degree (X : polynomial α) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:α) 1 lemma degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α) {f : α → β} [is_semiring_hom f] (hf : function.injective f) : degree (p.map f) = degree p := degree_map_eq_of_injective _ hf lemma nat_degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α) {f : α → β} [is_semiring_hom f] (hf : function.injective f) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' _ hf) theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one α $ H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : α) : monic (X + C x) := pow_one (X : polynomial α) ▸ monic_X_pow_add degree_C_le theorem degree_le_iff_coeff_zero (f : polynomial α) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem nat_degree_le_of_degree_le {p : polynomial α} {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end theorem leading_coeff_mul_X_pow {p : polynomial α} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (assume H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (assume H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : α) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : α) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_ge_one_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section nonzero_comm_semiring variables [nonzero_comm_semiring α] [decidable_eq α] {p q : polynomial α} instance : nonzero_comm_semiring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_semiring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X degree single finsupp.support, rw if_neg (zero_ne_one).symm, refl end lemma X_ne_zero : (X : polynomial α) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simpa only [monic, leading_coeff_zero] using zero_ne_one lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero α _ _ (h₁ ▸ h) end nonzero_comm_semiring section comm_semiring variables [comm_semiring α] [decidable_eq α] {p q : polynomial α} /-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial α) : polynomial α := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm, apply_eq_coeff], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial α) : div_X p * X + C (p.coeff 0) = p := polynomial.ext.2 $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : α) : div_X (C a) = 0 := polynomial.ext.2 $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := polynomial.ext.2 $ by simp [div_X] def nonzero_comm_semiring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_semiring α := { zero_ne_one := λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero], ..show comm_semiring α, by apply_instance } lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul_eq' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp0; exact calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne lattice.bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial α) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul_eq' this]; exact add_le_add' (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add @[elab_as_eliminator] def rec_on_horner {M : polynomial α → Sort*} : Π (p : polynomial α), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial α → Prop} (p : polynomial α) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, not_lt.2 (@lattice.bot_le ( ℕ) _ _)] using h0')) h0 end comm_semiring section comm_ring variables [comm_ring α] [decidable_eq α] {p q : polynomial α} instance : comm_ring (polynomial α) := finsupp.to_comm_ring instance : has_scalar α (polynomial α) := finsupp.to_has_scalar -- TODO if this becomes a semimodule then the below lemma could be proved for semimodules instance : module α (polynomial α) := finsupp.to_module ℕ α -- TODO -- this is OK for semimodules @[simp] lemma coeff_smul (p : polynomial α) (r : α) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply -- TODO -- this is OK for semimodules lemma C_mul' (a : α) (f : polynomial α) : C a * f = a • f := ext.2 $ λ n, coeff_C_mul f variable (α) def lcoeff (n : ℕ) : polynomial α →ₗ α := { to_fun := λ f, coeff f n, add := λ f g, coeff_add f g n, smul := λ r p, coeff_smul p r n } variable {α} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial α) : lcoeff α n f = coeff f n := rfl instance C.is_ring_hom : is_ring_hom (@C α _ _) := by apply is_ring_hom.of_semiring @[simp] lemma C_neg : C (-a) = -C a := is_ring_hom.map_neg C @[simp] lemma C_sub : C (a - b) = C a - C b := is_ring_hom.map_sub C instance eval₂.is_ring_hom {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma map_sub {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma coeff_neg (p : polynomial α) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial α) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma eval₂_neg {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (-p).eval₂ f x = -p.eval₂ f x := is_ring_hom.map_neg _ @[simp] lemma eval₂_sub {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := is_ring_hom.map_sub _ @[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial α), p = 0, from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma div_mod_by_monic_unique {f g} (q r : polynomial α) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial α))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01α : (0 : α) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01α) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial α) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial α) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end theorem monic_X_sub_C (x : α) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) theorem degree_mod_by_monic_le (p : polynomial α) {q : polynomial α} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial α) = 1 := (by rw [← C_0, ← C_1, hq]); rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] def nonzero_comm_ring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_ring α := { zero := 0, one := 1, zero_ne_one := λ h01, h $ by rw [← one_mul p, ← one_mul q, ← C_1, ← h01, C_0, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] [decidable_eq α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { ..polynomial.nonzero_comm_semiring, ..polynomial.comm_ring } @[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : degree ((X : polynomial α) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial α) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) : (X : polynomial α) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) end nonzero_comm_ring section comm_ring variables [comm_ring α] [decidable_eq α] {p q : polynomial α} @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : α) = 1 then by letI := subsingleton_of_zero_eq_one α h0; exact subsingleton.elim _ _ else by letI : nonzero_comm_ring α := nonzero_comm_ring.of_ne h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial α) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity def decidable_dvd_monic (p : polynomial α) (hq : monic q): decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) local attribute [instance, priority 0] classical.dec lemma multiplicity_X_sub_C_finite (a : α) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : α) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact h0 (subsingleton.elim _ _)), by letI : nonzero_comm_ring α := { zero_ne_one := this, ..show comm_ring α, by apply_instance }; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 def root_multiplicity (a : α) (p : polynomial α) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial α) (a : α) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial α) (a : α) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial α) (a : α) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial α} (a : α) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin letI : nonzero_comm_ring α := nonzero_comm_ring.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) _ hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring section integral_domain variables [integral_domain α] [decidable_eq α] {p q : polynomial α} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; [simp only [pow_zero, degree_one, add_monoid.zero_smul], simp only [*, pow_succ, succ_smul, degree_mul_eq]] @[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; [simp only [pow_zero, leading_coeff_one], simp only [*, pow_succ, leading_coeff_mul]] instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma nat_degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul_eq] @[simp] lemma nat_degree_pow_eq (p : polynomial α) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow_eq' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : (roots ((X : polynomial α) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ noncomputable def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α := by letI := classical.prop_decidable; exact roots ((X : polynomial α) ^ n - C a) @[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} : x ∈ nth_roots n a ↔ x ^ n = a := by letI := classical.prop_decidable; rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : (nth_roots n a).card ≤ n := by letI := classical.prop_decidable; exact if hn : n = 0 then if h : (X : polynomial α) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← @C_1 α _ _, ← is_ring_hom.map_sub (@C α _ _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff], dsimp [apply_eq_coeff], refine coeff_eq_zero_of_degree_lt _, rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_smul, add_monoid.smul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2 (lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp) end (by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero, classical.not_not]; simp {contextual := tt}) ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow_eq], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0): leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial α) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm, add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial α)) : degree (u : polynomial α) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial α)) : nat_degree (u : polynomial α) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma coeff_coe_units_zero_ne_zero (u : units (polynomial α)) : coeff (u : polynomial α) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] end integral_domain section field variables [discrete_field α] {p q : polynomial α} instance : vector_space α (polynomial α) := { ..finsupp.to_module ℕ α } lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact hp ⟨units.map C (units.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0))), rfl⟩) lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := ⟨mt is_unit_iff_dvd_one.1 (λ ⟨q, hq⟩, absurd (congr_arg degree hq) (λ h, have degree q = 0, by rw [degree_one, degree_mul_eq, hp1, eq_comm, nat.with_bot.add_eq_zero_iff] at h; exact h.2, by simp [degree_mul_eq, this, degree_one, hp1] at h; exact absurd h dec_trivial)), λ q r hpqr, begin have := congr_arg degree hpqr, rw [hp1, degree_mul_eq, eq_comm, nat.with_bot.add_eq_one_iff] at this, rw [is_unit_iff_degree_eq_zero, is_unit_iff_degree_eq_zero]; tautology end⟩ lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial α) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial α) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial α) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial α) := ⟨div⟩ instance : has_mod (polynomial α) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial α) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} lemma degree_div_le (p q : polynomial α) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [discrete_field β] (p : polynomial α) (f : α → β) [is_field_hom f] : degree (p.map f) = degree p := degree_map_eq_of_injective _ (is_field_hom.injective f) @[simp] lemma nat_degree_map [discrete_field β] (f : α → β) [is_field_hom f] : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [discrete_field β] (f : α → β) [is_field_hom f] : leading_coeff (p.map f) = f (leading_coeff p) := by simp [leading_coeff, coeff_map f] lemma map_div [discrete_field β] (f : α → β) [is_field_hom f] : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [is_field_hom.map_inv f, leading_coeff, coeff_map f] lemma map_mod [discrete_field β] (f : α → β) [is_field_hom f] : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← is_field_hom.map_inv f, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] @[simp] lemma map_eq_zero [discrete_field β] (f : α → β) [is_field_hom f] : p.map f = 0 ↔ p = 0 := by simp [polynomial.ext, is_field_hom.map_eq_zero f, coeff_map] lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial α)) (n : ℕ) : ((↑u : polynomial α).coeff n)⁻¹ = ((↑u⁻¹ : polynomial α).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end instance : normalization_domain (polynomial α) := { norm_unit := λ p, if hp0 : p = 0 then 1 else ⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rw [← C_mul, inv_mul_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0, by rw [← C_mul, mul_inv_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0,⟩, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ p q hp0 hq0, begin rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)], apply units.ext, show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹, rw [leading_coeff_mul, mul_inv', C_mul, mul_comm] end, norm_unit_coe_units := λ u, have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩, begin apply units.ext, rw [dif_neg (units.coe_ne_zero u)], conv_rhs {rw eq_C_of_degree_eq_zero hu}, refine C_inj.2 _, rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff, coeff_inv_units], simp end, ..polynomial.integral_domain } lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := show leading_coeff (p * ↑(dite _ _ _)) = 1, by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0 lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial α) = C p.leading_coeff⁻¹ := show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl end field section derivative variables [comm_semiring α] [decidable_eq α] /-- `derivative p` formal derivative of the polynomial `p` -/ def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial α) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff], { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul] }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] } end @[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp only [zero_mul, C_0]; refl @[simp] lemma derivative_C {a : α} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial α) = 1 := suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ 0, by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero], derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial α} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] instance : is_add_monoid_hom (derivative : polynomial α → polynomial α) := { map_add := λ _ _, derivative_add, map_zero := derivative_zero } @[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := (finset.sum_hom derivative).symm @[simp] lemma derivative_mul {f g : polynomial α} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial α) (x : α) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow] end derivative section domain variables [integral_domain α] [decidable_eq α] lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : α) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero], by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false] @[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {α : Type*} [comm_semiring α] (x y : α) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, rw [_root_.pow_succ, hz], existsi (x*z + (n+1)*x^n+z*y), simp [_root_.pow_succ], ring -- expensive! end variables [comm_ring α] [decidable_eq α] private def poly_binom_aux1 (x y : α) (e : ℕ) (a : α) : {k : α // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] def binom_expansion (f : polynomial α) (x y : α) : {k : α // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z : α // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ --sorry --false.elim $ not_lt_of_ge h zero_lt_one | 1 := ⟨1, by simp⟩ | (k+2) := begin cases pow_sub_pow_factor with z hz, existsi z*x + y^(k+1), rw [_root_.pow_succ x, _root_.pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)), ←mul_sub x, hz], simp only [_root_.pow_succ], ring end def eval_sub_factor (f : polynomial α) (x y : α) : {z : α // f.eval x - f.eval y = z*(x - y)} := begin existsi f.sum (λ a b, b * (pow_sub_pow_factor x y).val), unfold eval eval₂, rw [←finsupp.sum_sub], have : finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val) * (x - y) = finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val * (x - y)), { apply finsupp.sum_mul }, rw this, congr, ext e a, rw [mul_assoc, ←(pow_sub_pow_factor x y).property], simp [left_distrib] end end identities end polynomial
0a1c55f87696c24a06051a1d60c4c68abdffcfaa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/perm/list.lean
04aa0067202ee34aa1fbd9d87b1478c3fbe33777
[ "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
17,282
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import group_theory.perm.support /-! # Permutations from a list > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. When there are duplicate elements in `l`, how and in what arrangement with respect to the other elements they appear in the list determines the formed permutation. This is because `list.form_perm` is implemented as a product of `equiv.swap`s. That means that presence of a sublist of two adjacent duplicates like `[..., x, x, ...]` will produce the same permutation as if the adjacent duplicates were not present. The `list.form_perm` definition is meant to primarily be used with `nodup l`, so that the resulting permutation is cyclic (if `l` has at least two elements). The presence of duplicates in a particular placement can lead `list.form_perm` to produce a nontrivial permutation that is noncyclic. -/ namespace list variables {α β : Type*} section form_perm variables [decidable_eq α] (l : list α) open equiv equiv.perm /-- A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. -/ def form_perm : equiv.perm α := (zip_with equiv.swap l l.tail).prod @[simp] lemma form_perm_nil : form_perm ([] : list α) = 1 := rfl @[simp] lemma form_perm_singleton (x : α) : form_perm [x] = 1 := rfl @[simp] lemma form_perm_cons_cons (x y : α) (l : list α) : form_perm (x :: y :: l) = swap x y * form_perm (y :: l) := prod_cons lemma form_perm_pair (x y : α) : form_perm [x, y] = swap x y := rfl variables {l} {x : α} lemma form_perm_apply_of_not_mem (x : α) (l : list α) (h : x ∉ l) : form_perm l x = x := begin cases l with y l, { simp }, induction l with z l IH generalizing x y, { simp }, { specialize IH x z (mt (mem_cons_of_mem y) h), simp only [not_or_distrib, mem_cons_iff] at h, simp [IH, swap_apply_of_ne_of_ne, h] } end lemma mem_of_form_perm_apply_ne (x : α) (l : list α) : l.form_perm x ≠ x → x ∈ l := not_imp_comm.2 $ list.form_perm_apply_of_not_mem _ _ lemma form_perm_apply_mem_of_mem (x : α) (l : list α) (h : x ∈ l) : form_perm l x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : x ∈ z :: l, { rw [form_perm_cons_cons, mul_apply, swap_apply_def], split_ifs; simp [IH _ _ hx] }, { replace h : x = y := or.resolve_right h hx, simp [form_perm_apply_of_not_mem _ _ hx, ←h] } } end lemma mem_of_form_perm_apply_mem (x : α) (l : list α) (h : l.form_perm x ∈ l) : x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : (z :: l).form_perm x ∈ z :: l, { rw [list.form_perm_cons_cons, mul_apply, swap_apply_def] at h, split_ifs at h; simp [IH _ _ hx] }, { replace hx := (function.injective.eq_iff (equiv.injective _)).mp (list.form_perm_apply_of_not_mem _ _ hx), simp only [list.form_perm_cons_cons, hx, equiv.perm.coe_mul, function.comp_app, list.mem_cons_iff, swap_apply_def, ite_eq_left_iff] at h, simp only [list.mem_cons_iff], obtain h | h | h := h; { split_ifs at h; cc }}} end lemma form_perm_mem_iff_mem : l.form_perm x ∈ l ↔ x ∈ l := ⟨l.mem_of_form_perm_apply_mem x, l.form_perm_apply_mem_of_mem x⟩ @[simp] lemma form_perm_cons_concat_apply_last (x y : α) (xs : list α) : form_perm (x :: (xs ++ [y])) y = x := begin induction xs with z xs IH generalizing x y, { simp }, { simp [IH] } end @[simp] lemma form_perm_apply_last (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).last (cons_ne_nil x xs)) = x := begin induction xs using list.reverse_rec_on with xs y IH generalizing x; simp end @[simp] lemma form_perm_apply_nth_le_length (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).nth_le xs.length (by simp)) = x := by rw [nth_le_cons_length, form_perm_apply_last]; refl lemma form_perm_apply_head (x y : α) (xs : list α) (h : nodup (x :: y :: xs)) : form_perm (x :: y :: xs) x = y := by simp [form_perm_apply_of_not_mem _ _ h.not_mem] lemma form_perm_apply_nth_le_zero (l : list α) (h : nodup l) (hl : 1 < l.length) : form_perm l (l.nth_le 0 (zero_lt_one.trans hl)) = l.nth_le 1 hl := begin rcases l with (_|⟨x, _|⟨y, tl⟩⟩), { simp }, { simp }, { simpa using form_perm_apply_head _ _ _ h } end variables (l) lemma form_perm_eq_head_iff_eq_last (x y : α) : form_perm (y :: l) x = y ↔ x = last (y :: l) (cons_ne_nil _ _) := iff.trans (by rw form_perm_apply_last) (form_perm (y :: l)).injective.eq_iff lemma zip_with_swap_prod_support' (l l' : list α) : {x | (zip_with swap l l').prod x ≠ x} ≤ l.to_finset ⊔ l'.to_finset := begin simp only [set.sup_eq_union, set.le_eq_subset], induction l with y l hl generalizing l', { simp }, { cases l' with z l', { simp }, { intro x, simp only [set.union_subset_iff, mem_cons_iff, zip_with_cons_cons, foldr, prod_cons, mul_apply], intro hx, by_cases h : x ∈ {x | (zip_with swap l l').prod x ≠ x}, { specialize hl l' h, refine set.mem_union.elim hl (λ hm, _) (λ hm, _); { simp only [finset.coe_insert, set.mem_insert_iff, finset.mem_coe, to_finset_cons, mem_to_finset] at hm ⊢, simp [hm] } }, { simp only [not_not, set.mem_set_of_eq] at h, simp only [h, set.mem_set_of_eq] at hx, rw swap_apply_ne_self_iff at hx, rcases hx with ⟨hyz, rfl|rfl⟩; simp } } } end lemma zip_with_swap_prod_support [fintype α] (l l' : list α) : (zip_with swap l l').prod.support ≤ l.to_finset ⊔ l'.to_finset := begin intros x hx, have hx' : x ∈ {x | (zip_with swap l l').prod x ≠ x} := by simpa using hx, simpa using zip_with_swap_prod_support' _ _ hx' end lemma support_form_perm_le' : {x | form_perm l x ≠ x} ≤ l.to_finset := begin refine (zip_with_swap_prod_support' l l.tail).trans _, simpa [finset.subset_iff] using tail_subset l end lemma support_form_perm_le [fintype α] : support (form_perm l) ≤ l.to_finset := begin intros x hx, have hx' : x ∈ {x | form_perm l x ≠ x} := by simpa using hx, simpa using support_form_perm_le' _ hx' end lemma form_perm_apply_lt (xs : list α) (h : nodup xs) (n : ℕ) (hn : n + 1 < xs.length) : form_perm xs (xs.nth_le n ((nat.lt_succ_self n).trans hn)) = xs.nth_le (n + 1) hn := begin induction n with n IH generalizing xs, { simpa using form_perm_apply_nth_le_zero _ h _ }, { rcases xs with (_|⟨x, _|⟨y, l⟩⟩), { simp }, { simp }, { specialize IH (y :: l) h.of_cons _, { simpa [nat.succ_lt_succ_iff] using hn }, simp only [swap_apply_eq_iff, coe_mul, form_perm_cons_cons, nth_le], generalize_proofs at IH, rw [IH, swap_apply_of_ne_of_ne, nth_le]; { rintro rfl, simpa [nth_le_mem _ _ _] using h } } } end lemma form_perm_apply_nth_le (xs : list α) (h : nodup xs) (n : ℕ) (hn : n < xs.length) : form_perm xs (xs.nth_le n hn) = xs.nth_le ((n + 1) % xs.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases xs with x xs, { simp }, { have : n ≤ xs.length, { refine nat.le_of_lt_succ _, simpa using hn }, rcases this.eq_or_lt with rfl|hn', { simp }, { simp [form_perm_apply_lt, h, nat.mod_eq_of_lt, nat.succ_lt_succ hn'] } } end lemma support_form_perm_of_nodup' (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : {x | form_perm l x ≠ x} = l.to_finset := begin apply le_antisymm, { exact support_form_perm_le' l }, { intros x hx, simp only [finset.mem_coe, mem_to_finset] at hx, obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, rw [set.mem_set_of_eq, form_perm_apply_nth_le _ h], intro H, rw nodup_iff_nth_le_inj at h, specialize h _ _ _ _ H, cases (nat.succ_le_of_lt hn).eq_or_lt with hn' hn', { simp only [←hn', nat.mod_self] at h, refine not_exists.mpr h' _, simpa [←h, eq_comm, length_eq_one] using hn' }, { simpa [nat.mod_eq_of_lt hn'] using h } } end lemma support_form_perm_of_nodup [fintype α] (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : support (form_perm l) = l.to_finset := begin rw ←finset.coe_inj, convert support_form_perm_of_nodup' _ h h', simp [set.ext_iff] end lemma form_perm_rotate_one (l : list α) (h : nodup l) : form_perm (l.rotate 1) = form_perm l := begin have h' : nodup (l.rotate 1), { simpa using h }, ext x, by_cases hx : x ∈ l.rotate 1, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ h', nth_le_rotate l, nth_le_rotate l, form_perm_apply_nth_le _ h], simp }, { rw [form_perm_apply_of_not_mem _ _ hx, form_perm_apply_of_not_mem], simpa using hx } end lemma form_perm_rotate (l : list α) (h : nodup l) (n : ℕ) : form_perm (l.rotate n) = form_perm l := begin induction n with n hn, { simp }, { rw [nat.succ_eq_add_one, ←rotate_rotate, form_perm_rotate_one, hn], rwa is_rotated.nodup_iff, exact is_rotated.forall l n } end lemma form_perm_eq_of_is_rotated {l l' : list α} (hd : nodup l) (h : l ~r l') : form_perm l = form_perm l' := begin obtain ⟨n, rfl⟩ := h, exact (form_perm_rotate l hd n).symm end lemma form_perm_reverse (l : list α) (h : nodup l) : form_perm l.reverse = (form_perm l)⁻¹ := begin -- Let's show `form_perm l` is an inverse to `form_perm l.reverse`. rw [eq_comm, inv_eq_iff_mul_eq_one], ext x, -- We only have to check for `x ∈ l` that `form_perm l (form_perm l.reverse x)` rw [mul_apply, one_apply], by_cases hx : x ∈ l, swap, { rw [form_perm_apply_of_not_mem x l.reverse, form_perm_apply_of_not_mem _ _ hx], simpa using hx }, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem (mem_reverse.mpr hx), rw [form_perm_apply_nth_le l.reverse (nodup_reverse.mpr h), nth_le_reverse', form_perm_apply_nth_le _ h, nth_le_reverse'], { congr, rw [length_reverse, ←nat.succ_le_iff, nat.succ_eq_add_one] at hk, cases hk.eq_or_lt with hk' hk', { simp [←hk'] }, { rw [length_reverse, nat.mod_eq_of_lt hk', tsub_add_eq_add_tsub (nat.le_pred_of_lt hk'), nat.mod_eq_of_lt], { simp }, { rw tsub_add_cancel_of_le, refine tsub_lt_self _ (nat.zero_lt_succ _), all_goals { simpa using (nat.zero_le _).trans_lt hk' } } } }, all_goals { rw [← tsub_add_eq_tsub_tsub, ←length_reverse], refine tsub_lt_self _ (zero_lt_one.trans_le (le_add_right le_rfl)), exact k.zero_le.trans_lt hk } }, end lemma form_perm_pow_apply_nth_le (l : list α) (h : nodup l) (n k : ℕ) (hk : k < l.length) : (form_perm l ^ n) (l.nth_le k hk) = l.nth_le ((k + n) % l.length) (nat.mod_lt _ (k.zero_le.trans_lt hk)) := begin induction n with n hn, { simp [nat.mod_eq_of_lt hk] }, { simp [pow_succ, mul_apply, hn, form_perm_apply_nth_le _ h, nat.succ_eq_add_one, ←nat.add_assoc] } end lemma form_perm_pow_apply_head (x : α) (l : list α) (h : nodup (x :: l)) (n : ℕ) : (form_perm (x :: l) ^ n) x = (x :: l).nth_le (n % (x :: l).length) (nat.mod_lt _ (nat.zero_lt_succ _)) := by { convert form_perm_pow_apply_nth_le _ h n 0 _; simp } lemma form_perm_ext_iff {x y x' y' : α} {l l' : list α} (hd : nodup (x :: y :: l)) (hd' : nodup (x' :: y' :: l')) : form_perm (x :: y :: l) = form_perm (x' :: y' :: l') ↔ (x :: y :: l) ~r (x' :: y' :: l') := begin refine ⟨λ h, _, λ hr, form_perm_eq_of_is_rotated hd hr⟩, rw equiv.perm.ext_iff at h, have hx : x' ∈ (x :: y :: l), { have : x' ∈ {z | form_perm (x :: y :: l) z ≠ z}, { rw [set.mem_set_of_eq, h x', form_perm_apply_head _ _ _ hd'], simp only [mem_cons_iff, nodup_cons] at hd', push_neg at hd', exact hd'.left.left.symm }, simpa using support_form_perm_le' _ this }, obtain ⟨n, hn, hx'⟩ := nth_le_of_mem hx, have hl : (x :: y :: l).length = (x' :: y' :: l').length, { rw [←dedup_eq_self.mpr hd, ←dedup_eq_self.mpr hd', ←card_to_finset, ←card_to_finset], refine congr_arg finset.card _, rw [←finset.coe_inj, ←support_form_perm_of_nodup' _ hd (by simp), ←support_form_perm_of_nodup' _ hd' (by simp)], simp only [h] }, use n, apply list.ext_le, { rw [length_rotate, hl] }, { intros k hk hk', rw nth_le_rotate, induction k with k IH, { simp_rw [nat.zero_add, nat.mod_eq_of_lt hn], simpa }, { have : k.succ = (k + 1) % (x' :: y' :: l').length, { rw [←nat.succ_eq_add_one, nat.mod_eq_of_lt hk'] }, simp_rw this, rw [←form_perm_apply_nth_le _ hd' k (k.lt_succ_self.trans hk'), ←IH (k.lt_succ_self.trans hk), ←h, form_perm_apply_nth_le _ hd], congr' 1, have h1 : 1 = 1 % (x' :: y' :: l').length := by simp, rw [hl, nat.mod_eq_of_lt hk', h1, ←nat.add_mod, nat.succ_add] } } end lemma form_perm_apply_mem_eq_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = x ↔ length l ≤ 1 := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ hl, hl.nth_le_inj_iff], cases hn : l.length, { exact absurd k.zero_le (hk.trans_le hn.le).not_le }, { rw hn at hk, cases (nat.le_of_lt_succ hk).eq_or_lt with hk' hk', { simp [←hk', nat.succ_le_succ_iff, eq_comm] }, { simpa [nat.mod_eq_of_lt (nat.succ_lt_succ hk'), nat.succ_lt_succ_iff] using k.zero_le.trans_lt hk' } } end lemma form_perm_apply_mem_ne_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x ≠ x ↔ 2 ≤ l.length := begin rw [ne.def, form_perm_apply_mem_eq_self_iff _ hl x hx, not_le], exact ⟨nat.succ_le_of_lt, nat.lt_of_succ_le⟩ end lemma mem_of_form_perm_ne_self (l : list α) (x : α) (h : form_perm l x ≠ x) : x ∈ l := begin suffices : x ∈ {y | form_perm l y ≠ y}, { rw ←mem_to_finset, exact support_form_perm_le' _ this }, simpa using h end lemma form_perm_eq_self_of_not_mem (l : list α) (x : α) (h : x ∉ l) : form_perm l x = x := by_contra (λ H, h $ mem_of_form_perm_ne_self _ _ H) lemma form_perm_eq_one_iff (hl : nodup l) : form_perm l = 1 ↔ l.length ≤ 1 := begin cases l with hd tl, { simp }, { rw ←form_perm_apply_mem_eq_self_iff _ hl hd (mem_cons_self _ _), split, { simp {contextual := tt} }, { intro h, simp only [(hd :: tl).form_perm_apply_mem_eq_self_iff hl hd (mem_cons_self hd tl), add_le_iff_nonpos_left, length, nonpos_iff_eq_zero, length_eq_zero] at h, simp [h] } } end lemma form_perm_eq_form_perm_iff {l l' : list α} (hl : l.nodup) (hl' : l'.nodup) : l.form_perm = l'.form_perm ↔ l ~r l' ∨ l.length ≤ 1 ∧ l'.length ≤ 1 := begin rcases l with (_ | ⟨x, _ | ⟨y, l⟩⟩), { suffices : l'.length ≤ 1 ↔ l' = nil ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero] }, refine ⟨λ h, or.inr h, _⟩, rintro (rfl | h), { simp }, { exact h } }, { suffices : l'.length ≤ 1 ↔ [x] ~r l' ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero, le_rfl] }, refine ⟨λ h, or.inr h, _⟩, rintro (h | h), { simp [←h.perm.length_eq] }, { exact h } }, { rcases l' with (_ | ⟨x', _ | ⟨y', l'⟩⟩), { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, { suffices : ¬ (x :: y :: l) ~r [x'], { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, intro h, simpa using h.perm.length_eq }, { simp [-form_perm_cons_cons, form_perm_ext_iff hl hl'] } } end lemma form_perm_zpow_apply_mem_imp_mem (l : list α) (x : α) (hx : x ∈ l) (n : ℤ) : ((form_perm l) ^ n) x ∈ l := begin by_cases h : (l.form_perm ^ n) x = x, { simpa [h] using hx }, { have : x ∈ {x | (l.form_perm ^ n) x ≠ x} := h, rw ←set_support_apply_mem at this, replace this := set_support_zpow_subset _ _ this, simpa using support_form_perm_le' _ this } end lemma form_perm_pow_length_eq_one_of_nodup (hl : nodup l) : (form_perm l) ^ (length l) = 1 := begin ext x, by_cases hx : x ∈ l, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, simp [form_perm_pow_apply_nth_le _ hl, nat.mod_eq_of_lt hk] }, { have : x ∉ {x | (l.form_perm ^ l.length) x ≠ x}, { intros H, refine hx _, replace H := set_support_zpow_subset l.form_perm l.length H, simpa using support_form_perm_le' _ H }, simpa } end end form_perm end list
07ede02470f070cae586dd21d2e12eed53519374
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_addition/04.lean
ae45f0f2e66267759a82eecde603e41eeca3809a
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
135
lean
theorem succ_eq_succ_iff (a b : mynat) : succ a = succ b ↔ a = b := begin split, exact succ_inj, exact succ_eq_succ_of_eq, end
62cad974bf13f8ce0a4305bbc73ee6705c013b3f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/quotient_nilpotent.lean
221c44c4f72fdbc16d0a2493213cd95c59d9b7df
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,091
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 ring_theory.nilpotent import ring_theory.ideal.quotient_operations /-! # Nilpotent elements in quotient rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ lemma ideal.is_radical_iff_quotient_reduced {R : Type*} [comm_ring R] (I : ideal R) : I.is_radical ↔ is_reduced (R ⧸ I) := by { conv_lhs { rw ← @ideal.mk_ker R _ I }, exact ring_hom.ker_is_radical_iff_reduced_of_surjective (@ideal.quotient.mk_surjective R _ I) } variables {R S : Type*} [comm_semiring R] [comm_ring S] [algebra R S] (I : ideal S) /-- Let `P` be a property on ideals. If `P` holds for square-zero ideals, and if `P I → P (J ⧸ I) → P J`, then `P` holds for all nilpotent ideals. -/ lemma ideal.is_nilpotent.induction_on (hI : is_nilpotent I) {P : ∀ ⦃S : Type*⦄ [comm_ring S], by exactI ∀ I : ideal S, Prop} (h₁ : ∀ ⦃S : Type*⦄ [comm_ring S], by exactI ∀ I : ideal S, I ^ 2 = ⊥ → P I) (h₂ : ∀ ⦃S : Type*⦄ [comm_ring S], by exactI ∀ I J : ideal S, I ≤ J → P I → P (J.map (ideal.quotient.mk I)) → P J) : P I := begin obtain ⟨n, hI : I ^ n = ⊥⟩ := hI, unfreezingI { revert S }, apply nat.strong_induction_on n, clear n, introsI n H S _ I hI, by_cases hI' : I = ⊥, { subst hI', apply h₁, rw [← ideal.zero_eq_bot, zero_pow], exact zero_lt_two }, cases n, { rw [pow_zero, ideal.one_eq_top] at hI, haveI := subsingleton_of_bot_eq_top hI.symm, exact (hI' (subsingleton.elim _ _)).elim }, cases n, { rw [pow_one] at hI, exact (hI' hI).elim }, apply h₂ (I ^ 2) _ (ideal.pow_le_self two_ne_zero), { apply H n.succ _ (I ^ 2), { rw [← pow_mul, eq_bot_iff, ← hI, nat.succ_eq_add_one, nat.succ_eq_add_one], exact ideal.pow_le_pow (by linarith) }, { exact le_refl n.succ.succ } }, { apply h₁, rw [← ideal.map_pow, ideal.map_quotient_self] }, end lemma is_nilpotent.is_unit_quotient_mk_iff {R : Type*} [comm_ring R] {I : ideal R} (hI : is_nilpotent I) {x : R} : is_unit (ideal.quotient.mk I x) ↔ is_unit x := begin refine ⟨_, λ h, h.map I^.quotient.mk⟩, revert x, apply ideal.is_nilpotent.induction_on I hI; clear hI I, swap, { introv e h₁ h₂ h₃, apply h₁, apply h₂, exactI h₃.map ((double_quot.quot_quot_equiv_quot_sup I J).trans (ideal.quot_equiv_of_eq (sup_eq_right.mpr e))).symm.to_ring_hom }, { introv e H, resetI, obtain ⟨y, hy⟩ := ideal.quotient.mk_surjective (↑(H.unit⁻¹) : S ⧸ I), have : ideal.quotient.mk I (x * y) = ideal.quotient.mk I 1, { rw [map_one, _root_.map_mul, hy, is_unit.mul_coe_inv] }, rw ideal.quotient.eq at this, have : (x * y - 1) ^ 2 = 0, { rw [← ideal.mem_bot, ← e], exact ideal.pow_mem_pow this _ }, have : x * (y * (2 - x * y)) = 1, { rw [eq_comm, ← sub_eq_zero, ← this], ring }, exact is_unit_of_mul_eq_one _ _ this } end
64a4f20b8a048f60330e505101eb56d0a230d308
54deab7025df5d2df4573383df7e1e5497b7a2c2
/algebra/ring.lean
44503d041375743a12b2a38df9c1d1b6b3897057
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,930
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ open eq universe variable uu variable {A : Type uu} /- ring -/ section variables [ring A] (a b c d e : A) theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg A, @right_distrib A] end theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg A, @right_distrib A] end ... = d : begin rewrite h, simp [@add_sub_cancel A] end theorem mul_neg_one_eq_neg : a * (-1) = -a := have a + a * -1 = 0, from calc a + a * -1 = a * 1 + a * -1 : by simp ... = a * (1 + -1) : eq.symm (left_distrib a 1 (-1)) ... = 0 : by simp, symm (neg_eq_of_add_eq_zero this) theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, intro ha, apply h, simp [ha], intro hb, apply h, simp [hb] end end /- integral domains -/ section variables [s : integral_domain A] (a b c d e : A) include s theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : A} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : A} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this -- TODO: do we want the iff versions? -- theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) := -- sorry /- dvd.elim Hdvd (assume d, assume : a * c = a * b * d, have b * d = c, from eq_of_mul_eq_mul_left Ha begin rewrite ←mul.assoc, symmetry, exact this end, dvd.intro this) -/ -- theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) := -- sorry /- dvd.elim Hdvd (assume d, assume : c * a = b * a * d, have b * d * a = c * a, from by rewrite [mul.right_comm, ←this], have b * d = c, from eq_of_mul_eq_mul_right Ha this, dvd.intro this) -/ end /- namespace norm_num local attribute bit0 bit1 add1 [reducible] local attribute right_distrib left_distrib [simp] theorem mul_zero [mul_zero_class A] (a : A) : a * zero = zero := sorry -- by simp theorem zero_mul [mul_zero_class A] (a : A) : zero * a = zero := sorry -- by simp theorem mul_one [monoid A] (a : A) : a * one = a := sorry -- by simp theorem mul_bit0 [distrib A] (a b : A) : a * (bit0 b) = bit0 (a * b) := sorry -- by simp theorem mul_bit0_helper [distrib A] (a b t : A) (h : a * b = t) : a * (bit0 b) = bit0 t := sorry -- by rewrite -H; simp theorem mul_bit1 [semiring A] (a b : A) : a * (bit1 b) = bit0 (a * b) + a := sorry -- by simp theorem mul_bit1_helper [semiring A] (a b s t : A) (Hs : a * b = s) (Ht : bit0 s + a = t) : a * (bit1 b) = t := sorry -- by simp theorem subst_into_prod [has_mul A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := sorry -- by simp theorem mk_cong (op : A → A) (a b : A) (h : a = b) : op a = op b := sorry -- by simp theorem neg_add_neg_eq_of_add_add_eq_zero [add_comm_group A] (a b c : A) (h : c + a + b = 0) : -a + -b = c := sorry /- begin apply add_neg_eq_of_eq_add, apply neg_eq_of_add_eq_zero, simp end -/ theorem neg_add_neg_helper [add_comm_group A] (a b c : A) (h : a + b = c) : -a + -b = -c := sorry -- begin apply iff.mp !neg_eq_neg_iff_eq, simp end theorem neg_add_pos_eq_of_eq_add [add_comm_group A] (a b c : A) (h : b = c + a) : -a + b = c := sorry -- begin apply neg_add_eq_of_eq_add, simp end theorem neg_add_pos_helper1 [add_comm_group A] (a b c : A) (h : b + c = a) : -a + b = -c := sorry -- begin apply neg_add_eq_of_eq_add, apply eq_add_neg_of_add_eq H end theorem neg_add_pos_helper2 [add_comm_group A] (a b c : A) (h : a + c = b) : -a + b = c := sorry -- begin apply neg_add_eq_of_eq_add, rewrite H end theorem pos_add_neg_helper [add_comm_group A] (a b c : A) (h : b + a = c) : a + b = c := sorry -- by simp theorem sub_eq_add_neg_helper [add_comm_group A] (t₁ t₂ e w₁ w₂: A) (H₁ : t₁ = w₁) (H₂ : t₂ = w₂) (h : w₁ + -w₂ = e) : t₁ - t₂ = e := sorry -- by simp theorem pos_add_pos_helper [add_comm_group A] (a b c h₁ h₂ : A) (H₁ : a = h₁) (H₂ : b = h₂) (h : h₁ + h₂ = c) : a + b = c := sorry -- by simp theorem subst_into_subtr [add_group A] (l r t : A) (prt : l + -r = t) : l - r = t := sorry -- by simp theorem neg_neg_helper [add_group A] (a b : A) (h : a = -b) : -a = b := sorry -- by simp theorem neg_mul_neg_helper [ring A] (a b c : A) (h : a * b = c) : (-a) * (-b) = c := sorry -- by simp theorem neg_mul_pos_helper [ring A] (a b c : A) (h : a * b = c) : (-a) * b = -c := sorry -- by simp theorem pos_mul_neg_helper [ring A] (a b c : A) (h : a * b = c) : a * (-b) = -c := sorry -- by simp end norm_num attribute [simp] zero_mul mul_zero attribute [simp] neg_mul_eq_neg_mul_symm mul_neg_eq_neg_mul_symm attribute [simp] left_distrib right_distrib -/
345443e06e3af2eee344c236ec086eb4fe65f690
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/logic/embedding.lean
213a2dc1af227786aef535a73e6d661b48c57aa5
[ "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
5,849
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Injective functions. -/ import data.equiv.basic universes u v w x namespace function structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩ end function protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β := ⟨f, f.bijective.1⟩ @[simp] theorem equiv.to_embedding_coe_fn {α : Sort u} {β : Sort v} (f : α ≃ β) : (f.to_embedding : α → β) = f := rfl namespace function namespace embedding @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl theorem inj' {α β} : ∀ (f : α ↪ β), injective f | ⟨f, hf⟩ := hf @[refl] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ @[trans] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨_, injective_comp g.inj' f.inj'⟩ @[simp] theorem refl_apply {α} (x : α) : embedding.refl α x = x := rfl @[simp] theorem trans_apply {α β γ} (f : α ↪ β) (g : β ↪ γ) (a : α) : (f.trans g) a = g (f a) := rfl protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) protected noncomputable def of_surjective {α β} {f : β → α} (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective ⟨f.inj, hf⟩ protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β := ⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩ noncomputable def set_value {α β} (f : α ↪ β) (a : α) (b : β) : α ↪ β := by haveI := classical.dec; exact if h : ∃ a', f a' = b then (equiv.swap a (classical.some h)).to_embedding.trans f else ⟨λ a', if a' = a then b else f a', λ a₁ a₂ e, begin simp at e, split_ifs at e with h₁ h₂, { cc }, { cases h ⟨_, e.symm⟩ }, { cases h ⟨_, e⟩ }, { exact f.2 e } end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) : set_value f a b a = b := begin rw [set_value], cases classical.dec (∃ a', f a' = b); dsimp [dite], {simp}, simp [equiv.swap_apply_left], apply classical.some_spec h end /-- Embedding into `option` -/ protected def some {α} : α ↪ option α := ⟨some, option.injective_some α⟩ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨subtype.val, λ _ _, subtype.eq'⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.inj (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl def prod_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨assume ⟨a, b⟩, (e₁ a, e₂ b), assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h, have a₁ = a₂ ∧ b₁ = b₂, from (prod.mk.inj h).imp (assume h, e₁.inj h) (assume h, e₂.inj h), this.left ▸ this.right ▸ rfl⟩ section sum open sum def sum_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨assume s, match s with inl a := inl (e₁ a) | inr b := inr (e₂ b) end, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.inj $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.inj $ inr.inj h end⟩ @[simp] theorem sum_congr_apply_inl {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) (a) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := rfl @[simp] theorem sum_congr_apply_inr {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) (b) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := rfl end sum section sigma open sigma def sigma_congr_right {α : Type*} {β γ : α → Type*} (e : ∀ a, β a ↪ γ a) : sigma β ↪ sigma γ := ⟨λ ⟨a, b⟩, ⟨a, e a b⟩, λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h, begin injection h with h₁ h₂, subst a₂, congr, exact (e a₁).2 (eq_of_heq h₂) end⟩ end sigma def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).inj (congr_fun h a)⟩ def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := by haveI := classical.prop_decidable; exact let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in ⟨f', assume f₁ f₂ h, funext $ assume c, have ∃c', e c' = e c, from ⟨c, rfl⟩, have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _, have eq_b : classical.some this = c, from e.inj $ classical.some_spec this, by simp [f', this, if_pos, eq_b] at eq'; assumption⟩ end embedding end function namespace set /-- The injection map is an embedding between subsets. -/ def embedding_of_subset {α} {s t : set α} (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by congr; injection h⟩ end set
cc3f1be871189da4d177d50432f2cc96b6f88db2
af58757c0ea0692dc50b847d50227363bf9b45bc
/src/examples/nat_fol.lean
7a22b9dde196879fb293405173ea2d4b995379c6
[]
no_license
alyata/fol_lean
b5ca6a8e0adbbe4362bb31ea2ad21d4b40f8fd0a
5f2846e3e88d26712556697dd87b323fe7e6289f
refs/heads/master
1,682,445,984,511
1,622,871,465,000
1,622,871,465,000
372,267,980
1
0
null
null
null
null
UTF-8
Lean
false
false
2,625
lean
import fol set_option pp.beta true namespace fol_nat open fol -- example 1a: A language of natural numbers with the constant symbols `zero` and `one` -- and the function symbols `succ` and `add` inductive funcs : ℕ → Type | zero : funcs 0 | one : funcs 0 | succ : funcs 1 | add : funcs 2 inductive preds : ℕ → Type | equals : preds 2 def L : language := ⟨funcs, preds⟩ -- End Example -- Example 1b: shorthand for each function/constant symbol in L of example 1a def zero : term L := term.func funcs.zero fin.empty def one : term L := term.func funcs.one fin.empty def succ (arg : term L) : term L := term.func funcs.succ (arg :: fin.empty) def add (arg1 arg2 : term L) : term L := term.func funcs.add (arg1 :: arg2 :: fin.empty) def equ (arg1 arg2 : term L) : atom L := atom.atom preds.equals (arg1 :: arg2 :: fin.empty) -- End Example -- Example 2a: model for the natural number language of example 1a def interpret_func (n : ℕ) (c : funcs n) : (fin.vec n ℕ → ℕ) := match n, c with | 0, funcs.zero := (λ_, 0) | 0, funcs.one := (λ_, 1) | 1, funcs.succ := (λargs, args 0 + 1) | 2, funcs.add := (λargs, args 0 + args 1) end def interpret_pred (n : ℕ) (c : preds n) : (fin.vec n ℕ → Prop) := match n, c with | 2, preds.equals := (λargs, args 0 = args 1) end def M : model L := {domain := ℕ, funcs := interpret_func, preds := interpret_pred} -- End Example -- Example 2b: interpreting a ground term in the natural language using the natural model def interpret_term (t : term L) : ℕ := term.valuation M (λi, nat.zero) t #reduce interpret_term $ succ (add one one) example : interpret_term (succ (add one one)) = 3 := rfl -- End Example -- Example 2c: interpreting a ground predicate and proving the predicate def interpret_atom (p : atom L) : Prop := atom.valuation M (λi, nat.zero) p #reduce interpret_atom $ equ one (succ zero) example : interpret_atom (equ one (succ zero)) ↔ (1 = 1) := iff.rfl example : interpret_atom (equ one (succ zero)) := rfl -- End Example -- Example 2d: interpreting some sentences and proving the sentences def interpret_formula (f : formula L) : Prop := formula.valuation M (λi, nat.zero) f def reflexivity : formula L := ∀_(A_ (equ (term.var 0) (term.var 0))) #reduce interpret_formula reflexivity example : interpret_formula reflexivity := by {intro, exact rfl} def symmetry : formula L := ∀_∀_((A_ (equ (term.var 0) (term.var 1))) _→_(A_ (equ (term.var 1) (term.var 0)))) #reduce interpret_formula symmetry example : interpret_formula symmetry := begin intros x y h, exact h.symm end -- End Example end fol_nat
540c6014c0aee164560cdefd34309c48b1bf9b68
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/delta.lean
7edb5dd4a8383137f45838c7aa863e5a9ad0da96
[ "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
543
lean
def f (x : Nat) : Nat := x + 1 example (x y : Nat) (h : f x = 0) : False := by delta f at h trace_state contradiction example (x y : Nat) (h : f x = 0) : False := by delta f -- Error example (x y : Nat) (h1 : f x = 0) (h2 : 0 = 0) : False := by delta f at h2 -- Error example (x y : Nat) (h1 : f x = 0) (h2 : 0 = 0) : False := by delta f at h1 h2 -- Error example (x y : Nat) (h1 : f x = 0) (h2 : 0 = 0) : False := by delta f at * trace_state contradiction example (x y : Nat) (h2 : 0 = 0) : False := by delta f at *
4f5193c73a683347f309de0148d558668e797090
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/type_equations.lean
df88a94762631fce143625ef777c0f579b7a9f4c
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
856
lean
open nat inductive Expr | zero : Expr | one : Expr | add : Expr → Expr → Expr namespace Expr inductive direct_subterm : Expr → Expr → Prop | add_1 : ∀ e₁ e₂ : Expr, direct_subterm e₁ (add e₁ e₂) | add_2 : ∀ e₁ e₂ : Expr, direct_subterm e₂ (add e₁ e₂) theorem direct_subterm_wf : well_founded direct_subterm := sorry /- begin constructor, intro e, induction e, repeat (constructor; intro y hlt; cases hlt; repeat assumption) end -/ definition subterm := tc direct_subterm theorem subterm_wf : well_founded subterm := tc.wf direct_subterm_wf local infix `+` := Expr.add set_option pp.notation false definition ev : Expr → nat | zero := 0 | one := 1 | ((a : Expr) + b) := has_add.add (ev a) (ev b) definition foo : Expr := add zero (add one one) example : ev foo = 2 := rfl end Expr
2db4d64101cdac051d5889e411c0af6743f72539
6950a6e5cebf75da9b91f42789baf52514655111
/tptp/translation_tptp.lean
abf7a14443f39957fa44748f39745ff3975b3a83
[]
no_license
phlippe/Lean_hammer
a6d0a1af09fbce0c58b801032099b9b91d49ecf0
2116279b9c6b334f5b661e4abf4561368cca2391
refs/heads/master
1,587,486,769,513
1,561,466,931,000
1,561,466,931,000
169,705,506
0
1
null
1,550,228,564,000
1,549,614,939,000
Lean
UTF-8
Lean
false
false
13,329
lean
import .tptp meta instance : monad hammer_tactic := state_t.monad meta instance (α : Type) : has_coe (tactic α) (hammer_tactic α) := ⟨state_t.lift⟩ -- Extracting state from tactic meta def using_hammer {α} (t : hammer_tactic α) : tactic (α × hammer_state) := do let ss := hammer_state.mk [] [], state_t.run t ss -- (do a ← t, return a) meta def when' (c : Prop) [decidable c] (tac : hammer_tactic unit) : hammer_tactic unit := if c then tac else tactic.skip -- Checks if expression is a proposition meta def lives_in_prop_p (e : expr) : hammer_tactic bool := do tp ← tactic.infer_type e, return (if eq tp (expr.sort level.zero) then tt else ff) -- Checks if expression is a type meta def lives_in_type (e : expr) : hammer_tactic bool := do tp ← tactic.infer_type e, return (if eq tp (expr.sort (level.succ (level.succ level.zero))) then tt else ff) -- Adding new axiom to current state meta def add_axiom (n : name) (axioma : folform) : hammer_tactic unit := do state_t.modify (fun state, {state with axiomas := ⟨n, axioma⟩ :: state.axiomas}) -- Adding new constant to current state meta def add_constant (n : name) (e : expr) : hammer_tactic unit := do state_t.modify (fun state, {state with introduced_constants := ⟨n, e⟩ :: state.introduced_constants }) -- might want to do something different meta def mk_fresh_name : tactic name := tactic.mk_fresh_name meta def body_of : expr → hammer_tactic (expr × name) | e@(expr.pi n bi d b) := do id ← mk_fresh_name, let x := expr.local_const id n bi d, return $ prod.mk (expr.instantiate_var b x) id | e@(expr.lam n bi d b) := do id ← mk_fresh_name, let x := expr.local_const id n bi d, return $ prod.mk (expr.instantiate_var b x) id | e := return (e, name.anonymous) -- FC(Γ;Πx:t.s): List of free variables in expression excluding x in s meta def hammer_fc (e: expr) : list $ name × name × expr := expr.fold e [] (λ (e : expr) n l, match e with | e@(expr.local_const n n1 _ t) := let e := (n, n1, t) in if e ∉ l then e::l else l | _ := l end) -- Set of free variables that are not Γ proofs meta def hammer_ff (l : list $ name × name × expr) : hammer_tactic $ list $ name × name := do exprs ← list.mfilter (λ x, let (⟨_, _, t⟩ : name × name × expr) := x in do lip ← lives_in_prop_p t, return ¬lip) l, return $ list.foldl (λ a (x : name × name × expr), let (⟨n, n1, t⟩ : name × name × expr) := x in ⟨n, n1⟩ :: a) [] exprs -- Helper functions for dealing with variables meta def wrap_quantifier (binder : name → name → folform → folform) (ns : list $ name × name) (f : folform) : folform := list.foldr (λ (np : name × name) f, binder np.1 np.2 f) (folform.abstract_locals f (list.map (λ (np : name × name), np.1) ns)) ns meta def collect_lambdas_aux : (expr × (list $ name × name × expr)) → hammer_tactic (expr × (list $ name × name × expr)) | (e@(expr.lam n _ t _), l) := do (b, xn) ← body_of e, collect_lambdas_aux (b, (xn, n, t) :: l) | a := return a -- When an inductive declaration is translated, Lean adds the suffix "._main" to the name. However, in other expressions, the function is used without the "._main" suffix. -- To use the same name for the same functions at different places, we remove this suffix here. meta def remove_suffix_of_string : list char → list char | ['.','_','m','a','i','n'] := [] -- | ('.' :: '_' :: b) := [] -- What about other suffixes than main? | (a :: b) := ([a] ++ remove_suffix_of_string b) | [] := [] meta def collect_lambdas (e : expr) := collect_lambdas_aux (e, []) -- == Translating terms == -- Function F encodes propositions as FOL formulas -- Function G encodes types as guards -- Function C encodes CIC0 terms as FOL terms meta mutual def hammer_c, hammer_g, hammer_f -- Define function C (encodes CIC_0 terms as FOL terms) with hammer_c : expr → hammer_tactic folterm | e@(expr.const n _) := do -- TODO deviation from specification, map constants : sth : Prop to prf -- is this necessary? -- tactic.trace e, t ← tactic.infer_type e, -- consult the environment (get type of expression) lip ← lives_in_prop_p t, -- check whether t is prop or not if lip then return $ folterm.prf -- What about the type/formula it actually proofs? else return $ folterm.const $ (remove_suffix_of_string n.to_string.to_list).as_string | (expr.local_const n pp _ t) := -- Same for local constants do lip ← lives_in_prop_p t, if lip then return $ folterm.prf else return $ folterm.lconst n pp | (expr.app t s) := -- Application (in paper C_Γ(ts)=...) do tp ← hammer_c t, -- Get C_Γ(t) sp ← hammer_c s, -- Get C_Γ(s) match tp with | folterm.prf := return folterm.prf -- If C_Γ(t) is type proof, then just return type proof | _ := -- Anything else: check what type C_Γ(s) has match sp with | folterm.prf := return tp -- If it is a proof, return C_Γ(t) | _ := return $ folterm.app tp sp -- else: Return C_Γ(t) applied on C_Γ(s) end end | e@(expr.pi n _ t _) := -- Dependent types (in paper C_Γ(Πx:t.s) ) do lip ← lives_in_prop_p e, Fn ← mk_fresh_name, let F := folterm.const Fn, -- Fresh constant F let An := n ++ Fn, -- Axiom name ys ← hammer_ff $ hammer_fc e, -- y = FF_Γ(FC(Γ;Πx:t.s)) let ce0 := list.foldl (λ t (np : name × name), folterm.app t (folterm.lconst np.1 np.2)) F ys, -- Fy (for all elements in ys, apply F on them by creating local constant of the name) if lip then -- If s is of type Prop: new axiom ∀y.P(Fy) ↔ F_Γ(Πx:t.s) (do let ce1 := folform.P ce0, ce2 ← hammer_f e, -- F_Γ(Πx:t.s) add_axiom An $ wrap_quantifier folform.all ys (folform.iff ce1 ce2)) -- Add new axiom to tactic else -- Otherwise: new axiom ∀yz.T(z,Fy) ↔ G_Γ(z,Πx:t.s) (do zn ← mk_fresh_name, -- Get new, fresh constant name let zlc := folterm.lconst zn zn, -- Create local constant from this name let ys := (⟨zn, zn⟩ :: ys : list $ name × name), -- Add this constant to the already existing set of free variables of our formula let ce1 := folform.T zlc ce0, -- type checker T(z,Fy) ce2 ← hammer_g zlc e, -- type guard G_Γ(z,Πx:t.s) add_axiom An $ wrap_quantifier folform.all ys (folform.iff ce1 ce2)), -- Add new axiom to tactic return ce0 -- Return Fy (what for is this necessary?) | e@(expr.lam n _ _ _) := -- Lambda expression C_Γ(λx:τ.t)=Fy_0 do (t, xτs) ← collect_lambdas e, -- Get all lambda expressions in e -- tactic.trace e, α ← tactic.infer_type t, -- Infer the type of t given all lambda expression (Γ,x:τ|-t:α) let yρs := hammer_fc e, -- y: ρ = FC(Γ;λx:τ.t) - Get list of free constants in e Fn ← mk_fresh_name, -- Fresh constant name let An := n ++ Fn, -- Add new constant name to list of current constants y₀s ← hammer_ff yρs, x₀s ← hammer_ff xτs, let Ft := list.foldr (λ (nt : name × name × expr) a, expr.pi nt.2.1 binder_info.default nt.2.2 $ expr.abstract_local a nt.1) α $ yρs ++ xτs, -- instead of extending the environment, we use a local constant and keep track of its name add_constant Fn Ft, let F := @expr.local_const tt Fn Fn binder_info.default Ft, let (ce1a : expr) := list.foldl (λ (a : expr) (nt : name × name × expr), (a (expr.local_const nt.1 nt.2.1 binder_info.default nt.2.2))) F $ yρs ++ xτs, my_eq ← tactic.mk_const `eq, my_iff ← tactic.mk_const `iff, lip ← lives_in_prop_p ce1a, let ce1b' := if lip then (my_iff ce1a t) else (my_eq α ce1a t), -- ce1b ← tactic.to_expr ``(eq %%ce1a %%t), -- tactic.to_expr is going to blow up if operands are not of the same type. Exciting. ce1 ← hammer_f ce1b', add_axiom An $ wrap_quantifier folform.all (y₀s ++ x₀s) ce1, return $ list.foldl (λ a (nt : name × name), folterm.app a $ folterm.lconst nt.1 nt.2) (folterm.const Fn) y₀s | e@(expr.elet x τ t s) := do let yαs := hammer_fc (t τ), y₀s ← hammer_ff yαs, Fn ← mk_fresh_name, let An := x ++ Fn, let Ft := list.foldr (λ (nt : name × name × expr) a, expr.pi nt.2.1 binder_info.default nt.2.2 $ expr.abstract_local a nt.1) τ $ yαs, -- deviation from the specification, since I cannot imagine why a definition -- instead of a constant is required since the redexes F... are not going to be -- reduced -- instead of extending the environment, we use a local constant and keep track of its name add_constant Fn Ft, tactic.add_decl $ declaration.cnst Fn [] Ft tt, let F := expr.local_const Fn Fn binder_info.default Ft, let ce1 := list.foldl (λ (e : expr) (nt : name × name × expr), (e (expr.local_const nt.1 nt.2.1 binder_info.default nt.2.2))) F yαs, -- TODO deviation from the specification, we use yαs here instead of y₀s. -- I presume the specification is some sort of "optimization" since since -- Gamma-proof terms are going to be filtered by the definition of hammer_c -- anyway, however infer_type is not going to blow up but it will report -- incorrect types if the arguments to a function are in the wrong positions lip ← lives_in_prop_p Ft, if lip then do ce2 ← hammer_c t, add_axiom An $ wrap_quantifier folform.all y₀s $ folform.eq (list.foldl (λ e (nt : name × name), (folterm.app e (folterm.const nt.1))) (folterm.const Fn) y₀s) ce2 else return (), hammer_c $ expr.instantiate_var s ce1 -- TODO: Check if those need to be implemented as well | e@(expr.var _) := -- do tactic.trace e, undefined | e@(expr.sort _) := -- do tactic.trace e, undefined | e@(expr.mvar _ _ _) := -- do tactic.trace e, undefined | e@(expr.macro _ _) := -- do tactic.trace e, undefined -- Define function G (encodes types as guards) with hammer_g : folterm → expr → hammer_tactic folform | u w@(expr.pi n _ t _) := do lip ← lives_in_prop_p t, if lip then do ge1 ← hammer_f t, (s, _) ← body_of w, ge2 ← hammer_g u s, -- tactic.trace ge1, -- tactic.trace ge2, -- tactic.trace $ folform.imp ge1 ge2, return $ folform.imp ge1 ge2 else do (s, xn) ← body_of w, ge1 ← hammer_g (folterm.lconst xn n) t, ge2 ← hammer_g (folterm.app u (folterm.lconst xn n)) s, -- tactic.trace ge1, -- tactic.trace ge2, return $ wrap_quantifier folform.all [(xn, n)] (folform.imp ge1 ge2) | u w := do ge1 ← hammer_c w, return $ folform.T u ge1 -- Define function F (encodes propositions as FOL formulas) with hammer_f : expr → hammer_tactic folform -- Pi notations are translated as ∀x | e@(expr.pi n _ t _) := do lip ← lives_in_prop_p t, if lip -- If t is prop, we can translate it more efficiently (t → s) then do fe1 ← (hammer_f t), (s, _) ← body_of e, fe2 ← hammer_f s, return $ folform.imp fe1 fe2 else do (s, xn) ← body_of e, fe1 ← hammer_g (folterm.lconst xn n) t, fe2 ← hammer_f s, return $ wrap_quantifier folform.all [(xn, n)] (folform.imp fe1 fe2) -- Translating ∃x relation | e@`(@Exists %%t %%ps) := -- we cannot assume that ps has the shape of a lambda do xn ← mk_fresh_name, let lc := expr.local_const xn xn binder_info.default t, s ← tactic.whnf (ps lc), fe1 ← hammer_g (folterm.lconst xn xn) t, fe2 ← hammer_f s, return $ wrap_quantifier folform.exist [(xn, xn)] (folform.conj fe1 fe2) -- Translating conjunction | e@`(and %%t %%s) := do fe1 ← hammer_f t, fe2 ← hammer_f s, return $ folform.conj fe1 fe2 -- Translating disjunction | `(or %%t %%s) := do fe1 ← hammer_f t, fe2 ← hammer_f s, return $ folform.disj fe1 fe2 -- Translating two-sided implication A⇄B | `(iff %%t %%s) := do fe1 ← hammer_f t, fe2 ← hammer_f s, return $ folform.iff fe1 fe2 -- Translating negation | `(not %%t) := do fe1 ← hammer_f t, return $ folform.neg $ fe1 -- Translating equality | `(%%t = %%s) := do fe1 ← hammer_c t, fe2 ← hammer_c s, return $ folform.eq fe1 fe2 | t := do ge1 ← hammer_c t, return $ folform.P ge1
7e677a8b301fa1e48e411d345c826b7b5c277c7e
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/int/order.lean
49b35c2ca45f3673366fd1a77c49ae162429f2ef
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
9,424
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 order relation on the integers. -/ prelude import init.data.int.basic namespace int private def nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false) protected def le (a b : ℤ) : Prop := nonneg (b - a) instance : has_le int := ⟨int.le⟩ protected def lt (a b : ℤ) : Prop := (a + 1) ≤ b instance : has_lt int := ⟨int.lt⟩ private def decidable_nonneg (a : ℤ) : decidable (nonneg a) := int.cases_on a (take a, decidable.true) (take a, decidable.false) instance decidable_le (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _ instance decidable_lt (a b : ℤ) : decidable (a < b) := decidable_nonneg _ lemma lt_iff_add_one_le (a b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl _ private lemma nonneg.elim {a : ℤ} : nonneg a → ∃ n : ℕ, a = n := int.cases_on a (take n H, exists.intro n rfl) (take n', false.elim) private lemma nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial) lemma le.intro_sub {a b : ℤ} {n : ℕ} (h : b - a = n) : a ≤ b := show nonneg (b - a), by rw h; trivial lemma le.intro {a b : ℤ} {n : ℕ} (h : a + n = b) : a ≤ b := le.intro_sub (by rw -h; simp) lemma le.dest_sub {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, b - a = n := nonneg.elim h lemma le.dest {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, a + n = b := match (le.dest_sub h) with | ⟨n, h₁⟩ := exists.intro n begin rw [-h₁, add_comm], simp end end lemma le.elim {a b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ n : ℕ, a + ↑n = b → P) : P := exists.elim (le.dest h) h' protected lemma le_total (a b : ℤ) : a ≤ b ∨ b ≤ a := or.imp_right (assume H : nonneg (-(b - a)), have -(b - a) = a - b, by simp, show nonneg (a - b), from this ▸ H) (nonneg_or_nonneg_neg (b - a)) lemma coe_nat_le_coe_nat_of_le {m n : ℕ} (h : m ≤ n) : (↑m : ℤ) ≤ ↑n := match nat.le.dest h with | ⟨k, (hk : m + k = n)⟩ := le.intro (begin rw [-hk], reflexivity end) end lemma le_of_coe_nat_le_coe_nat {m n : ℕ} (h : (↑m : ℤ) ≤ ↑n) : m ≤ n := le.elim h (take k, assume hk : ↑m + ↑k = ↑n, have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k).trans hk), nat.le.intro this) lemma coe_nat_le_coe_nat_iff (m n : ℕ) : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le lemma coe_zero_le (n : ℕ) : 0 ≤ (↑n : ℤ) := coe_nat_le_coe_nat_of_le n.zero_le lemma eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ n : ℕ, a = n := by note t := le.dest_sub h; simp at t; exact t lemma lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(nat.succ n) := le.intro (show a + 1 + n = a + nat.succ n, begin simp [int.coe_nat_eq], reflexivity end) lemma lt.intro {a b : ℤ} {n : ℕ} (h : a + nat.succ n = b) : a < b := h ▸ lt_add_succ a n lemma lt.dest {a b : ℤ} (h : a < b) : ∃ n : ℕ, a + ↑(nat.succ n) = b := le.elim h (take n, assume hn : a + 1 + n = b, exists.intro n begin rw [-hn, add_assoc, add_comm (1 : int)], reflexivity end) lemma lt.elim {a b : ℤ} (h : a < b) {P : Prop} (h' : ∀ n : ℕ, a + ↑(nat.succ n) = b → P) : P := exists.elim (lt.dest h) h' lemma coe_nat_lt_coe_nat_iff (n m : ℕ) : (↑n : ℤ) < ↑m ↔ n < m := begin rw [lt_iff_add_one_le, -int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end lemma lt_of_coe_nat_lt_coe_nat {m n : ℕ} (h : (↑m : ℤ) < ↑n) : m < n := (coe_nat_lt_coe_nat_iff _ _).mp h lemma coe_nat_lt_coe_nat_of_lt {m n : ℕ} (h : m < n) : (↑m : ℤ) < ↑n := (coe_nat_lt_coe_nat_iff _ _).mpr h /- show that the integers form an ordered additive group -/ protected lemma le_refl (a : ℤ) : a ≤ a := le.intro (add_zero a) protected lemma le_trans {a b c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := le.elim h₁ (take n, assume hn : a + n = b, le.elim h₂ (take m, assume hm : b + m = c, begin apply le.intro, rw [-hm, -hn, add_assoc], reflexivity end)) protected lemma le_antisymm {a b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b := le.elim h₁ (take n, assume hn : a + n = b, le.elim h₂ (take m, assume hm : b + m = a, have a + ↑(n + m) = a + 0, by rw [int.coe_nat_add, -add_assoc, hn, hm, add_zero a], have (↑(n + m) : ℤ) = 0, from add_left_cancel this, have n + m = 0, from int.coe_nat_inj this, have n = 0, from nat.eq_zero_of_add_eq_zero_right this, show a = b, begin rw [-hn, this, int.coe_nat_zero, add_zero a] end)) protected lemma lt_irrefl (a : ℤ) : ¬ a < a := suppose a < a, lt.elim this (take n, assume hn : a + nat.succ n = a, have a + nat.succ n = a + 0, by rw [hn, add_zero], have nat.succ n = 0, from int.coe_nat_inj (add_left_cancel this), show false, from nat.succ_ne_zero _ this) protected lemma ne_of_lt {a b : ℤ} (h : a < b) : a ≠ b := (suppose a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b)) lemma le_of_lt {a b : ℤ} (h : a < b) : a ≤ b := lt.elim h (take n, assume hn : a + nat.succ n = b, le.intro hn) protected lemma lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (assume h, ⟨le_of_lt h, int.ne_of_lt h⟩) (assume ⟨aleb, aneb⟩, le.elim aleb (take n, assume hn : a + n = b, have n ≠ 0, from (suppose n = 0, aneb begin rw [-hn, this, int.coe_nat_zero, add_zero] end), have n = nat.succ (nat.pred n), from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)), lt.intro (begin rewrite this at hn, exact hn end))) protected lemma le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) := iff.intro (assume h, decidable.by_cases (suppose a = b, or.inr this) (suppose a ≠ b, le.elim h (take n, assume hn : a + n = b, have n ≠ 0, from (suppose n = 0, ‹a ≠ b› begin rw [-hn, this, int.coe_nat_zero, add_zero] end), have n = nat.succ (nat.pred n), from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)), or.inl (lt.intro (begin rewrite this at hn, exact hn end))))) (assume h, or.elim h (assume h', le_of_lt h') (assume h', h' ▸ int.le_refl a)) lemma lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected lemma add_le_add_left {a b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b := le.elim h (take n, assume hn : a + n = b, le.intro (show c + a + n = c + b, begin rw [add_assoc, hn] end)) protected lemma add_lt_add_left {a b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b := iff.mpr (int.lt_iff_le_and_ne _ _) (and.intro (int.add_le_add_left (le_of_lt h) _) (take heq, int.lt_irrefl b begin rw add_left_cancel heq at h, exact h end)) protected lemma mul_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := le.elim ha (take n, assume hn, le.elim hb (take m, assume hm, le.intro (show 0 + ↑n * ↑m = a * b, begin rw [-hn, -hm], repeat {rw zero_add} end))) protected lemma mul_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := lt.elim ha (take n, assume hn, lt.elim hb (take m, assume hm, lt.intro (show 0 + ↑(nat.succ (nat.succ n * m + n)) = a * b, begin rw [-hn, -hm], repeat {rw int.coe_nat_zero}, simp, rw [-int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end))) protected lemma zero_lt_one : (0 : ℤ) < 1 := trivial protected lemma not_le_of_gt {a b : ℤ} (h : a < b) : ¬ b ≤ a := assume hba : b ≤ a, have a = b, from int.le_antisymm (le_of_lt h) hba, show false, from int.lt_irrefl b (begin rw this at h, exact h end) protected lemma lt_of_lt_of_le {a b c : ℤ} (hab : a < b) (hbc : b ≤ c) : a < c := have hac : a ≤ c, from int.le_trans (le_of_lt hab) hbc, iff.mpr (int.lt_iff_le_and_ne _ _) (and.intro hac (assume heq, int.not_le_of_gt begin rw -heq, assumption end hbc)) protected lemma lt_of_le_of_lt {a b c : ℤ} (hab : a ≤ b) (hbc : b < c) : a < c := have hac : a ≤ c, from int.le_trans hab (le_of_lt hbc), iff.mpr (int.lt_iff_le_and_ne _ _) (and.intro hac (assume heq, int.not_le_of_gt begin rw heq, exact hbc end hab)) instance : decidable_linear_ordered_comm_ring int := { int.comm_ring with le := int.le, le_refl := int.le_refl, le_trans := @int.le_trans, le_antisymm := @int.le_antisymm, lt := int.lt, le_of_lt := @int.le_of_lt, lt_of_lt_of_le := @int.lt_of_lt_of_le, lt_of_le_of_lt := @int.lt_of_le_of_lt, lt_irrefl := int.lt_irrefl, add_le_add_left := @int.add_le_add_left, add_lt_add_left := @int.add_lt_add_left, zero_ne_one := zero_ne_one, mul_nonneg := @int.mul_nonneg, mul_pos := @int.mul_pos, le_iff_lt_or_eq := int.le_iff_lt_or_eq, le_total := int.le_total, zero_lt_one := int.zero_lt_one, decidable_eq := int.decidable_eq, decidable_le := int.decidable_le, decidable_lt := int.decidable_lt } instance : decidable_linear_ordered_comm_group int := by apply_instance lemma eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = nat_abs a := let ⟨n, e⟩ := eq_coe_of_zero_le h in by rw e; refl lemma le_nat_abs {a : ℤ} : a ≤ nat_abs a := or.elim (le_total 0 a) (λh, by rw eq_nat_abs_of_zero_le h; refl) (λh, le_trans h (coe_zero_le _)) end int -- TODO(Jeremy): add more facts specific to the integers
4e38646888a191444088f1a7e839df833d1df6db
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/fintype/card.lean
27075fd26ecea94d4ec0c672376267d0df7aa78e
[ "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
17,200
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.fintype.basic import algebra.big_operators.ring /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype @[to_additive] lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [decidable_eq ι] [fintype ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) : (∏ x, f x) = f a := finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim @[to_additive] lemma prod_unique [unique β] (f : β → M) : (∏ x, f x) = f (default β) := by simp only [finset.prod_singleton, univ_unique] /-- If a product of a `finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `finset` of a subsingleton type has a given value, so do the terms in that sum."] lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b := finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h end end fintype open finset section variables {M : Type*} [fintype α] [decidable_eq α] [comm_monoid M] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → M) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl @[to_additive] lemma finset.prod_mul_prod_compl (s : finset α) (f : α → M) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl_compl.prod_mul_prod f @[to_additive] lemma finset.prod_compl_mul_prod (s : finset α) (f : α → M) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := is_compl_compl.symm.prod_mul_prod f end @[to_additive] theorem fin.prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) : ∏ i, f i = ((list.fin_range n).map f).prod := by simp [fin.univ_def, finset.fin_range] @[to_additive] theorem fin.prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) : (list.of_fn f).prod = ∏ i, f i := by rw [list.of_fn_eq_map, fin.prod_univ_def] /-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/ @[simp, to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/ theorem fin.prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) := begin rw [fin.univ_succ_above, finset.prod_insert, finset.prod_image], { intros x _ y _ hxy, exact fin.succ_above_right_inj.mp hxy }, { simp [fin.succ_above_ne] } end /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/ theorem fin.sum_univ_succ_above [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∑ i, f i = f x + ∑ i : fin n, f (x.succ_above i) := by apply @fin.prod_univ_succ_above (multiplicative β) attribute [to_additive] fin.prod_univ_succ_above /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f 0` plus the remaining product -/ theorem fin.prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := fin.prod_univ_succ_above f 0 /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f 0` plus the remaining product -/ theorem fin.sum_univ_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∑ i, f i = f 0 + ∑ i : fin n, f i.succ := fin.sum_univ_succ_above f 0 attribute [to_additive] fin.prod_univ_succ /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f (fin.last n)` plus the remaining product -/ theorem fin.prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) := by simpa [mul_comm] using fin.prod_univ_succ_above f (fin.last n) /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f (fin.last n)` plus the remaining sum -/ theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∑ i, f i = ∑ i : fin n, f i.cast_succ + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ -- FIXME ouch, this should be in the main file. @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by simp [sum.fintype, fintype.of_equiv_card] @[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = ∏ a in s, card (t a) := multiset.card_pi _ _ @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b @[to_additive] lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β} (hf : function.bijective f) (g : β → γ) : ∏ i, g (f i) = ∏ i, g i := prod_bij (λ i hi, f i) (λ i hi, mem_univ _) (λ i hi, rfl) (λ i j _ _ h, hf.1 h) $ λ i hi, (hf.2 i).imp $ λ j hj, ⟨mem_univ _, hj.symm⟩ @[to_additive] lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := e.bijective.prod_comp f /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i = ∏ i in range n, f i := calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i : ((equiv.fin_equiv_subtype n).trans (equiv.subtype_congr_right (λ _, mem_range.symm))).prod_comp (f ∘ coe) ... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach] @[to_additive] lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) : ∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := begin rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl], rintros ⟨i, hi⟩ _, simp only [fin.coe_eq_val, hi, dif_pos] end @[to_additive] lemma finset.prod_subtype {M : Type*} [comm_monoid M] {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → M) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, begin rw [← prod_attach, attach_eq_univ], substI p, congr end @[to_additive] lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α] (p : α → Prop) [decidable_pred p] (f : α → M) : ∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a := by { rw ← finset.prod_subtype, simp } @[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _ @[to_additive] lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← (equiv.sigma_preimage_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma], refl end lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p] [comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) := begin simp only [prod_dite, attach_eq_univ], congr' 1, { convert (equiv.subtype_congr_right _).prod_comp (λ x : {x // p x}, f x x.2), simp }, { convert (equiv.subtype_congr_right _).prod_comp (λ x : {x // ¬p x}, g x x.2), simp } end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) : (∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) := by { classical, rw [univ_sum_type, prod_sum_elim] } @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := by simp only [← fintype.prod_sum_elim, sum.elim_comp_inl_inr] end namespace list lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ ((j : ℕ) < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), ((j : ℕ) < i.succ) = ((j : ℕ) < i), { assume j, have : (j : ℕ) < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end -- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. -- Use `multiplicative` instead. lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).sum = ∑ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := @prod_take_of_fn (multiplicative α) _ n f i attribute [to_additive] prod_take_of_fn @[to_additive] lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), (j : ℕ) < n := λ j, j.is_lt, simp [this] } end lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.is_lt | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) •ℤ [g].nth_le i i.2, rw [fin.sum_univ_succ], simp, end | (g :: h :: L) := calc g + -h + L.alternating_sum = g + -h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) •ℤ list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
8d1da2fcfbf27e5d8c1aba6d3d6ec871ae8ad4b6
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_propositional/prop_07.lean
9189a9e18571a77de096da4f56bb9587be4b7001
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
155
lean
namespace prop_07 variable P : Prop theorem prop_7 : P → ¬ ¬ P := assume h1: P, assume h2: ¬ P, show false, from h2 h1 -- end namespace end prop_07
17a07d0592f6347ff2a0799c5f0c9c7d5bcf33b3
aa101d73b1a3173c7ec56de02b96baa8ca64c42e
/src/my_exercises/01_equality_rewriting.lean
e5b81c0821a5798fa1a44dd4da17cc2d37c61f32
[ "Apache-2.0" ]
permissive
gihanmarasingha/tutorials
b554d4d53866c493c4341dc13e914b01444e95a6
56617114ef0f9f7b808476faffd11e22e4380918
refs/heads/master
1,671,141,758,153
1,599,173,318,000
1,599,173,318,000
282,405,870
0
0
Apache-2.0
1,595,666,751,000
1,595,666,750,000
null
UTF-8
Lean
false
false
5,309
lean
import data.real.basic /- One of the earliest kind of proofs one encounters while learning mathematics is proving by a calculation. It may not sound like a proof, but this is actually using lemmas expressing properties of operations on numbers. It also uses the fundamental property of equality: if two mathematical objects A and B are equal then, in any statement involving A, one can replace A by B. This operation is called rewriting, and the Lean "tactic" for this is `rw`. In the following exercises, we will use the following two lemmas: mul_assoc a b c : a * b * c = a * (b * c) mul_comm a b : a*b = b*a Hence the command rw mul_assoc a b c, will replace a*b*c by a*(b*c) in the current goal. In order to replace backward, we use rw ← mul_assoc a b c, replacing a*(b*c) by a*b*c in the current goal. Of course we don't want to constantly invoke those lemmas, and we will eventually introduce more powerful solutions. -/ example (a b c : ℝ) : (a * b) * c = b * (a * c) := begin rw mul_comm a b, rw mul_assoc b a c, end -- 0001 example (a b c : ℝ) : (c * b) * a = b * (a * c) := begin rw mul_comm c b, rw mul_assoc b c a, rw mul_comm c a end -- 0002 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin rw mul_comm, rw mul_assoc, rw mul_comm c a, end /- Now let's return to the preceding example to experiment with what happens if we don't give arguments to mul_assoc or mul_comm. For instance, you can start the next proof with rw ← mul_assoc, Try to figure out what happens. -/ -- 0003 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin rw ←mul_assoc, rw mul_comm a b, rw mul_assoc, end /- We can also perform rewriting in an assumption of the local context, using for instance rw mul_comm a b at hyp, in order to replace a*b by b*a in assumption hyp. The next example will use a third lemma: two_mul a : 2*a = a + a Also we use the `exact` tactic, which allows to provide a direct proof term. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin rw hyp' at hyp, rw mul_comm d a at hyp, rw ← two_mul (a*d) at hyp, rw ← mul_assoc 2 a d at hyp, exact hyp, -- Our assumption hyp is now exactly what we have to prove end /- And the next one can use: sub_self x : x - x = 0 -/ -- 0004 example (a b c d : ℝ) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 := begin rw hyp' at hyp, rw mul_comm at hyp, rw sub_self at hyp, exact hyp, end /- What is written in the two preceding example is very far away from what we would write on paper. Let's now see how to get a more natural layout. Inside each pair of curly braces below, the goal is to prove equality with the preceding line. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin calc c = d*a + b : by { rw hyp } ... = d*a + a*d : by { rw hyp' } ... = a*d + a*d : by { rw mul_comm d a } ... = 2*(a*d) : by { rw two_mul } ... = 2*a*d : by { rw mul_assoc }, end /- Let's note there is no comma at the end of each line of calculation. `calc` is really one command, and the comma comes only after it's fully done. From a practical point of view, when writing such a proof, it is convenient to: * pause the tactic state view update in VScode by clicking the Pause icon button in the top right corner of the Lean Goal buffer * write the full calculation, ending each line with ": by {}" * resume tactic state update by clicking the Play icon button and fill in proofs between curly braces. Let's return to the other example using this method. -/ -- 0005 example (a b c d : ℝ) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 := begin calc c = b*a - d : hyp ... = b*a - a*b : by rw hyp' ... = a*b - a*b : by rw mul_comm ... = 0 : by rw sub_self end /- The preceding proofs have exhausted our supply of "mul_comm" patience. Now it's time to get the computer to work harder. The `ring` tactic will prove any goal that follows by applying only the axioms of commutative (semi-)rings, in particular commutativity and associativity of addition and multiplication, as well as distributivity. We also note that curly braces are not necessary when we write a single tactic proof, so let's get rid of them. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin calc c = d*a + b : by rw hyp ... = d*a + a*d : by rw hyp' ... = 2*a*d : by ring, end /- Of course we can use `ring` outside of `calc`. Let's do the next one in one line. -/ -- 0006 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin ring, end /- This is too much fun. Let's do it again. -/ -- 0007 example (a b : ℝ) : (a + b) + a = 2*a + b := begin ring, end /- Maybe this is cheating. Let's try to do the next computation without ring. We could use: pow_two x : x^2 = x*x mul_sub a b c : a*(b-c) = a*b - a*c add_mul a b c : (a+b)*c = a*c + b*c add_sub a b c : a + (b - c) = (a + b) - c sub_sub a b c : a - b - c = a - (b + c) add_zero a : a + 0 = a -/ -- 0008 example (a b : ℝ) : (a + b)*(a - b) = a^2 - b^2 := begin rw mul_sub, rw add_mul a b b, rw ←sub_sub, rw add_mul, rw mul_comm b a, rw ←add_sub, rw sub_self, rw add_zero, rw pow_two, rw pow_two, end /- Let's stick to ring in the end. -/
1ef64ef11cc07c62fc7c766aac263630a023e815
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/univ.lean
8702fb320c911cedf02b6cf956c0cb6b7b34f69e
[ "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
241
lean
import data.num definition id2 (A : Type) (a : A) := a check id2 Type num check id2 Type' num check id2 Type.{1} num check id2 _ num check id2 Type.{_+1} num check id2 Type.{0+1} num check id2 Type Type.{1} check id2 Type' Type.{1}
83f8183413f77b6e6bf776efe6be8a8ab66d2de7
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/declareConfigElabBug.lean
cd2ec0e5290c717f5b86d70fd09236dd48a3a750
[ "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
168
lean
set_option trace.Elab true theorem ex (h : a = b) : (fun x => x) a = b := by simp (config := { beta := false }) trace_state simp (config := { beta := true }) [h]
221393c81da33e76b6e44aa877fdc920c8342a3c
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/integral/layercake.lean
6cc9602fe672a46add2eb0717d56519070ac3466
[ "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
18,168
lean
/- Copyright (c) 2022 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import measure_theory.integral.interval_integral import analysis.special_functions.integrals /-! # The layer cake formula / Cavalieri's principle / tail probability formula In this file we prove the following layer cake formula. Consider a non-negative measurable function `f` on a sigma-finite measure space. Apply pointwise to it an increasing absolutely continuous function `G : ℝ≥0 → ℝ≥0` vanishing at the origin, with derivative `G' = g` on the positive real line (in other words, `G` a primitive of a non-negative locally integrable function `g` on the positive real line). Then the integral of the result, `∫ G ∘ f`, can be written as the integral over the positive real line of the "tail measures" of `f` (i.e., a function giving the measures of the sets on which `f` exceeds different positive real values) weighted by `g`. In probability theory contexts, the "tail measures" could be referred to as "tail probabilities" of the random variable `f`, or as values of the "complementary cumulative distribution function" of the random variable `f`. The terminology "tail probability formula" is therefore occasionally used for the layer cake formula (or a standard application of it). The essence of the (mathematical) proof is Fubini's theorem. We also give the two most common applications of the layer cake formula * a representation of the integral of a nonnegative function f: ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) ≥ t} dt * a representation of the integral of the p:th power of a nonnegative function f: ∫ f(ω)^p ∂μ(ω) = p * ∫ t^(p-1) * μ {ω | f(ω) ≥ t} dt . Variants of the formulas with measures of sets of the form {ω | f(ω) > t} instead of {ω | f(ω) ≥ t} are also included. ## Main results * `lintegral_comp_eq_lintegral_meas_le_mul` and `lintegral_comp_eq_lintegral_meas_lt_mul`: The general layer cake formulas with Lebesgue integrals, written in terms of measures of sets of the forms {ω | t ≤ f(ω)} and {ω | t < f(ω)}, respectively. * `lintegral_eq_lintegral_meas_le` and `lintegral_eq_lintegral_meas_lt`: The most common special cases of the layer cake formulas, stating that for a nonnegative function f we have ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) ≥ t} dt and ∫ f(ω) ∂μ(ω) = ∫ μ {ω | f(ω) > t} dt, respectively. * `lintegral_rpow_eq_lintegral_meas_le_mul` and `lintegral_rpow_eq_lintegral_meas_lt_mul`: Other common special cases of the layer cake formulas, stating that for a nonnegative function f and p > 0, we have ∫ f(ω)^p ∂μ(ω) = p * ∫ μ {ω | f(ω) ≥ t} * t^(p-1) dt and ∫ f(ω)^p ∂μ(ω) = p * ∫ μ {ω | f(ω) > t} * t^(p-1) dt, respectively. ## Tags layer cake representation, Cavalieri's principle, tail probability formula -/ noncomputable theory open_locale ennreal measure_theory open set measure_theory filter /-! ### Layercake formula -/ section layercake namespace measure_theory variables {α : Type*} [measurable_space α] {f : α → ℝ} {g : ℝ → ℝ} {s : set α} /-- An auxiliary version of the layer cake formula (Cavalieri's principle, tail probability formula), with a measurability assumption that would also essentially follow from the integrability assumptions. See `measure_theory.lintegral_comp_eq_lintegral_meas_le_mul` and `measure_theory.lintegral_comp_eq_lintegral_meas_lt_mul` for the main formulations of the layer cake formula. -/ lemma lintegral_comp_eq_lintegral_meas_le_mul_of_measurable (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) (g_intble : ∀ t > 0, interval_integrable g volume 0 t) (g_mble : measurable g) (g_nn : ∀ t > 0, 0 ≤ g t) : ∫⁻ ω, ennreal.of_real (∫ t in 0 .. (f ω), g t) ∂μ = ∫⁻ t in Ioi 0, (μ {a : α | t ≤ f a}) * ennreal.of_real (g t) := begin have g_intble' : ∀ (t : ℝ), 0 ≤ t → interval_integrable g volume 0 t, { intros t ht, cases eq_or_lt_of_le ht, { simp [← h], }, { exact g_intble t h, }, }, have integrand_eq : ∀ ω, ennreal.of_real (∫ t in 0 .. (f ω), g t) = ∫⁻ t in Ioc 0 (f ω), ennreal.of_real (g t), { intro ω, have g_ae_nn : 0 ≤ᵐ[volume.restrict (Ioc 0 (f ω))] g, { filter_upwards [self_mem_ae_restrict (measurable_set_Ioc : measurable_set (Ioc 0 (f ω)))] with x hx using g_nn x hx.1, }, rw ← of_real_integral_eq_lintegral_of_real (g_intble' (f ω) (f_nn ω)).1 g_ae_nn, congr, exact interval_integral.integral_of_le (f_nn ω), }, simp_rw [integrand_eq, ← lintegral_indicator (λ t, ennreal.of_real (g t)) measurable_set_Ioc, ← lintegral_indicator _ measurable_set_Ioi], rw lintegral_lintegral_swap, { apply congr_arg, funext s, have aux₁ : (λ x, (Ioc 0 (f x)).indicator (λ (t : ℝ), ennreal.of_real (g t)) s) = (λ x, (ennreal.of_real (g s) * (Ioi (0 : ℝ)).indicator (λ _, 1) s) * (Ici s).indicator (λ (t : ℝ), (1 : ℝ≥0∞)) (f x)), { funext a, by_cases s ∈ Ioc (0 : ℝ) (f a), { simp only [h, (show s ∈ Ioi (0 : ℝ), from h.1), (show f a ∈ Ici s, from h.2), indicator_of_mem, mul_one], }, { have h_copy := h, simp only [mem_Ioc, not_and, not_le] at h, by_cases h' : 0 < s, { simp only [h_copy, h h', indicator_of_not_mem, not_false_iff, mem_Ici, not_le, mul_zero], }, { have : s ∉ Ioi (0 : ℝ) := h', simp only [this, h', indicator_of_not_mem, not_false_iff, mul_zero, zero_mul, mem_Ioc, false_and], }, }, }, simp_rw aux₁, rw lintegral_const_mul', swap, { apply ennreal.mul_ne_top ennreal.of_real_ne_top, by_cases s ∈ Ioi (0 : ℝ); { simp [h], }, }, simp_rw [(show (λ a, (Ici s).indicator (λ (t : ℝ), (1 : ℝ≥0∞)) (f a)) = (λ a, {a : α | s ≤ f a}.indicator (λ _, 1) a), by { funext a, by_cases s ≤ f a; simp [h], })], rw lintegral_indicator, swap, { exact f_mble measurable_set_Ici, }, rw [lintegral_one, measure.restrict_apply measurable_set.univ, univ_inter, indicator_mul_left, mul_assoc, (show (Ioi 0).indicator (λ (_x : ℝ), (1 : ℝ≥0∞)) s * μ {a : α | s ≤ f a} = (Ioi 0).indicator (λ (_x : ℝ), 1 * μ {a : α | s ≤ f a}) s, by { by_cases 0 < s; simp [h], })], simp_rw [mul_comm _ (ennreal.of_real _), one_mul], refl, }, have aux₂ : function.uncurry (λ (x : α) (y : ℝ), (Ioc 0 (f x)).indicator (λ (t : ℝ), ennreal.of_real (g t)) y) = {p : α × ℝ | p.2 ∈ Ioc 0 (f p.1)}.indicator (λ p, ennreal.of_real (g p.2)), { funext p, cases p, rw function.uncurry_apply_pair, by_cases p_snd ∈ Ioc 0 (f p_fst), { have h' : (p_fst, p_snd) ∈ {p : α × ℝ | p.snd ∈ Ioc 0 (f p.fst)} := h, rw [set.indicator_of_mem h', set.indicator_of_mem h], }, { have h' : (p_fst, p_snd) ∉ {p : α × ℝ | p.snd ∈ Ioc 0 (f p.fst)} := h, rw [set.indicator_of_not_mem h', set.indicator_of_not_mem h], }, }, rw aux₂, have mble := measurable_set_region_between_oc measurable_zero f_mble measurable_set.univ, simp_rw [mem_univ, pi.zero_apply, true_and] at mble, exact (ennreal.measurable_of_real.comp (g_mble.comp measurable_snd)).ae_measurable.indicator mble, end /-- The layer cake formula / Cavalieri's principle / tail probability formula: Let `f` be a non-negative measurable function on a sigma-finite measure space. Let `G` be an increasing absolutely continuous function on the positive real line, vanishing at the origin, with derivative `G' = g`. Then the integral of the composition `G ∘ f` can be written as the integral over the positive real line of the "tail measures" `μ {ω | f(ω) ≥ t}` of `f` weighted by `g`. Roughly speaking, the statement is: `∫⁻ (G ∘ f) ∂μ = ∫⁻ t in 0 .. ∞, g(t) * μ {ω | f(ω) ≥ t}`. See `lintegral_comp_eq_lintegral_meas_lt_mul` for a version with sets of the form `{ω | f(ω) > t}` instead. -/ theorem lintegral_comp_eq_lintegral_meas_le_mul (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) (g_intble : ∀ t > 0, interval_integrable g volume 0 t) (g_nn : ∀ᵐ t ∂(volume.restrict (Ioi 0)), 0 ≤ g t) : ∫⁻ ω, ennreal.of_real (∫ t in 0 .. f ω, g t) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ennreal.of_real (g t) := begin have ex_G : ∃ (G : ℝ → ℝ), measurable G ∧ 0 ≤ G ∧ g =ᵐ[volume.restrict (Ioi 0)] G, { refine ae_measurable.exists_measurable_nonneg _ g_nn, exact ae_measurable_Ioi_of_forall_Ioc (λ t ht, (g_intble t ht).1.1.ae_measurable), }, rcases ex_G with ⟨G, G_mble, G_nn, g_eq_G⟩, have g_eq_G_on : ∀ t, g =ᵐ[volume.restrict (Ioc 0 t)] G, from λ t, ae_mono (measure.restrict_mono Ioc_subset_Ioi_self le_rfl) g_eq_G, have G_intble : ∀ t > 0, interval_integrable G volume 0 t, { refine λ t t_pos, ⟨(g_intble t t_pos).1.congr_fun_ae (g_eq_G_on t), _⟩, rw Ioc_eq_empty_of_le t_pos.lt.le, exact integrable_on_empty, }, have eq₁ : ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ennreal.of_real (g t) = ∫⁻ t in Ioi 0, μ {a : α | t ≤ f a} * ennreal.of_real (G t), { apply lintegral_congr_ae, filter_upwards [g_eq_G] with a ha, rw [ha], }, have eq₂ : ∀ ω, ∫ t in 0..f ω, g t = ∫ t in 0..f ω, G t, { refine λ ω, interval_integral.integral_congr_ae _, have fω_nn : 0 ≤ f ω := f_nn ω, rw [uIoc_of_le fω_nn, ← ae_restrict_iff' (measurable_set_Ioc : measurable_set (Ioc (0 : ℝ) (f ω)))], exact g_eq_G_on (f ω), }, simp_rw [eq₁, eq₂], exact lintegral_comp_eq_lintegral_meas_le_mul_of_measurable μ f_nn f_mble G_intble G_mble (λ t t_pos, G_nn t), end /-- The standard case of the layer cake formula / Cavalieri's principle / tail probability formula: For a nonnegative function `f` on a sigma-finite measure space, the Lebesgue integral of `f` can be written (roughly speaking) as: `∫⁻ f ∂μ = ∫⁻ t in 0 .. ∞, μ {ω | f(ω) ≥ t}`. See `lintegral_eq_lintegral_meas_lt` for a version with sets of the form `{ω | f(ω) > t}` instead. -/ theorem lintegral_eq_lintegral_meas_le (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) : ∫⁻ ω, ennreal.of_real (f ω) ∂μ = ∫⁻ t in Ioi 0, (μ {a : α | t ≤ f a}) := begin set cst := λ (t : ℝ), (1 : ℝ) with def_cst, have cst_intble : ∀ t > 0, interval_integrable cst volume 0 t, from λ _ _, interval_integrable_const, have key := lintegral_comp_eq_lintegral_meas_le_mul μ f_nn f_mble cst_intble (eventually_of_forall (λ t, zero_le_one)), simp_rw [def_cst, ennreal.of_real_one, mul_one] at key, rw ← key, congr' with ω, simp only [interval_integral.integral_const, sub_zero, algebra.id.smul_eq_mul, mul_one], end /-- An application of the layer cake formula / Cavalieri's principle / tail probability formula: For a nonnegative function `f` on a sigma-finite measure space, the Lebesgue integral of `f` can be written (roughly speaking) as: `∫⁻ f^p ∂μ = p * ∫⁻ t in 0 .. ∞, t^(p-1) * μ {ω | f(ω) ≥ t}`. See `lintegral_rpow_eq_lintegral_meas_lt_mul` for a version with sets of the form `{ω | f(ω) > t}` instead. -/ theorem lintegral_rpow_eq_lintegral_meas_le_mul (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) {p : ℝ} (p_pos: 0 < p) : ∫⁻ ω, ennreal.of_real ((f ω)^p) ∂μ = (ennreal.of_real p) * ∫⁻ t in Ioi 0, (μ {a : α | t ≤ f a}) * ennreal.of_real (t^(p-1)) := begin have one_lt_p : -1 < p - 1 := by linarith, have obs : ∀ (x : ℝ), (∫ (t : ℝ) in 0..x, t^(p-1)) = x^p / p, { intros x, rw integral_rpow (or.inl one_lt_p), simp [real.zero_rpow p_pos.ne.symm], }, set g := λ (t : ℝ), t^(p-1) with g_def, have g_nn : ∀ᵐ t ∂(volume.restrict (Ioi (0 : ℝ))), 0 ≤ g t, { filter_upwards [self_mem_ae_restrict (measurable_set_Ioi : measurable_set (Ioi (0 : ℝ)))], intros t t_pos, rw g_def, exact real.rpow_nonneg_of_nonneg (mem_Ioi.mp t_pos).le (p - 1), }, have g_intble : ∀ t > 0, interval_integrable g volume 0 t, from λ _ _, interval_integral.interval_integrable_rpow' one_lt_p, have key := lintegral_comp_eq_lintegral_meas_le_mul μ f_nn f_mble g_intble g_nn, simp_rw [g_def] at key, rw [← key, ← lintegral_const_mul (ennreal.of_real p)]; simp_rw obs, { congr' with ω, rw [← ennreal.of_real_mul p_pos.le, mul_div_cancel' ((f ω)^p) p_pos.ne.symm], }, { exact ((f_mble.pow measurable_const).div_const p).ennreal_of_real, }, end end measure_theory end layercake section layercake_lt open measure_theory variables {α : Type*} [measurable_space α] (μ : measure α) variables {β : Type*} [measurable_space β] [measurable_singleton_class β] namespace measure lemma meas_le_ne_meas_lt_subset_meas_pos {R : Type*} [linear_order R] [measurable_space R] [measurable_singleton_class R] {g : α → R} (g_mble : measurable g) {t : R} (ht : μ {a : α | t ≤ g a} ≠ μ {a : α | t < g a}) : 0 < μ {a : α | g a = t} := begin have uni : {a : α | t ≤ g a } = {a : α | t < g a} ∪ {a : α | t = g a}, { ext a, simp only [mem_set_of_eq, mem_union], apply le_iff_lt_or_eq, }, rw (show {a : α | t = g a} = {a : α | g a = t}, by simp_rw [eq_comm]) at uni, have disj : {a : α | t < g a} ∩ {a : α | g a = t} = ∅, { ext a, simp only [mem_inter_iff, mem_set_of_eq, mem_empty_iff_false, iff_false, not_and], exact ne_of_gt, }, have μ_add : μ {a : α | t ≤ g a} = μ {a : α | t < g a} + μ {a : α | g a = t}, by rw [uni, measure_union (disjoint_iff_inter_eq_empty.mpr disj) (g_mble (finite.measurable_set (finite_singleton t)))], by_contra con, rw [not_lt, nonpos_iff_eq_zero] at con, rw [con, add_zero] at μ_add, exact ht μ_add, end lemma countable_meas_le_ne_meas_lt [sigma_finite μ] {R : Type*} [linear_order R] [measurable_space R] [measurable_singleton_class R] {g : α → R} (g_mble : measurable g) : {t : R | μ {a : α | t ≤ g a } ≠ μ {a : α | t < g a}}.countable := countable.mono (show _, from λ t ht, meas_le_ne_meas_lt_subset_meas_pos μ g_mble ht) (measure.countable_meas_level_set_pos g_mble) lemma meas_le_ae_eq_meas_lt [sigma_finite μ] {R : Type*} [linear_order R] [measurable_space R] [measurable_singleton_class R] (ν : measure R) [has_no_atoms ν] {g : α → R} (g_mble : measurable g) : (λ t, μ {a : α | t ≤ g a}) =ᵐ[ν] (λ t, μ {a : α | t < g a}) := set.countable.measure_zero (measure.countable_meas_le_ne_meas_lt μ g_mble) _ end measure variables {f : α → ℝ} {g : ℝ → ℝ} {s : set α} /-- The layer cake formula / Cavalieri's principle / tail probability formula: Let `f` be a non-negative measurable function on a sigma-finite measure space. Let `G` be an increasing absolutely continuous function on the positive real line, vanishing at the origin, with derivative `G' = g`. Then the integral of the composition `G ∘ f` can be written as the integral over the positive real line of the "tail measures" `μ {ω | f(ω) > t}` of `f` weighted by `g`. Roughly speaking, the statement is: `∫⁻ (G ∘ f) ∂μ = ∫⁻ t in 0 .. ∞, g(t) * μ {ω | f(ω) > t}`. See `lintegral_comp_eq_lintegral_meas_le_mul` for a version with sets of the form `{ω | f(ω) ≥ t}` instead. -/ theorem lintegral_comp_eq_lintegral_meas_lt_mul (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) (g_intble : ∀ t > 0, interval_integrable g volume 0 t) (g_nn : ∀ᵐ t ∂(volume.restrict (Ioi 0)), 0 ≤ g t) : ∫⁻ ω, ennreal.of_real (∫ t in 0 .. f ω, g t) ∂μ = ∫⁻ t in Ioi 0, μ {a : α | t < f a} * ennreal.of_real (g t) := begin rw lintegral_comp_eq_lintegral_meas_le_mul μ f_nn f_mble g_intble g_nn, apply lintegral_congr_ae, filter_upwards [measure.meas_le_ae_eq_meas_lt μ (volume.restrict (Ioi 0)) f_mble] with t ht, rw ht, end /-- The standard case of the layer cake formula / Cavalieri's principle / tail probability formula: For a nonnegative function `f` on a sigma-finite measure space, the Lebesgue integral of `f` can be written (roughly speaking) as: `∫⁻ f ∂μ = ∫⁻ t in 0 .. ∞, μ {ω | f(ω) > t}`. See `lintegral_eq_lintegral_meas_le` for a version with sets of the form `{ω | f(ω) ≥ t}` instead. -/ theorem lintegral_eq_lintegral_meas_lt (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) : ∫⁻ ω, ennreal.of_real (f ω) ∂μ = ∫⁻ t in Ioi 0, (μ {a : α | t < f a}) := begin rw lintegral_eq_lintegral_meas_le μ f_nn f_mble, apply lintegral_congr_ae, filter_upwards [measure.meas_le_ae_eq_meas_lt μ (volume.restrict (Ioi 0)) f_mble] with t ht, rw ht, end /-- An application of the layer cake formula / Cavalieri's principle / tail probability formula: For a nonnegative function `f` on a sigma-finite measure space, the Lebesgue integral of `f` can be written (roughly speaking) as: `∫⁻ f^p ∂μ = p * ∫⁻ t in 0 .. ∞, t^(p-1) * μ {ω | f(ω) > t}`. See `lintegral_rpow_eq_lintegral_meas_le_mul` for a version with sets of the form `{ω | f(ω) ≥ t}` instead. -/ theorem lintegral_rpow_eq_lintegral_meas_lt_mul (μ : measure α) [sigma_finite μ] (f_nn : 0 ≤ f) (f_mble : measurable f) {p : ℝ} (p_pos: 0 < p) : ∫⁻ ω, ennreal.of_real ((f ω)^p) ∂μ = (ennreal.of_real p) * ∫⁻ t in Ioi 0, (μ {a : α | t < f a}) * ennreal.of_real (t^(p-1)) := begin rw lintegral_rpow_eq_lintegral_meas_le_mul μ f_nn f_mble p_pos, apply congr_arg (λ z, (ennreal.of_real p * z)), apply lintegral_congr_ae, filter_upwards [measure.meas_le_ae_eq_meas_lt μ (volume.restrict (Ioi 0)) f_mble] with t ht, rw ht, end end layercake_lt
9bd2ba637ff425c0b64a2e40ba30d56f5b3332b0
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/uniform_space/basic.lean
2f738fba4cdee79aab248b5be8b0ec69c7948bdd
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
69,686
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 order.filter.lift import topology.separation /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space filter set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ @[mono] lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k := λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s := λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩ /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := begin unfold symmetric_rel at *, rw [preimage_inter, hU, hV], end /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : 𝓟 id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- Suppose that one can put two mathematical structures on a type, a rich one `R` and a poor one `P`, and that one can deduce the poor structure from the rich structure through a map `F` (called a forgetful functor) (think `R = metric_space` and `P = topological_space`). A possible implementation would be to have a type class `rich` containing a field `R`, a type class `poor` containing a field `P`, and an instance from `rich` to `poor`. However, this creates diamond problems, and a better approach is to let `rich` extend `poor` and have a field saying that `F R = P`. To illustrate this, consider the pair `metric_space` / `topological_space`. Consider the topology on a product of two metric spaces. With the first approach, it could be obtained by going first from each metric space to its topology, and then taking the product topology. But it could also be obtained by considering the product metric space (with its sup distance) and then the topology coming from this distance. These would be the same topology, but not definitionally, which means that from the point of view of Lean's kernel, there would be two different `topological_space` instances on the product. This is not compatible with the way instances are designed and used: there should be at most one instance of a kind on each type. This approach has created an instance diamond that does not commute definitionally. The second approach solves this issue. Now, a metric space contains both a distance, a topology, and a proof that the topology coincides with the one coming from the distance. When one defines the product of two metric spaces, one uses the sup distance and the product topology, and one has to give the proof that the sup distance induces the product topology. Following both sides of the instance diamond then gives rise (definitionally) to the product topology on the product space. Another approach would be to have the rich type class take the poor type class as an instance parameter. It would solve the diamond problem, but it would lead to a blow up of the number of type classes one would need to declare to work with complicated classes, say a real inner product space, and would create exponential complexity when working with products of such complicated spaces, that are avoided by bundling things carefully as above. Note that this description of this specific case of the product of metric spaces is oversimplified compared to mathlib, as there is an intermediate typeclass between `metric_space` and `topological_space` called `uniform_space`. The above scheme is used at both levels, embedding a topology in the uniform space structure, and a uniform structure in the metric space structure. Note also that, when `P` is a proposition, there is no such issue as any two proofs of `P` are definitionally equivalent in Lean. To avoid boilerplate, there are some designs that can automatically fill the poor fields when creating a rich structure if one doesn't want to do something special about them. For instance, in the definition of metric spaces, default tactics fill the uniform space fields if they are not given explicitly. One can also have a helper function creating the rich structure from a structure with less fields, where the helper function fills the remaining fields. See for instance `uniform_space.of_core` or `real_inner_product.of_core`. For more details on this question, called the forgetful inheritance pattern, see [Competing inheritance paths in dependent type theory: a case study in functional analysis](https://hal.inria.fr/hal-02463336). -/ library_note "forgetful inheritance" /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem_sets' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs, use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w], have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w, calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono ... ⊆ s : w_sub, end lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s := subset_comp_self (refl_le_uniformity h) lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s := begin rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩, rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩, use [t, t_in, t_symm], have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in, calc t ○ t ○ t ⊆ w ○ t : by mono ... ⊆ w ○ (t ○ t) : by mono ... ⊆ w ○ w : by mono ... ⊆ s : w_sub, end /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V) (hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W := begin rw mem_ball_symmetry hV at hx, exact ⟨z, hx, hy⟩ end lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty := begin cases p with x y, split, { rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩, exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, }, { rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩, rwa mem_ball_symmetry hW' at z_in, use [z, w] ; tauto }, end /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : {p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F := by rw mem_comap_sets ; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, F.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux } lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (x, y) ∈ s i}) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin rw [nhds_eq_comap_uniformity, mem_comap_sets], exact iff.rfl, end lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x := begin rw uniform_space.mem_nhds_iff, exact ⟨V, V_in, subset.refl _⟩ end lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s := begin rw uniform_space.mem_nhds_iff, split, { rintros ⟨V, V_in, V_sub⟩, use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V], exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub }, { rintros ⟨V, V_in, V_symm, V_sub⟩, exact ⟨V, V_in, V_sub⟩ } end lemma uniform_space.has_basis_nhds (x : α) : has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) := ⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩ open uniform_space lemma uniform_space.has_basis_nhds_prod (x y : α) : has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) := begin rw nhds_prod_eq, apply (has_basis_nhds x).prod' (has_basis_nhds y), rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩, exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩, ball_mono (inter_subset_left U V) x, ball_mono (inter_subset_right U V) y⟩, end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := (nhds_basis_uniformity' (𝓤 α).basis_sets).mem_of_mem h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : 𝓝 a ×ᶠ 𝓝 b = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-- Entourages are neighborhoods of the diagonal. -/ lemma nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α := begin apply supr_le _, intros x V V_in, rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩, have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x), { rw nhds_prod_eq, exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) }, apply mem_sets_of_superset this, rintros ⟨u, v⟩ ⟨u_in, v_in⟩, exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in) end /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_uniformity (s : set $ α × α) : closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V := begin ext ⟨x, y⟩, simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter, mem_set_of_eq], apply forall_congr, intro V, apply forall_congr, rintros ⟨V_in, V_symm⟩, simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop], exact iff.rfl, end lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id := begin rw filter.has_basis_self, intro t, split, { intro h, rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩, refine ⟨closure w, _, is_closed_closure, _⟩, apply mem_sets_of_superset w_in subset_closure, refine subset.trans _ r, rw closure_eq_uniformity, apply Inter_subset_of_subset, apply Inter_subset, exact ⟨w_in, w_symm⟩ }, { rintros ⟨r, r_in, r_closed, r_sub⟩, exact mem_sets_of_superset r_in r_sub, } end /-- Closed entourages form a basis of the uniformity filter. -/ lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure := ⟨begin intro t, rw uniformity_has_basis_closed.mem_iff, split, { rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩, use [r, r_in], convert r_sub, rw r_closed.closure_eq, refl }, { rintros ⟨r, r_in, r_sub⟩, exact ⟨closure r, ⟨mem_sets_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ } end⟩ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_cluster_pt ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, ← ne_bot, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /-! ### Uniformity bases -/ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := ⟨λ t, ⟨λ t_in, ⟨symmetrize_rel t, ⟨⟨symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t⟩, symmetrize_rel_subset_self _⟩⟩, λ ⟨s, ⟨s_in, h⟩, hst⟩, mem_sets_of_superset s_in hst⟩⟩ lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) : ∃ V : ℕ → set (α × α), has_antimono_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) := begin rcases h.has_antimono_basis with ⟨U, hbasis, hdec, monotrue⟩, clear monotrue, simp only [forall_prop_of_true] at hdec, use λ n, symmetrize_rel (U n), refine ⟨⟨⟨_⟩, by intros ; mono, by tauto⟩, λ n, symmetric_symmetrize_rel _⟩, intros t, rw hbasis.mem_iff, split, { rintro ⟨i, _, hi⟩, exact ⟨i, trivial, subset.trans (inter_subset_left _ _) hi⟩ }, { rintro ⟨i, _, hi⟩, rcases hbasis.mem_iff.mp (symmetrize_mem_uniformity $ hbasis.mem_of_mem trivial) with ⟨j, _, hj⟩, use j, tauto } end /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop := tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} : uniform_continuous_on f S ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i := ((ha.inf_principal (S.prod S)).tendsto_iff hb).trans $ by finish [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := 𝓟 id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓤 α = comap (prod.map f f) (𝓤 β) := by { rw h, refl } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := begin by_cases h : nonempty ι, { resetI, refine (eq_of_nhds_eq_nhds $ assume a, _), rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, rw [infi_uniformity, lift'_infi], { simp only [nhds_eq_uniformity], refl }, { exact assume a b, rfl } }, { rw [infi_of_empty h, infi_of_empty h, to_topological_space_top] } end lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi], simp only [← to_topological_space_infi], end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) := begin unfold uniform_continuous_on set.restrict uniform_continuous tendsto, rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl, uniformity_comap rfl, show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl], conv in (map _ (comap _ _)) { rw ← filter.map_map }, rw subtype_coe_map_comap_prod, refl, end lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s := begin rw uniform_continuous_on_iff_restrict at h, rw continuous_on_iff_continuous_restrict, exact h.continuous end section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
6f7f5be4e7d7eda93443013e346d6a1986bca49c
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/t1.lean
8e8b6275e11f72a0d6ffb60ccf50a6ea4a06de56
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
325
lean
prelude definition Prop : Type.{1} := Type.{0} print raw ((Prop)) print raw Prop print raw fun (x y : Prop), x x print raw fun (x y : Prop) {z : Prop}, x y print raw λ [x y : Prop] {z : Prop}, x z print raw Pi (x y : Prop) {z : Prop}, x print raw ∀ (x y : Prop) {z : Prop}, x print raw forall {x y : Prop} w {z : Prop}, x
49fe64cf5eb56a5aad6317e0832162dc5698f6b0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe_issue2.lean
56ed2c24b4295c13451fa0a0ae8d016d256173eb
[ "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
132
lean
import data.int data.real open int real example : (1 : ℤ) * (1 : ℤ) = (1 : ℤ) := sorry example : (1 : ℤ) * 1 = 1 := sorry
95373a6b112ad44d85164f287b8bbc4e2de7d399
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/converter/conv.lean
14261d2ee5fb33f3c08b7a3f14c6b0f388e08f4b
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
3,436
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Converter monad for building simplifiers. -/ prelude import init.meta.tactic init.meta.simp_tactic init.meta.interactive import init.meta.congr_lemma init.meta.match_tactic open tactic universe u meta def conv (α : Type u) := tactic α meta instance : monad conv := by dunfold conv; apply_instance meta instance : monad_fail conv := by dunfold conv; apply_instance meta instance : alternative conv := by dunfold conv; apply_instance namespace conv meta def convert (c : conv unit) (lhs : expr) (rel : name := `eq) : tactic (expr × expr) := do lhs_type ← infer_type lhs, rhs ← mk_meta_var lhs_type, new_target ← mk_app rel [lhs, rhs], new_g ← mk_meta_var new_target, gs ← get_goals, set_goals [new_g], c, repeat reflexivity, n ← num_goals, when (n ≠ 0) (fail "convert tactic failed, there are unsolved goals"), set_goals gs, rhs ← instantiate_mvars rhs, new_g ← instantiate_mvars new_g, return (rhs, new_g) meta def lhs : conv expr := do (_, lhs, rhs) ← target_lhs_rhs, return lhs meta def rhs : conv expr := do (_, lhs, rhs) ← target_lhs_rhs, return rhs meta def update_lhs (new_lhs : expr) (h : expr) : conv unit := do transitivity, rhs >>= unify new_lhs, exact h, t ← target >>= instantiate_mvars, change t meta def change (new_lhs : expr) : conv unit := do (r, lhs, rhs) ← target_lhs_rhs, new_target ← mk_app r [new_lhs, rhs], tactic.change new_target meta def skip : conv unit := reflexivity meta def whnf : conv unit := lhs >>= tactic.whnf >>= change meta def dsimp (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : conv unit := do s ← match s with | some s := return s | none := simp_lemmas.mk_default end, l ← lhs, s.dsimplify u l cfg >>= change private meta def congr_aux : list congr_arg_kind → list expr → tactic (list expr × list expr) | [] [] := return ([], []) | (k::ks) (a::as) := do (gs, largs) ← congr_aux ks as, match k with | congr_arg_kind.fixed := return $ (gs, a::largs) | congr_arg_kind.fixed_no_param := return $ (gs, largs) | congr_arg_kind.eq := do a_type ← infer_type a, rhs ← mk_meta_var a_type, g_type ← mk_app `eq [a, rhs], g ← mk_meta_var g_type, return (g::gs, a::rhs::g::largs) | congr_arg_kind.cast := return $ (gs, a::largs) | _ := fail "congr tactic failed, unsupported congruence lemma" end | ks as := fail "congr tactic failed, unsupported congruence lemma" meta def congr : conv unit := do (r, lhs, rhs) ← target_lhs_rhs, guard (r = `eq), let fn := lhs.get_app_fn, let args := lhs.get_app_args, cgr_lemma ← mk_congr_lemma_simp fn (some args.length), g::gs ← get_goals, (new_gs, lemma_args) ← congr_aux cgr_lemma.arg_kinds args, let g_val := cgr_lemma.proof.mk_app lemma_args, unify g g_val, set_goals $ new_gs ++ gs, return () meta def funext : conv unit := repeat $ do (r, lhs, rhs) ← target_lhs_rhs, guard (r = `eq), (expr.lam n _ _ _) ← return lhs, tactic.applyc `funext, intro n, return () end conv
09b81fbf37f8771efacfdd6543da20cd6ee7d87a
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/has_reflect.lean
fe33fcabf8575ffaeb028e0b36aa472a0c2b5810
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,753
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.expr init.util @[reducible] meta def {u} has_reflect (α : Sort u) := Π a : α, reflected a meta instance bool.reflect : has_reflect bool | tt := `(tt) | ff := `(ff) section local attribute [semireducible] reflected meta instance nat.reflect : has_reflect ℕ | n := if n = 0 then `(0 : ℕ) else if n = 1 then `(1 : ℕ) else if n % 2 = 0 then `(bit0 %%(nat.reflect (n / 2)) : ℕ) else `(bit1 %%(nat.reflect (n / 2)) : ℕ) meta instance unsigned.reflect : has_reflect unsigned | ⟨n, pr⟩ := `(unsigned.of_nat' n) end meta instance name.reflect : has_reflect name | name.anonymous := `(name.anonymous) | (name.mk_string s n) := `(λ n, name.mk_string s n).subst (name.reflect n) | (name.mk_numeral i n) := `(λ n, name.mk_numeral i n).subst (name.reflect n) meta instance list.reflect {α : Type} [has_reflect α] [reflected α] : has_reflect (list α) | [] := `([]) | (h::t) := `(λ t, h :: t).subst (list.reflect t) meta instance option.reflect {α : Type} [has_reflect α] [reflected α] : has_reflect (option α) | (some x) := `(_) | none := `(_) meta instance unit.reflect : has_reflect unit | () := `(_) meta instance prod.reflect {α β : Type} [has_reflect α] [reflected α] [has_reflect β] [reflected β] : has_reflect (α × β) | ⟨x, y⟩ := `(_) meta instance pos.reflect : has_reflect pos | ⟨l, c⟩ := `(_) meta instance sum.reflect {α β : Type} [has_reflect α] [reflected α] [has_reflect β] [reflected β] : has_reflect (sum α β) | (sum.inl _) := `(_) | (sum.inr _) := `(_)
9e7cf3d621cc29ff5517b4e311ebd48f3a4fac61
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/abelian/diagram_lemmas/four.lean
b8f794e147076e6ebd05bd1a25bc30ad8b9012b4
[ "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
7,627
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 category_theory.abelian.pseudoelements /-! # The four and five lemmas Consider the following commutative diagram with exact rows in an abelian category: ``` A ---f--> B ---g--> C ---h--> D ---i--> E | | | | | α β γ δ ε | | | | | v v v v v A' --f'-> B' --g'-> C' --h'-> D' --i'-> E' ``` We show: - the "mono" version of the four lemma: if `α` is an epimorphism and `β` and `δ` are monomorphisms, then `γ` is a monomorphism, - the "epi" version of the four lemma: if `β` and `δ` are epimorphisms and `ε` is a monomorphism, then `γ` is an epimorphism, - the five lemma: if `α`, `β`, `δ` and `ε` are isomorphisms, then `γ` is an isomorphism. ## Implementation details To show the mono version, we use pseudoelements. For the epi version, we use a completely different arrow-theoretic proof. In theory, it should be sufficient to have one version and the other should follow automatically by duality. In practice, mathlib's knowledge about duality isn't quite at the point where this is doable easily. However, one key duality statement about exactness is needed in the proof of the epi version of the four lemma: we need to know that exactness of a pair `(f, g)`, which we defined via the map from the image of `f` to the kernel of `g`, is the same as "co-exactness", defined via the map from the cokernel of `f` to the coimage of `g` (more precisely, we only need the consequence that if `(f, g)` is exact, then the factorization of `g` through the cokernel of `f` is monomorphic). Luckily, in the case of abelian categories, we have the characterization that `(f, g)` is exact if and only if `f ≫ g = 0` and `kernel.ι g ≫ cokernel.π f = 0`, and the latter condition is self dual, so the equivalence of exactness and co-exactness follows easily. ## Tags four lemma, five lemma, diagram lemma, diagram chase -/ open category_theory (hiding comp_apply) open category_theory.abelian.pseudoelement open category_theory.limits universes v u variables {V : Type u} [category.{v} V] [abelian V] local attribute [instance] preadditive.has_equalizers_of_has_kernels local attribute [instance] object_to_sort hom_to_fun open_locale pseudoelement namespace category_theory.abelian variables {A B C D A' B' C' D' : V} variables {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D} variables {f' : A' ⟶ B'} {g' : B' ⟶ C'} {h' : C' ⟶ D'} variables {α : A ⟶ A'} {β : B ⟶ B'} {γ : C ⟶ C'} {δ : D ⟶ D'} variables (comm₁ : α ≫ f' = f ≫ β) (comm₂ : β ≫ g' = g ≫ γ) (comm₃ : γ ≫ h' = h ≫ δ) include comm₁ comm₂ comm₃ section variables [exact f g] [exact g h] [exact f' g'] /-- The four lemma, mono version. For names of objects and morphisms, refer to the following diagram: ``` A ---f--> B ---g--> C ---h--> D | | | | α β γ δ | | | | v v v v A' --f'-> B' --g'-> C' --h'-> D' ``` -/ lemma mono_of_epi_of_mono_of_mono (hα : epi α) (hβ : mono β) (hδ : mono δ) : mono γ := mono_of_zero_of_map_zero _ $ λ c hc, have h c = 0, from suffices δ (h c) = 0, from zero_of_map_zero _ (pseudo_injective_of_mono _) _ this, calc δ (h c) = h' (γ c) : by rw [←comp_apply, ←comm₃, comp_apply] ... = h' 0 : by rw hc ... = 0 : apply_zero _, exists.elim (pseudo_exact_of_exact.2 _ this) $ λ b hb, have g' (β b) = 0, from calc g' (β b) = γ (g b) : by rw [←comp_apply, comm₂, comp_apply] ... = γ c : by rw hb ... = 0 : hc, exists.elim (pseudo_exact_of_exact.2 _ this) $ λ a' ha', exists.elim (pseudo_surjective_of_epi α a') $ λ a ha, have f a = b, from suffices β (f a) = β b, from pseudo_injective_of_mono _ this, calc β (f a) = f' (α a) : by rw [←comp_apply, ←comm₁, comp_apply] ... = f' a' : by rw ha ... = β b : ha', calc c = g b : hb.symm ... = g (f a) : by rw this ... = 0 : pseudo_exact_of_exact.1 _ end section variables [exact g h] [exact f' g'] [exact g' h'] /-- The four lemma, epi version. For names of objects and morphisms, refer to the following diagram: ``` A ---f--> B ---g--> C ---h--> D | | | | α β γ δ | | | | v v v v A' --f'-> B' --g'-> C' --h'-> D' ``` -/ lemma epi_of_epi_of_epi_of_mono (hα : epi α) (hγ : epi γ) (hδ : mono δ) : epi β := preadditive.epi_of_cancel_zero _ $ λ R r hβr, have hf'r : f' ≫ r = 0, from limits.zero_of_epi_comp α $ calc α ≫ f' ≫ r = f ≫ β ≫ r : by rw reassoc_of comm₁ ... = f ≫ 0 : by rw hβr ... = 0 : has_zero_morphisms.comp_zero _ _, let y : R ⟶ pushout r g' := pushout.inl, z : C' ⟶ pushout r g' := pushout.inr in have mono y, from mono_inl_of_factor_thru_epi_mono_factorization r g' (cokernel.π f') (cokernel.desc f' g' (by simp)) (by simp) (cokernel.desc f' r hf'r) (by simp) _ (colimit.is_colimit _), have hz : g ≫ γ ≫ z = 0, from calc g ≫ γ ≫ z = β ≫ g' ≫ z : by rw ←reassoc_of comm₂ ... = β ≫ r ≫ y : by rw ←pushout.condition ... = 0 ≫ y : by rw reassoc_of hβr ... = 0 : has_zero_morphisms.zero_comp _ _, let v : pushout r g' ⟶ pushout (γ ≫ z) (h ≫ δ) := pushout.inl, w : D' ⟶ pushout (γ ≫ z) (h ≫ δ) := pushout.inr in have mono v, from mono_inl_of_factor_thru_epi_mono_factorization _ _ (cokernel.π g) (cokernel.desc g h (by simp) ≫ δ) (by simp) (cokernel.desc _ _ hz) (by simp) _ (colimit.is_colimit _), have hzv : z ≫ v = h' ≫ w, from (cancel_epi γ).1 $ calc γ ≫ z ≫ v = h ≫ δ ≫ w : by rw [←category.assoc, pushout.condition, category.assoc] ... = γ ≫ h' ≫ w : by rw reassoc_of comm₃, suffices (r ≫ y) ≫ v = 0, by exactI zero_of_comp_mono _ (zero_of_comp_mono _ this), calc (r ≫ y) ≫ v = g' ≫ z ≫ v : by rw [pushout.condition, category.assoc] ... = g' ≫ h' ≫ w : by rw hzv ... = 0 ≫ w : exact.w_assoc _ ... = 0 : has_zero_morphisms.zero_comp _ _ end section five variables {E E' : V} {i : D ⟶ E} {i' : D' ⟶ E'} {ε : E ⟶ E'} (comm₄ : δ ≫ i' = i ≫ ε) variables [exact f g] [exact g h] [exact h i] [exact f' g'] [exact g' h'] [exact h' i'] variables [is_iso α] [is_iso β] [is_iso δ] [is_iso ε] include comm₄ /-- The five lemma. For names of objects and morphisms, refer to the following diagram: ``` A ---f--> B ---g--> C ---h--> D ---i--> E | | | | | α β γ δ ε | | | | | v v v v v A' --f'-> B' --g'-> C' --h'-> D' --i'-> E' ``` -/ lemma is_iso_of_is_iso_of_is_iso_of_is_iso_of_is_iso : is_iso γ := have mono γ, by apply mono_of_epi_of_mono_of_mono comm₁ comm₂ comm₃; apply_instance, have epi γ, by apply epi_of_epi_of_epi_of_mono comm₂ comm₃ comm₄; apply_instance, by exactI is_iso_of_mono_of_epi _ end five end category_theory.abelian
d9503d42f8f1d15be03f9a0322e213c4f0f4bda4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/euclidean/monge_point.lean
2e03285bc3c35c790b6b50870f079a3e9b428367
[ "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
38,118
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.circumcenter /-! # Monge point and orthocenter This file defines the orthocenter of a triangle, via its n-dimensional generalization, the Monge point of a simplex. ## Main definitions * `monge_point` is the Monge point of a simplex, defined in terms of its position on the Euler line and then shown to be the point of concurrence of the Monge planes. * `monge_plane` is a Monge plane of an (n+2)-simplex, which is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). * `altitude` is the line that passes through a vertex of a simplex and is orthogonal to the opposite face. * `orthocenter` is defined, for the case of a triangle, to be the same as its Monge point, then shown to be the point of concurrence of the altitudes. * `orthocentric_system` is a predicate on sets of points that says whether they are four points, one of which is the orthocenter of the other three (in which case various other properties hold, including that each is the orthocenter of the other three). ## References * <https://en.wikipedia.org/wiki/Altitude_(triangle)> * <https://en.wikipedia.org/wiki/Monge_point> * <https://en.wikipedia.org/wiki/Orthocentric_system> * Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point Sphere of an n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf) -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace affine namespace simplex open finset affine_subspace euclidean_geometry points_with_circumcenter_index variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The Monge point of a simplex (in 2 or more dimensions) is a generalization of the orthocenter of a triangle. It is defined to be the intersection of the Monge planes, where a Monge plane is the (n-1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an (n-2)-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). The circumcenter O, centroid G and Monge point M are collinear in that order on the Euler line, with OG : GM = (n-1) : 2. Here, we use that ratio to define the Monge point (so resulting in a point that equals the centroid in 0 or 1 dimensions), and then show in subsequent lemmas that the point so defined lies in the Monge planes and is their unique point of intersection. -/ def monge_point {n : ℕ} (s : simplex ℝ P n) : P := (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) • ((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ s.circumcenter /-- The position of the Monge point in relation to the circumcenter and centroid. -/ lemma monge_point_eq_smul_vsub_vadd_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.monge_point = (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) • ((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ s.circumcenter := rfl /-- The Monge point lies in the affine span. -/ lemma monge_point_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.monge_point ∈ affine_span ℝ (set.range s.points) := smul_vsub_vadd_mem _ _ (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (card_fin (n + 1))) s.circumcenter_mem_affine_span s.circumcenter_mem_affine_span /-- Two simplices with the same points have the same Monge point. -/ lemma monge_point_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.monge_point = s₂.monge_point := by simp_rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_of_range_eq h, circumcenter_eq_of_range_eq h] omit V /-- The weights for the Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + 2) → ℝ | (point_index i) := (((n + 1) : ℕ) : ℝ)⁻¹ | circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ)) /-- `monge_point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_monge_point_weights_with_circumcenter (n : ℕ) : ∑ i, monge_point_weights_with_circumcenter n i = 1 := begin simp_rw [sum_points_with_circumcenter, monge_point_weights_with_circumcenter, sum_const, card_fin, nsmul_eq_mul], have hn1 : (n + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, field_simp [hn1], ring end include V /-- The Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ lemma monge_point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P (n + 2)) : s.monge_point = (univ : finset (points_with_circumcenter_index (n + 2))).affine_combination s.points_with_circumcenter (monge_point_weights_with_circumcenter n) := begin rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub, ←linear_map.map_smul, weighted_vsub_vadd_affine_combination], congr' with i, rw [pi.add_apply, pi.smul_apply, smul_eq_mul, pi.sub_apply], have hn1 : (n + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, cases i; simp_rw [centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, monge_point_weights_with_circumcenter]; rw [add_tsub_assoc_of_le (dec_trivial : 1 ≤ 2), (dec_trivial : 2 - 1 = 1)], { rw [if_pos (mem_univ _), sub_zero, add_zero, card_fin], have hn3 : (n + 2 + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, field_simp [hn1, hn3, mul_comm] }, { field_simp [hn1], ring } end omit V /-- The weights for the Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/ def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 3)) : points_with_circumcenter_index (n + 2) → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then (((n + 1) : ℕ) : ℝ)⁻¹ else 0 | circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ)) /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the result of subtracting `centroid_weights_with_circumcenter` from `monge_point_weights_with_circumcenter`. -/ lemma monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ} {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ = monge_point_weights_with_circumcenter n - centroid_weights_with_circumcenter ({i₁, i₂}ᶜ) := begin ext i, cases i, { rw [pi.sub_apply, monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter, monge_point_vsub_face_centroid_weights_with_circumcenter], have hu : card ({i₁, i₂}ᶜ : finset (fin (n + 3))) = n + 1, { simp [card_compl, fintype.card_fin, h] }, rw hu, by_cases hi : i = i₁ ∨ i = i₂; simp [compl_eq_univ_sdiff, hi] }, { simp [monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter, monge_point_vsub_face_centroid_weights_with_circumcenter] } end /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/ @[simp] lemma sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : ∑ i, monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i = 0 := begin rw monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h, simp_rw [pi.sub_apply, sum_sub_distrib, sum_monge_point_weights_with_circumcenter], rw [sum_centroid_weights_with_circumcenter, sub_self], simp [←card_pos, card_compl, h] end include V /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. -/ lemma monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points = (univ : finset (points_with_circumcenter_index (n + 2))).weighted_vsub s.points_with_circumcenter (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) := by simp_rw [monge_point_eq_affine_combination_of_points_with_circumcenter, centroid_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub, monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h] /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, is orthogonal to the difference of the two vertices not in that face. -/ lemma inner_monge_point_vsub_face_centroid_vsub {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} : ⟪s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points, s.points i₁ -ᵥ s.points i₂⟫ = 0 := begin by_cases h : i₁ = i₂, { simp [h], }, simp_rw [monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter s h, point_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub], have hs : ∑ i, (point_weights_with_circumcenter i₁ - point_weights_with_circumcenter i₂) i = 0, { simp }, rw [inner_weighted_vsub _ (sum_monge_point_vsub_face_centroid_weights_with_circumcenter h) _ hs, sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter], simp only [monge_point_vsub_face_centroid_weights_with_circumcenter, points_with_circumcenter_point], let fs : finset (fin (n + 3)) := {i₁, i₂}, have hfs : ∀ i : fin (n + 3), i ∉ fs → (i ≠ i₁ ∧ i ≠ i₂), { intros i hi, split ; { intro hj, simpa [←hj] using hi } }, rw ←sum_subset fs.subset_univ _, { simp_rw [sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter, points_with_circumcenter_point, pi.sub_apply, point_weights_with_circumcenter], rw [←sum_subset fs.subset_univ _], { simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton], repeat { rw ←sum_subset fs.subset_univ _ }, { simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton], simp [h, ne.symm h, dist_comm (s.points i₁)] }, all_goals { intros i hu hi, simp [hfs i hi] } }, { intros i hu hi, simp [hfs i hi, point_weights_with_circumcenter] } }, { intros i hu hi, simp [hfs i hi] } end /-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). This definition is only intended to be used when `i₁ ≠ i₂`. -/ def monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : affine_subspace ℝ P := mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points) (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ affine_span ℝ (set.range s.points) /-- The definition of a Monge plane. -/ lemma monge_plane_def {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : s.monge_plane i₁ i₂ = mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points) (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ affine_span ℝ (set.range s.points) := rfl /-- The Monge plane associated with vertices `i₁` and `i₂` equals that associated with `i₂` and `i₁`. -/ lemma monge_plane_comm {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : s.monge_plane i₁ i₂ = s.monge_plane i₂ i₁ := begin simp_rw monge_plane_def, congr' 3, { congr' 1, exact pair_comm _ _ }, { ext, simp_rw submodule.mem_span_singleton, split, all_goals { rintros ⟨r, rfl⟩, use -r, rw [neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev] } } end /-- The Monge point lies in the Monge planes. -/ lemma monge_point_mem_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} : s.monge_point ∈ s.monge_plane i₁ i₂ := begin rw [monge_plane_def, mem_inf_iff, ←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _), direction_mk', submodule.mem_orthogonal'], refine ⟨_, s.monge_point_mem_affine_span⟩, intros v hv, rcases submodule.mem_span_singleton.mp hv with ⟨r, rfl⟩, rw [inner_smul_right, s.inner_monge_point_vsub_face_centroid_vsub, mul_zero] end /-- The direction of a Monge plane. -/ lemma direction_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} : (s.monge_plane i₁ i₂).direction = (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points) := by rw [monge_plane_def, direction_inf_of_mem_inf s.monge_point_mem_monge_plane, direction_mk', direction_affine_span] /-- The Monge point is the only point in all the Monge planes from any one vertex. -/ lemma eq_monge_point_of_forall_mem_monge_plane {n : ℕ} {s : simplex ℝ P (n + 2)} {i₁ : fin (n + 3)} {p : P} (h : ∀ i₂, i₁ ≠ i₂ → p ∈ s.monge_plane i₁ i₂) : p = s.monge_point := begin rw ←@vsub_eq_zero_iff_eq V, have h' : ∀ i₂, i₁ ≠ i₂ → p -ᵥ s.monge_point ∈ (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points), { intros i₂ hne, rw [←s.direction_monge_plane, vsub_right_mem_direction_iff_mem s.monge_point_mem_monge_plane], exact h i₂ hne }, have hi : p -ᵥ s.monge_point ∈ ⨅ (i₂ : {i // i₁ ≠ i}), (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ, { rw submodule.mem_infi, exact λ i, (submodule.mem_inf.1 (h' i i.property)).1 }, rw [submodule.infi_orthogonal, ←submodule.span_Union] at hi, have hu : (⋃ (i : {i // i₁ ≠ i}), ({s.points i₁ -ᵥ s.points i} : set V)) = (-ᵥ) (s.points i₁) '' (s.points '' (set.univ \ {i₁})), { rw [set.image_image], ext x, simp_rw [set.mem_Union, set.mem_image, set.mem_singleton_iff, set.mem_diff_singleton], split, { rintros ⟨i, rfl⟩, use [i, ⟨set.mem_univ _, i.property.symm⟩] }, { rintros ⟨i, ⟨hiu, hi⟩, rfl⟩, use [⟨i, hi.symm⟩, rfl] } }, rw [hu, ←vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_univ _), set.image_univ] at hi, have hv : p -ᵥ s.monge_point ∈ vector_span ℝ (set.range s.points), { let s₁ : finset (fin (n + 3)) := univ.erase i₁, obtain ⟨i₂, h₂⟩ := card_pos.1 (show 0 < card s₁, by simp [card_erase_of_mem]), have h₁₂ : i₁ ≠ i₂ := (ne_of_mem_erase h₂).symm, exact (submodule.mem_inf.1 (h' i₂ h₁₂)).2 }, exact submodule.disjoint_def.1 ((vector_span ℝ (set.range s.points)).orthogonal_disjoint) _ hv hi, end /-- An altitude of a simplex is the line that passes through a vertex and is orthogonal to the opposite face. -/ def altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : affine_subspace ℝ P := mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓ affine_span ℝ (set.range s.points) /-- The definition of an altitude. -/ lemma altitude_def {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : s.altitude i = mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓ affine_span ℝ (set.range s.points) := rfl /-- A vertex lies in the corresponding altitude. -/ lemma mem_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : s.points i ∈ s.altitude i := (mem_inf_iff _ _ _).2 ⟨self_mem_mk' _ _, mem_affine_span ℝ (set.mem_range_self _)⟩ /-- The direction of an altitude. -/ lemma direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : (s.altitude i).direction = (vector_span ℝ (s.points '' ↑(finset.univ.erase i)))ᗮ ⊓ vector_span ℝ (set.range s.points) := by rw [altitude_def, direction_inf_of_mem (self_mem_mk' (s.points i) _) (mem_affine_span ℝ (set.mem_range_self _)), direction_mk', direction_affine_span, direction_affine_span] /-- The vector span of the opposite face lies in the direction orthogonal to an altitude. -/ lemma vector_span_le_altitude_direction_orthogonal {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : vector_span ℝ (s.points '' ↑(finset.univ.erase i)) ≤ (s.altitude i).directionᗮ := begin rw direction_altitude, exact le_trans (vector_span ℝ (s.points '' ↑(finset.univ.erase i))).le_orthogonal_orthogonal (submodule.orthogonal_le inf_le_left) end open finite_dimensional /-- An altitude is finite-dimensional. -/ instance finite_dimensional_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : finite_dimensional ℝ ((s.altitude i).direction) := begin rw direction_altitude, apply_instance end /-- An altitude is one-dimensional (i.e., a line). -/ @[simp] lemma finrank_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : finrank ℝ ((s.altitude i).direction) = 1 := begin rw direction_altitude, have h := submodule.finrank_add_inf_finrank_orthogonal (vector_span_mono ℝ (set.image_subset_range s.points ↑(univ.erase i))), have hc : card (univ.erase i) = n + 1, { rw card_erase_of_mem (mem_univ _), simp }, refine add_left_cancel (trans h _), rw [s.independent.finrank_vector_span (fintype.card_fin _), ← finset.coe_image, s.independent.finrank_vector_span_image_finset hc] end /-- A line through a vertex is the altitude through that vertex if and only if it is orthogonal to the opposite face. -/ lemma affine_span_pair_eq_altitude_iff {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) (p : P) : affine_span ℝ {p, s.points i} = s.altitude i ↔ (p ≠ s.points i ∧ p ∈ affine_span ℝ (set.range s.points) ∧ p -ᵥ s.points i ∈ (affine_span ℝ (s.points '' ↑(finset.univ.erase i))).directionᗮ) := begin rw [eq_iff_direction_eq_of_mem (mem_affine_span ℝ (set.mem_insert_of_mem _ (set.mem_singleton _))) (s.mem_altitude _), ←vsub_right_mem_direction_iff_mem (mem_affine_span ℝ (set.mem_range_self i)) p, direction_affine_span, direction_affine_span, direction_affine_span], split, { intro h, split, { intro heq, rw [heq, set.pair_eq_singleton, vector_span_singleton] at h, have hd : finrank ℝ (s.altitude i).direction = 0, { rw [←h, finrank_bot] }, simpa using hd }, { rw [←submodule.mem_inf, _root_.inf_comm, ←direction_altitude, ←h], exact vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_singleton _)) } }, { rintro ⟨hne, h⟩, rw [←submodule.mem_inf, _root_.inf_comm, ←direction_altitude] at h, rw [vector_span_eq_span_vsub_set_left_ne ℝ (set.mem_insert _ _), set.insert_diff_of_mem _ (set.mem_singleton _), set.diff_singleton_eq_self (λ h, hne (set.mem_singleton_iff.1 h)), set.image_singleton], refine eq_of_le_of_finrank_eq _ _, { rw submodule.span_le, simpa using h }, { rw [finrank_direction_altitude, finrank_span_set_eq_card], { simp }, { refine linear_independent_singleton _, simpa using hne } } } end end simplex namespace triangle open euclidean_geometry finset simplex affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The orthocenter of a triangle is the intersection of its altitudes. It is defined here as the 2-dimensional case of the Monge point. -/ def orthocenter (t : triangle ℝ P) : P := t.monge_point /-- The orthocenter equals the Monge point. -/ lemma orthocenter_eq_monge_point (t : triangle ℝ P) : t.orthocenter = t.monge_point := rfl /-- The position of the orthocenter in relation to the circumcenter and centroid. -/ lemma orthocenter_eq_smul_vsub_vadd_circumcenter (t : triangle ℝ P) : t.orthocenter = (3 : ℝ) • ((univ : finset (fin 3)).centroid ℝ t.points -ᵥ t.circumcenter : V) +ᵥ t.circumcenter := begin rw [orthocenter_eq_monge_point, monge_point_eq_smul_vsub_vadd_circumcenter], norm_num end /-- The orthocenter lies in the affine span. -/ lemma orthocenter_mem_affine_span (t : triangle ℝ P) : t.orthocenter ∈ affine_span ℝ (set.range t.points) := t.monge_point_mem_affine_span /-- Two triangles with the same points have the same orthocenter. -/ lemma orthocenter_eq_of_range_eq {t₁ t₂ : triangle ℝ P} (h : set.range t₁.points = set.range t₂.points) : t₁.orthocenter = t₂.orthocenter := monge_point_eq_of_range_eq h /-- In the case of a triangle, altitudes are the same thing as Monge planes. -/ lemma altitude_eq_monge_plane (t : triangle ℝ P) {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : t.altitude i₁ = t.monge_plane i₂ i₃ := begin have hs : ({i₂, i₃}ᶜ : finset (fin 3)) = {i₁}, by dec_trivial!, have he : univ.erase i₁ = {i₂, i₃}, by dec_trivial!, rw [monge_plane_def, altitude_def, direction_affine_span, hs, he, centroid_singleton, coe_insert, coe_singleton, vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_insert i₂ _)], simp [h₂₃, submodule.span_insert_eq_span] end /-- The orthocenter lies in the altitudes. -/ lemma orthocenter_mem_altitude (t : triangle ℝ P) {i₁ : fin 3} : t.orthocenter ∈ t.altitude i₁ := begin obtain ⟨i₂, i₃, h₁₂, h₂₃, h₁₃⟩ : ∃ i₂ i₃, i₁ ≠ i₂ ∧ i₂ ≠ i₃ ∧ i₁ ≠ i₃, by dec_trivial!, rw [orthocenter_eq_monge_point, t.altitude_eq_monge_plane h₁₂ h₁₃ h₂₃], exact t.monge_point_mem_monge_plane end /-- The orthocenter is the only point lying in any two of the altitudes. -/ lemma eq_orthocenter_of_forall_mem_altitude {t : triangle ℝ P} {i₁ i₂ : fin 3} {p : P} (h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ t.altitude i₁) (h₂ : p ∈ t.altitude i₂) : p = t.orthocenter := begin obtain ⟨i₃, h₂₃, h₁₃⟩ : ∃ i₃, i₂ ≠ i₃ ∧ i₁ ≠ i₃, { clear h₁ h₂, dec_trivial! }, rw t.altitude_eq_monge_plane h₁₃ h₁₂ h₂₃.symm at h₁, rw t.altitude_eq_monge_plane h₂₃ h₁₂.symm h₁₃.symm at h₂, rw orthocenter_eq_monge_point, have ha : ∀ i, i₃ ≠ i → p ∈ t.monge_plane i₃ i, { intros i hi, have hi₁₂ : i₁ = i ∨ i₂ = i, { clear h₁ h₂, dec_trivial! }, cases hi₁₂, { exact hi₁₂ ▸ h₂ }, { exact hi₁₂ ▸ h₁ } }, exact eq_monge_point_of_forall_mem_monge_plane ha end /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius. -/ lemma dist_orthocenter_reflection_circumcenter (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) : dist t.orthocenter (reflection (affine_span ℝ (t.points '' {i₁, i₂})) t.circumcenter) = t.circumradius := begin rw [←mul_self_inj_of_nonneg dist_nonneg t.circumradius_nonneg, t.reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter h, t.orthocenter_eq_monge_point, monge_point_eq_affine_combination_of_points_with_circumcenter, dist_affine_combination t.points_with_circumcenter (sum_monge_point_weights_with_circumcenter _) (sum_reflection_circumcenter_weights_with_circumcenter h)], simp_rw [sum_points_with_circumcenter, pi.sub_apply, monge_point_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter], have hu : ({i₁, i₂} : finset (fin 3)) ⊆ univ := subset_univ _, obtain ⟨i₃, hi₃, hi₃₁, hi₃₂⟩ : ∃ i₃, univ \ ({i₁, i₂} : finset (fin 3)) = {i₃} ∧ i₃ ≠ i₁ ∧ i₃ ≠ i₂, by dec_trivial!, simp_rw [←sum_sdiff hu, hi₃], simp [hi₃₁, hi₃₂], norm_num end /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius, variant using a `finset`. -/ lemma dist_orthocenter_reflection_circumcenter_finset (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) : dist t.orthocenter (reflection (affine_span ℝ (t.points '' ↑({i₁, i₂} : finset (fin 3)))) t.circumcenter) = t.circumradius := by { convert dist_orthocenter_reflection_circumcenter _ h, simp } /-- The affine span of the orthocenter and a vertex is contained in the altitude. -/ lemma affine_span_orthocenter_point_le_altitude (t : triangle ℝ P) (i : fin 3) : affine_span ℝ {t.orthocenter, t.points i} ≤ t.altitude i := begin refine span_points_subset_coe_of_subset_coe _, rw [set.insert_subset, set.singleton_subset_iff], exact ⟨t.orthocenter_mem_altitude, t.mem_altitude i⟩ end /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then an altitude of `t₂` from a vertex that was not replaced is the corresponding side of `t₁`. -/ lemma altitude_replace_orthocenter_eq_affine_span {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂) (h₃ : t₂.points j₃ = t₁.points i₃) : t₂.altitude j₂ = affine_span ℝ {t₁.points i₁, t₁.points i₂} := begin symmetry, rw [←h₂, t₂.affine_span_pair_eq_altitude_iff], rw [h₂], use t₁.independent.injective.ne hi₁₂, have he : affine_span ℝ (set.range t₂.points) = affine_span ℝ (set.range t₁.points), { refine ext_of_direction_eq _ ⟨t₁.points i₃, mem_affine_span ℝ ⟨j₃, h₃⟩, mem_affine_span ℝ (set.mem_range_self _)⟩, refine eq_of_le_of_finrank_eq (direction_le (span_points_subset_coe_of_subset_coe _)) _, { have hu : (finset.univ : finset (fin 3)) = {j₁, j₂, j₃}, { clear h₁ h₂ h₃, dec_trivial! }, rw [←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton, h₁, h₂, h₃, set.insert_subset, set.insert_subset, set.singleton_subset_iff], exact ⟨t₁.orthocenter_mem_affine_span, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (set.mem_range_self _)⟩ }, { rw [direction_affine_span, direction_affine_span, t₁.independent.finrank_vector_span (fintype.card_fin _), t₂.independent.finrank_vector_span (fintype.card_fin _)] } }, rw he, use mem_affine_span ℝ (set.mem_range_self _), have hu : finset.univ.erase j₂ = {j₁, j₃}, { clear h₁ h₂ h₃, dec_trivial! }, rw [hu, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton, h₁, h₃], have hle : (t₁.altitude i₃).directionᗮ ≤ (affine_span ℝ ({t₁.orthocenter, t₁.points i₃} : set P)).directionᗮ := submodule.orthogonal_le (direction_le (affine_span_orthocenter_point_le_altitude _ _)), refine hle ((t₁.vector_span_le_altitude_direction_orthogonal i₃) _), have hui : finset.univ.erase i₃ = {i₁, i₂}, { clear hle h₂ h₃, dec_trivial! }, rw [hui, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton], refine vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_singleton _)) end /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then the orthocenter of `t₂` is the vertex of `t₁` that was replaced. -/ lemma orthocenter_replace_orthocenter_eq_point {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂) (h₃ : t₂.points j₃ = t₁.points i₃) : t₂.orthocenter = t₁.points i₁ := begin refine (triangle.eq_orthocenter_of_forall_mem_altitude hj₂₃ _ _).symm, { rw altitude_replace_orthocenter_eq_affine_span hi₁₂ hi₁₃ hi₂₃ hj₁₂ hj₁₃ hj₂₃ h₁ h₂ h₃, exact mem_affine_span ℝ (set.mem_insert _ _) }, { rw altitude_replace_orthocenter_eq_affine_span hi₁₃ hi₁₂ hi₂₃.symm hj₁₃ hj₁₂ hj₂₃.symm h₁ h₃ h₂, exact mem_affine_span ℝ (set.mem_insert _ _) } end end triangle end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Four points form an orthocentric system if they consist of the vertices of a triangle and its orthocenter. -/ def orthocentric_system (s : set P) : Prop := ∃ t : triangle ℝ P, t.orthocenter ∉ set.range t.points ∧ s = insert t.orthocenter (set.range t.points) /-- This is an auxiliary lemma giving information about the relation of two triangles in an orthocentric system; it abstracts some reasoning, with no geometric content, that is common to some other lemmas. Suppose the orthocentric system is generated by triangle `t`, and we are given three points `p` in the orthocentric system. Then either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂` and `j₃` of `t`, or `p` has the same points as `t`. -/ lemma exists_of_range_subset_orthocentric_system {t : triangle ℝ P} (ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P} (hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) : (∃ (i₁ i₂ i₃ j₂ j₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ (∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = t.orthocenter ∧ j₂ ≠ j₃ ∧ t.points j₂ = p i₂ ∧ t.points j₃ = p i₃) ∨ set.range p = set.range t.points := begin by_cases h : t.orthocenter ∈ set.range p, { left, rcases h with ⟨i₁, h₁⟩, obtain ⟨i₂, i₃, h₁₂, h₁₃, h₂₃, h₁₂₃⟩ : ∃ (i₂ i₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃, { clear h₁, dec_trivial! }, have h : ∀ i, i₁ ≠ i → ∃ (j : fin 3), t.points j = p i, { intros i hi, replace hps := set.mem_of_mem_insert_of_ne (set.mem_of_mem_of_subset (set.mem_range_self i) hps) (h₁ ▸ hpi.ne hi.symm), exact hps }, rcases h i₂ h₁₂ with ⟨j₂, h₂⟩, rcases h i₃ h₁₃ with ⟨j₃, h₃⟩, have hj₂₃ : j₂ ≠ j₃, { intro he, rw [he, h₃] at h₂, exact h₂₃.symm (hpi h₂) }, exact ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ }, { right, have hs := set.subset_diff_singleton hps h, rw set.insert_diff_self_of_not_mem ho at hs, refine set.eq_of_subset_of_card_le hs _, rw [set.card_range_of_injective hpi, set.card_range_of_injective t.independent.injective] } end /-- For any three points in an orthocentric system generated by triangle `t`, there is a point in the subspace spanned by the triangle from which the distance of all those three points equals the circumradius. -/ lemma exists_dist_eq_circumradius_of_subset_insert_orthocenter {t : triangle ℝ P} (ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P} (hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) : ∃ c ∈ affine_span ℝ (set.range t.points), ∀ p₁ ∈ set.range p, dist p₁ c = t.circumradius := begin rcases exists_of_range_subset_orthocentric_system ho hps hpi with ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs, { use [reflection (affine_span ℝ (t.points '' {j₂, j₃})) t.circumcenter, reflection_mem_of_le_of_mem (affine_span_mono ℝ (set.image_subset_range _ _)) t.circumcenter_mem_affine_span], intros p₁ hp₁, rcases hp₁ with ⟨i, rfl⟩, replace h₁₂₃ := h₁₂₃ i, repeat { cases h₁₂₃ }, { rw h₁, exact triangle.dist_orthocenter_reflection_circumcenter t hj₂₃ }, { rw [←h₂, dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert _ _)))], exact t.dist_circumcenter_eq_circumradius _ }, { rw [←h₃, dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert_of_mem _ (set.mem_singleton _))))], exact t.dist_circumcenter_eq_circumradius _ } }, { use [t.circumcenter, t.circumcenter_mem_affine_span], intros p₁ hp₁, rw hs at hp₁, rcases hp₁ with ⟨i, rfl⟩, exact t.dist_circumcenter_eq_circumradius _ } end /-- Any three points in an orthocentric system are affinely independent. -/ lemma orthocentric_system.affine_independent {s : set P} (ho : orthocentric_system s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rcases ho with ⟨t, hto, hst⟩, rw hst at hps, rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto hps hpi with ⟨c, hcs, hc⟩, exact cospherical.affine_independent ⟨c, t.circumradius, hc⟩ set.subset.rfl hpi end /-- Any three points in an orthocentric system span the same subspace as the whole orthocentric system. -/ lemma affine_span_of_orthocentric_system {s : set P} (ho : orthocentric_system s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_span ℝ (set.range p) = affine_span ℝ s := begin have ha := ho.affine_independent hps hpi, rcases ho with ⟨t, hto, hts⟩, have hs : affine_span ℝ s = affine_span ℝ (set.range t.points), { rw [hts, affine_span_insert_eq_affine_span ℝ t.orthocenter_mem_affine_span] }, refine ext_of_direction_eq _ ⟨p 0, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (hps (set.mem_range_self _))⟩, have hfd : finite_dimensional ℝ (affine_span ℝ s).direction, { rw hs, apply_instance }, haveI := hfd, refine eq_of_le_of_finrank_eq (direction_le (affine_span_mono ℝ hps)) _, rw [hs, direction_affine_span, direction_affine_span, ha.finrank_vector_span (fintype.card_fin _), t.independent.finrank_vector_span (fintype.card_fin _)] end /-- All triangles in an orthocentric system have the same circumradius. -/ lemma orthocentric_system.exists_circumradius_eq {s : set P} (ho : orthocentric_system s) : ∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r := begin rcases ho with ⟨t, hto, hts⟩, use t.circumradius, intros t₂ ht₂, have ht₂s := ht₂, rw hts at ht₂, rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto ht₂ t₂.independent.injective with ⟨c, hc, h⟩, rw set.forall_range_iff at h, have hs : set.range t.points ⊆ s, { rw hts, exact set.subset_insert _ _ }, rw [affine_span_of_orthocentric_system ⟨t, hto, hts⟩ hs t.independent.injective, ←affine_span_of_orthocentric_system ⟨t, hto, hts⟩ ht₂s t₂.independent.injective] at hc, exact (t₂.eq_circumradius_of_dist_eq hc h).symm end /-- Given any triangle in an orthocentric system, the fourth point is its orthocenter. -/ lemma orthocentric_system.eq_insert_orthocenter {s : set P} (ho : orthocentric_system s) {t : triangle ℝ P} (ht : set.range t.points ⊆ s) : s = insert t.orthocenter (set.range t.points) := begin rcases ho with ⟨t₀, ht₀o, ht₀s⟩, rw ht₀s at ht, rcases exists_of_range_subset_orthocentric_system ht₀o ht t.independent.injective with ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs, { obtain ⟨j₁, hj₁₂, hj₁₃, hj₁₂₃⟩ : ∃ j₁ : fin 3, j₁ ≠ j₂ ∧ j₁ ≠ j₃ ∧ ∀ j : fin 3, j = j₁ ∨ j = j₂ ∨ j = j₃, { clear h₂ h₃, dec_trivial! }, suffices h : t₀.points j₁ = t.orthocenter, { have hui : (set.univ : set (fin 3)) = {i₁, i₂, i₃}, { ext x, simpa using h₁₂₃ x }, have huj : (set.univ : set (fin 3)) = {j₁, j₂, j₃}, { ext x, simpa using hj₁₂₃ x }, rw [←h, ht₀s, ←set.image_univ, huj, ←set.image_univ, hui], simp_rw [set.image_insert_eq, set.image_singleton, h₁, ←h₂, ←h₃], rw set.insert_comm }, exact (triangle.orthocenter_replace_orthocenter_eq_point hj₁₂ hj₁₃ hj₂₃ h₁₂ h₁₃ h₂₃ h₁ h₂.symm h₃.symm).symm }, { rw hs, convert ht₀s using 2, exact triangle.orthocenter_eq_of_range_eq hs } end end euclidean_geometry
0b54d78e61ec35f7570fb0357976325f26699540
4727251e0cd73359b15b664c3170e5d754078599
/src/data/semiquot.lean
445adc1ef493c652ba2ee9acf90a9a62c0cfbc6d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,816
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.set.lattice /-! # Semiquotients A data type for semiquotients, which are classically equivalent to nonempty sets, but are useful for programming; the idea is that a semiquotient set `S` represents some (particular but unknown) element of `S`. This can be used to model nondeterministic functions, which return something in a range of values (represented by the predicate `S`) but are not completely determined. -/ /-- A member of `semiquot α` is classically a nonempty `set α`, and in the VM is represented by an element of `α`; the relation between these is that the VM element is required to be a member of the set `s`. The specific element of `s` that the VM computes is hidden by a quotient construction, allowing for the representation of nondeterministic functions. -/ structure {u} semiquot (α : Type*) := mk' :: (s : set α) (val : trunc ↥s) namespace semiquot variables {α : Type*} {β : Type*} instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩ /-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/ def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α := ⟨s, trunc.mk ⟨a, h⟩⟩ theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := begin refine ⟨congr_arg _, λ h, _⟩, cases q₁, cases q₂, cc, end theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ := ext_s.trans set.ext_iff theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q := let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩ theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h := ext_s.2 rfl theorem nonempty (q : semiquot α) : q.s.nonempty := q.exists_mem /-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/ protected def pure (a : α) : semiquot α := mk (set.mem_singleton a) @[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b := set.mem_singleton_iff /-- Replace `s` in a `semiquot` with a superset. -/ def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α := ⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩) (λ _ _, trunc.eq _ _) q.2⟩ /-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/ def blur (s : set α) (q : semiquot α) : semiquot α := blur' q (set.subset_union_right s q.s) theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) : blur s q = blur' q h := by unfold blur; congr; exact set.union_eq_self_of_subset_right h @[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl /-- Convert a `trunc α` to a `semiquot α`. -/ def of_trunc (q : trunc α) : semiquot α := ⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩ /-- Convert a `semiquot α` to a `trunc α`. -/ def to_trunc (q : semiquot α) : trunc α := q.2.map subtype.val /-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f` at any point of `q`. -/ def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β := trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ x.2 _ y.2) theorem lift_on_of_mem (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : lift_on q f h = f a := by revert h; rw eq_mk_of_mem aq; intro; refl /-- Apply a function to the unknown value stored in a `semiquot α`. -/ def map (f : α → β) (q : semiquot α) : semiquot β := ⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩ @[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _ /-- Apply a function returning a `semiquot` to a `semiquot`. -/ def bind (q : semiquot α) (f : α → semiquot β) : semiquot β := ⟨⋃ a ∈ q.1, (f a).1, q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩ @[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) : b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_Union₂ instance : monad semiquot := { pure := @semiquot.pure, map := @semiquot.map, bind := @semiquot.bind } @[simp] lemma map_def {β} : ((<$>) : (α → β) → semiquot α → semiquot β) = map := rfl @[simp] lemma bind_def {β} : ((>>=) : semiquot α → (α → semiquot β) → semiquot β) = bind := rfl @[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b := set.mem_singleton_iff theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) := set.mem_singleton a @[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b := ext_s.trans set.singleton_eq_singleton_iff instance : is_lawful_monad semiquot := { pure_bind := λ α β x f, ext.2 $ by simp, bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩, λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩, id_map := λ α q, ext.2 $ by simp, bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] } instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩ instance : partial_order (semiquot α) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, le_refl := λ s, set.subset.refl _, le_trans := λ s t u, set.subset.trans, le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) } instance : semilattice_sup (semiquot α) := { sup := λ s, blur s.s, le_sup_left := λ s t, set.subset_union_left _ _, le_sup_right := λ s t, set.subset_union_right _ _, sup_le := λ s t u, set.union_subset, ..semiquot.partial_order } @[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s := set.singleton_subset_iff /-- Assert that a `semiquot` contains only one possible value. -/ def is_pure (q : semiquot α) : Prop := ∀ a b ∈ q, a = b /-- Extract the value from a `is_pure` semiquotient. -/ def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h theorem get_mem {q : semiquot α} (p) : get q p ∈ q := let ⟨a, h⟩ := exists_mem q in by unfold get; rw lift_on_of_mem q _ _ a h; exact h theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) := ext.2 $ λ a, by simp; exact ⟨λ h, p _ h _ (get_mem _), λ e, e.symm ▸ get_mem _⟩ @[simp] theorem pure_is_pure (a : α) : is_pure (pure a) | b ab c ac := by { rw [mem_pure] at ab ac, cc } theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a := ⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩ theorem is_pure.mono {s t : semiquot α} (st : s ≤ t) (h : is_pure t) : is_pure s | a as b bs := h _ (st as) _ (st bs) theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t := ⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp; exact h _ (get_mem _) _ (st $ get_mem _), le_of_eq⟩ theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q | a b aq bq := subsingleton.elim _ _ /-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/ def univ [inhabited α] : semiquot α := mk $ set.mem_univ default instance [inhabited α] : inhabited (semiquot α) := ⟨univ⟩ @[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ := @set.mem_univ α @[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J := ext.2 $ by simp @[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α := ⟨λ h, ⟨λ a b, h a trivial b trivial⟩, λ ⟨h⟩ a _ b _, h a b⟩ instance [inhabited α] : order_top (semiquot α) := { top := univ, le_top := λ s, set.subset_univ _ } end semiquot
af165820203422b93272400237d979d418baf31d
54deab7025df5d2df4573383df7e1e5497b7a2c2
/order/zorn.lean
0aa8041e5906bd8edaccd174cef1ff285a71f389
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,617
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 Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import data.set.lattice noncomputable theory universes u open set classical local attribute [instance] decidable_inhabited local attribute [instance] prop_decidable namespace zorn section chain parameters {α : Type u} {r : α → α → Prop} local infix ` ≺ `:50 := r def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) def super_chain (c₁ c₂ : set α) := chain c₂ ∧ c₁ ⊂ c₂ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') def succ_chain (c : set α) := if h : ∃c', chain c ∧ super_chain c c' then some h else c theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_iff, not_not_iff] at hc₂, exact have ∃c', super_chain c c', from hc₂.neg_resolve_left hc₁, let ⟨c', hc'⟩ := this in show super_chain c (succ_chain c), from succ_spec ⟨c', hc₁, hc'⟩ end theorem succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) theorem chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case _root_.zorn.chain_closure.succ c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case _root_.zorn.chain_closure.union s hs ih { refine (or_of_not_implies' $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case _root_.zorn.chain_closure.succ c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case _root_.zorn.chain_closure.union s hs ih { apply or.imp (assume h', subset.antisymm h' h) id, apply classical.by_contradiction, simp [not_or_iff, sUnion_subset_iff, classical.not_forall_iff, not_implies_iff], intro h, cases h with h₁ h₂, cases h₂ with c₃ h₂, cases h₂ with h₂ hc₃, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₂ $ h' ▸ subset.refl _) }, { exact (h₁ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₂ $ subset.trans succ_increasing h) } } end theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case _root_.zorn.chain_closure.succ c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case _root_.zorn.chain_closure.union s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ theorem chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case _root_.zorn.chain_closure.succ c hc h { exact chain_succ h }, case _root_.zorn.chain_closure.union s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ chain_closure), have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := this in have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ theorem zorn (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @zorn α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ end zorn
092db558379928f520f055bd640a79f8c685f252
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/limits/has_limits.lean
7f2cfbcdbe8bbb29106572188ea512182fdbe70d
[ "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
39,095
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.limits.is_limit /-! # Existence of limits and colimits In `category_theory.limits.is_limit` we defined `is_limit c`, the data showing that a cone `c` is a limit cone. The two main structures defined in this file are: * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits -- morphism levels before object levels. See note [category_theory universes]. universes v u u' u'' w variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} section limit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ @[nolint has_inhabited_instance] structure limit_cone (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit (F : J ⥤ C) : Prop := mk' :: (exists_limit : nonempty (limit_cone F)) lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F := classical.choice $ has_limit.exists_limit variables (J C) /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape : Prop := (has_limit : Π F : J ⥤ C, has_limit F . tactic.apply_instance) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits : Prop := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C . tactic.apply_instance) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone /-- An arbitrary choice of limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] : (limit.cone F).X = limit F := rfl @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] : (limit.cone F).π.app = limit.π _ := rfl @[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := (get_limit_cone F).is_limit /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map _ (limit.is_limit G) α @[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j := limit.lift_π _ j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ limit.cone F := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _ @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _ /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ t.cone.X := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit @[simp, reassoc] lemma limit.iso_limit_cone_hom_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma limit.iso_limit_cone_inv_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w @[simp] lemma limit.lift_map {F G : J ⥤ C} [has_limit F] [has_limit G] (c : cone F) (α : F ⟶ G) : limit.lift F c ≫ lim_map α = limit.lift G ((cones.postcompose α).obj c) := by { ext, rw [assoc, lim_map_π, limit.lift_π_assoc, limit.lift_π], refl } @[simp] lemma limit.lift_cone {F : J ⥤ C} [has_limit F] : limit.lift F (limit.cone F) = 𝟙 (limit F) := (limit.is_limit _).lift_self /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. lemma has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp, reassoc] lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : (has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j := is_limit.cone_points_iso_of_nat_iso_hom_comp _ _ _ _ @[simp, reassoc] lemma has_limit.lift_iso_of_nat_iso_hom {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F) (w : F ≅ G) : limit.lift F t ≫ (has_limit.iso_of_nat_iso w).hom = limit.lift G ((cones.postcompose w.hom).obj _) := is_limit.lift_comp_cone_points_iso_of_nat_iso_hom _ _ _ /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : (has_limit.iso_of_equivalence e w).hom ≫ limit.π G k = limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end @[simp] lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : (has_limit.iso_of_equivalence e w).inv ≫ limit.π F j = limit.π G (e.functor.obj j) ≫ w.hom.app j := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) ((limit.cone F).whisker E) @[simp, reassoc] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl variables {E F} /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = (limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫ (limit.iso_limit_cone s).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (G.map_cone (limit.cone F)) @[simp, reassoc] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl } @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := has_limit.mk { cone := cone.whisker e.functor (limit.cone F), is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] section /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ @[simps obj] def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, lim_map α, map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } end variables {F} {G : J ⥤ C} (α : F ⟶ G) -- We generate this manually since `simps` gives it a weird name. @[simp] lemma lim_map_eq_lim_map : lim.map α = lim_map α := rfl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by { ext, simp } lemma limit.map_pre' [has_limits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim_map α) ≫ limit.post G H = limit.post F H ≫ lim_map (whisker_right α H) := begin ext, simp only [whisker_right_app, lim_map_π, assoc, limit.post_π_assoc, limit.post_π, ← H.map_comp], end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ @[nolint has_inhabited_instance] structure colimit_cocone (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit (F : J ⥤ C) : Prop := mk' :: (exists_colimit : nonempty (colimit_cocone F)) lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F := classical.choice $ has_colimit.exists_colimit variables (J C) /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape : Prop := (has_colimit : Π F : J ⥤ C, has_colimit F . tactic.apply_instance) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits : Prop := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C . tactic.apply_instance) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone /-- An arbitrary choice of colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] : (colimit.cocone F).X = colimit F := rfl @[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := (get_colimit_cocone F).is_colimit /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) _ α @[simp, reassoc] lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) : colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j := colimit.ι_desc _ j /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _ @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _ /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ t.cocone.X := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w @[simp] lemma colimit.desc_cocone {F : J ⥤ C} [has_colimit F] : colimit.desc F (colimit.cocone F) = 𝟙 (colimit F) := (colimit.is_colimit _).desc_self /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ lemma has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := has_colimit.mk ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j := is_colimit.comp_cocone_points_iso_of_nat_iso_hom _ _ _ _ @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_hom_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G] (t : cocone G) (w : F ≅ G) : (has_colimit.iso_of_nat_iso w).hom ≫ colimit.desc G t = colimit.desc F ((cocones.precompose w.hom).obj _) := is_colimit.cocone_points_iso_of_nat_iso_hom_desc _ _ _ /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom = F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end @[simp] lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv = G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E) @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end variables {E F} /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = (colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫ (colimit.iso_colimit_cocone t).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F)) @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl } @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, } /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] section local attribute [simp] colim_map /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ @[simps obj] def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colim_map α, map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] }, map_comp' := λ F G H α β, by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit section opposite /-- If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone. -/ def is_limit.op {t : cone F} (P : is_limit t) : is_colimit t.op := { desc := λ s, (P.lift s.unop).op, fac' := λ s j, congr_arg has_hom.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone. -/ def is_colimit.op {t : cocone F} (P : is_colimit t) : is_limit t.op := { lift := λ s, (P.desc s.unop).op, fac' := λ s j, congr_arg has_hom.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone. -/ def is_limit.unop {t : cone F.op} (P : is_limit t) : is_colimit t.unop := { desc := λ s, (P.lift s.op).unop, fac' := λ s j, congr_arg has_hom.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone. -/ def is_colimit.unop {t : cocone F.op} (P : is_colimit t) : is_limit t.unop := { lift := λ s, (P.desc s.op).unop, fac' := λ s j, congr_arg has_hom.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- `t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {t : cone F} : is_limit t ≃ is_colimit t.op := equiv_of_subsingleton_of_subsingleton is_limit.op (λ P, P.unop.of_iso_limit (cones.ext (iso.refl _) (by tidy))) /-- `t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone. -/ def is_colimit_equiv_is_limit_op {t : cocone F} : is_colimit t ≃ is_limit t.op := equiv_of_subsingleton_of_subsingleton is_colimit.op (λ P, P.unop.of_iso_colimit (cocones.ext (iso.refl _) (by tidy))) end opposite end category_theory.limits
26d59ad048a7acc1f2693a6f5c43d0257397351a
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/control/monad.lean
0093387bb2ae35a70355d271b300bc4d0a85e788
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
990
lean
import util.control.applicative universes u v variable {m : Type u → Type v} variable [monad m] variables {α β γ : Type u} open functor nat namespace monad lemma map_bind (f : γ → β) (x : m α) (g : α → m γ) : f <$> (x >>= g) = x >>= (map f ∘ g) := sorry lemma bind_map (f : α → β) (x : m α) (g : β → m γ) : f <$> x >>= g = x >>= g ∘ f := sorry def mmap₂ (f : α → β → m γ) : list α → list β → m (list γ) | (x :: xs) (y :: ys) := (::) <$> f x y <*> mmap₂ xs ys | [] _ := pure [] | _ [] := pure [] def mmap₂' (f : α → β → m γ) : list α → list β → m punit | (x :: xs) (y :: ys) := f x y *> mmap₂' xs ys | [] _ := pure punit.star | _ [] := pure punit.star end monad open applicative def monad.mrepeat : ℕ → m α → m (list α) | 0 _ := return [] | (succ n) m := lift₂ (::) m (monad.mrepeat n m) def monad.mrepeat' : ℕ → m α → m punit | 0 _ := return punit.star | (succ n) m := m *> monad.mrepeat' n m
37447e6c19d2a6e17d5ea4a5f1bff71722154e47
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/limits/L01defs.lean
bbec198320f02dfac906f7888a5f39950b492bcc
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,443
lean
import game.sets.L01defs --NOTE: the recursive import from previous world breaks run_cmd add_interactive below?? --I think the problem comes from sup_inf.rat_complete --So I will import sup_inf in the next level import data.real.basic import tactic.linarith namespace xena -- hide notation `|` x `|` := abs x -- hide lemma zero_of_abs_lt_all (x : ℝ) (h : ∀ ε > 0, |x| < ε) : x = 0 := eq_zero_of_abs_eq_zero $ eq_of_le_of_forall_le_of_dense (abs_nonneg x) $ λ ε ε_pos, le_of_lt (h ε ε_pos) -- begin hide -- The next few things should be hidden @[user_attribute] meta def ineq_rules : user_attribute := { name := `ineq_rules, descr := "lemmas usable to prove inequalities" } attribute [ineq_rules] add_lt_add le_max_left le_max_right meta def inequality := `[linarith <|> apply_rules ineq_rules] run_cmd add_interactive [`inequality] -- end of scary things -- end hide -- World name : Sequences and limits /- # Chapter 3 : Sequences and limits # Level 1 : Introduction to sequences. Lean's natural numbers start at zero, so it is convenient to let our sequences start from the zeroth term. In other words, a sequence of reals will be $a_0, a_1, a_2, \ldots$. -/ /- Let's just step back for a minute and think about what a sequence really *is*. If $n$ is a natural number then $a_n$ is a real number, so $n\mapsto a_n$ is actually a function from natural numbers to real numbers. If we just call this function $a$ then the $n$th term in the sequence will be called `a(n)` or `a n` in Lean, rather than $a_n$, but this is OK. The key definition we want is the concept of a limit of a sequence. -/ definition is_limit (a : ℕ → ℝ) (α : ℝ) := ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → |a n - α| < ε /- Let's now prove the basic fact that a sequence has at most one limit. -/ /- Lemma If $a_n \to \ell$ and $a_n \to m$ then $\ell = m$. -/ lemma limit.unique (a : ℕ → ℝ) (l m : ℝ) (hl : is_limit a l) (hm : is_limit a m) : l = m := begin wlog h : l ≤ m, rw le_iff_lt_or_eq at h, cases h, exfalso, generalize h : (m - l) / 2 = ε, have hε : 0 < ε, {inequality}, cases (hl ε hε) with L hL, cases (hm ε hε) with M hM, have hL' := hL (max L M) (le_max_left _ _), have hM' := hM (max L M) (le_max_right _ _), rw abs_lt at hL', rw abs_lt at hM', cases hL', cases hM', linarith, assumption, end end xena -- hide
2ee305b4f97dbe6bd766ffb8637a7e7945d6918f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monad/bundled_auto.lean
355322c3f4c2a8c99b0f3da9511823955ae9c632
[]
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,634
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monad.basic import Mathlib.category_theory.eq_to_hom import Mathlib.PostPort universes v u l namespace Mathlib /-! # Bundled Monads We define bundled (co)monads as a structure consisting of a functor `func : C ⥤ C` endowed with a term of type `(co)monad func`. See `category_theory.monad.basic` for the definition. The type of bundled (co)monads on a category `C` is denoted `(Co)Monad C`. We also define morphisms of bundled (co)monads as morphisms of their underlying (co)monads in the sense of `category_theory.(co)monad_hom`. We construct a category instance on `(Co)Monad C`. -/ namespace category_theory /-- Bundled monads. -/ structure Monad (C : Type u) [category C] where func : C ⥤ C str : autoParam (monad func) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) /-- Bundled comonads -/ structure Comonad (C : Type u) [category C] where func : C ⥤ C str : autoParam (comonad func) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) namespace Monad /-- The initial monad. TODO: Prove it's initial. -/ def initial (C : Type u) [category C] : Monad C := mk 𝟭 protected instance inhabited {C : Type u} [category C] : Inhabited (Monad C) := { default := initial C } protected instance func.category_theory.monad {C : Type u} [category C] {M : Monad C} : monad (func M) := str M /-- Morphisms of bundled monads. -/ def hom {C : Type u} [category C] (M : Monad C) (N : Monad C) := monad_hom (func M) (func N) namespace hom end hom protected instance hom.inhabited {C : Type u} [category C] {M : Monad C} : Inhabited (hom M M) := { default := monad_hom.id (func M) } protected instance category_theory.category {C : Type u} [category C] : category (Monad C) := category.mk /-- The forgetful functor from `Monad C` to `C ⥤ C`. -/ def forget (C : Type u) [category C] : Monad C ⥤ C ⥤ C := functor.mk func fun (_x _x_1 : Monad C) (f : _x ⟶ _x_1) => monad_hom.to_nat_trans f @[simp] theorem comp_to_nat_trans {C : Type u} [category C] {M : Monad C} {N : Monad C} {L : Monad C} (f : M ⟶ N) (g : N ⟶ L) : monad_hom.to_nat_trans (f ≫ g) = nat_trans.vcomp (monad_hom.to_nat_trans f) (monad_hom.to_nat_trans g) := rfl @[simp] theorem assoc_func_app {C : Type u} [category C] {M : Monad C} {X : C} : functor.map (func M) (nat_trans.app μ_ X) ≫ nat_trans.app μ_ X = nat_trans.app μ_ (functor.obj (func M) X) ≫ nat_trans.app μ_ X := monad.assoc X end Monad namespace Comonad /-- The terminal comonad. TODO: Prove it's terminal. -/ def terminal (C : Type u) [category C] : Comonad C := mk 𝟭 protected instance inhabited {C : Type u} [category C] : Inhabited (Comonad C) := { default := terminal C } protected instance func.category_theory.comonad {C : Type u} [category C] {M : Comonad C} : comonad (func M) := str M /-- Morphisms of bundled comonads. -/ def hom {C : Type u} [category C] (M : Comonad C) (N : Comonad C) := comonad_hom (func M) (func N) namespace hom end hom protected instance hom.inhabited {C : Type u} [category C] {M : Comonad C} : Inhabited (hom M M) := { default := comonad_hom.id (func M) } protected instance category_theory.category {C : Type u} [category C] : category (Comonad C) := category.mk /-- The forgetful functor from `CoMonad C` to `C ⥤ C`. -/ def forget (C : Type u) [category C] : Comonad C ⥤ C ⥤ C := functor.mk func fun (_x _x_1 : Comonad C) (f : _x ⟶ _x_1) => comonad_hom.to_nat_trans f @[simp] theorem comp_to_nat_trans {C : Type u} [category C] {M : Comonad C} {N : Comonad C} {L : Comonad C} (f : M ⟶ N) (g : N ⟶ L) : comonad_hom.to_nat_trans (f ≫ g) = nat_trans.vcomp (comonad_hom.to_nat_trans f) (comonad_hom.to_nat_trans g) := rfl @[simp] theorem coassoc_func_app {C : Type u} [category C] {M : Comonad C} {X : C} : nat_trans.app δ_ X ≫ functor.map (func M) (nat_trans.app δ_ X) = nat_trans.app δ_ X ≫ nat_trans.app δ_ (functor.obj (func M) X) := comonad.coassoc X end Mathlib
82dfbd8cb9498a4e1dd99c39ff80f60f019e95dd
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/locally_convex/abs_convex.lean
5377b4e2ad37654c1a71c84f049efdc50150ce3a
[ "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
6,180
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.locally_convex.balanced_core_hull import analysis.locally_convex.with_seminorms import analysis.convex.gauge /-! # Absolutely convex sets A set is called absolutely convex or disked if it is convex and balanced. The importance of absolutely convex sets comes from the fact that every locally convex topological vector space has a basis consisting of absolutely convex sets. ## Main definitions * `gauge_seminorm_family`: the seminorm family induced by all open absolutely convex neighborhoods of zero. ## Main statements * `with_gauge_seminorm_family`: the topology of a locally convex space is induced by the family `gauge_seminorm_family`. ## Todo * Define the disked hull ## Tags disks, convex, balanced -/ open normed_field set open_locale big_operators nnreal pointwise topological_space variables {𝕜 E F G ι : Type*} section nontrivially_normed_field variables (𝕜 E) {s : set E} variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [module ℝ E] [smul_comm_class ℝ 𝕜 E] variables [topological_space E] [locally_convex_space ℝ E] [has_continuous_smul 𝕜 E] lemma nhds_basis_abs_convex : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ 𝓝 (0 : E) ∧ balanced 𝕜 s ∧ convex ℝ s) id := begin refine (locally_convex_space.convex_basis_zero ℝ E).to_has_basis (λ s hs, _) (λ s hs, ⟨s, ⟨hs.1, hs.2.2⟩, rfl.subset⟩), refine ⟨convex_hull ℝ (balanced_core 𝕜 s), _, convex_hull_min (balanced_core_subset s) hs.2⟩, refine ⟨filter.mem_of_superset (balanced_core_mem_nhds_zero hs.1) (subset_convex_hull ℝ _), _⟩, refine ⟨balanced_convex_hull_of_balanced (balanced_core_balanced s), _⟩, exact convex_convex_hull ℝ (balanced_core 𝕜 s), end variables [has_continuous_smul ℝ E] [topological_add_group E] lemma nhds_basis_abs_convex_open : (𝓝 (0 : E)).has_basis (λ (s : set E), (0 : E) ∈ s ∧ is_open s ∧ balanced 𝕜 s ∧ convex ℝ s) id := begin refine (nhds_basis_abs_convex 𝕜 E).to_has_basis _ _, { rintros s ⟨hs_nhds, hs_balanced, hs_convex⟩, refine ⟨interior s, _, interior_subset⟩, exact ⟨mem_interior_iff_mem_nhds.mpr hs_nhds, is_open_interior, hs_balanced.interior (mem_interior_iff_mem_nhds.mpr hs_nhds), hs_convex.interior⟩ }, rintros s ⟨hs_zero, hs_open, hs_balanced, hs_convex⟩, exact ⟨s, ⟨hs_open.mem_nhds hs_zero, hs_balanced, hs_convex⟩, rfl.subset⟩, end end nontrivially_normed_field section absolutely_convex_sets variables [topological_space E] [add_comm_monoid E] [has_zero E] [semi_normed_ring 𝕜] variables [has_smul 𝕜 E] [has_smul ℝ E] variables (𝕜 E) /-- The type of absolutely convex open sets. -/ def abs_convex_open_sets := { s : set E // (0 : E) ∈ s ∧ is_open s ∧ balanced 𝕜 s ∧ convex ℝ s } instance abs_convex_open_sets.has_coe : has_coe (abs_convex_open_sets 𝕜 E) (set E) := ⟨subtype.val⟩ namespace abs_convex_open_sets variables {𝕜 E} lemma coe_zero_mem (s : abs_convex_open_sets 𝕜 E) : (0 : E) ∈ (s : set E) := s.2.1 lemma coe_is_open (s : abs_convex_open_sets 𝕜 E) : is_open (s : set E) := s.2.2.1 lemma coe_nhds (s : abs_convex_open_sets 𝕜 E) : (s : set E) ∈ 𝓝 (0 : E) := s.coe_is_open.mem_nhds s.coe_zero_mem lemma coe_balanced (s : abs_convex_open_sets 𝕜 E) : balanced 𝕜 (s : set E) := s.2.2.2.1 lemma coe_convex (s : abs_convex_open_sets 𝕜 E) : convex ℝ (s : set E) := s.2.2.2.2 end abs_convex_open_sets instance : nonempty (abs_convex_open_sets 𝕜 E) := begin rw ←exists_true_iff_nonempty, dunfold abs_convex_open_sets, rw subtype.exists, exact ⟨set.univ, ⟨mem_univ 0, is_open_univ, balanced_univ, convex_univ⟩, trivial⟩, end end absolutely_convex_sets variables [is_R_or_C 𝕜] variables [add_comm_group E] [topological_space E] variables [module 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E] variables [has_continuous_smul ℝ E] variables (𝕜 E) /-- The family of seminorms defined by the gauges of absolute convex open sets. -/ noncomputable def gauge_seminorm_family : seminorm_family 𝕜 E (abs_convex_open_sets 𝕜 E) := λ s, gauge_seminorm s.coe_balanced s.coe_convex (absorbent_nhds_zero s.coe_nhds) variables {𝕜 E} lemma gauge_seminorm_family_ball (s : abs_convex_open_sets 𝕜 E) : (gauge_seminorm_family 𝕜 E s).ball 0 1 = (s : set E) := begin dunfold gauge_seminorm_family, rw seminorm.ball_zero_eq, simp_rw gauge_seminorm_to_fun, exact gauge_lt_one_eq_self_of_open s.coe_convex s.coe_zero_mem s.coe_is_open, end variables [topological_add_group E] [has_continuous_smul 𝕜 E] variables [smul_comm_class ℝ 𝕜 E] [locally_convex_space ℝ E] /-- The topology of a locally convex space is induced by the gauge seminorm family. -/ lemma with_gauge_seminorm_family : with_seminorms (gauge_seminorm_family 𝕜 E) := begin refine seminorm_family.with_seminorms_of_has_basis _ _, refine (nhds_basis_abs_convex_open 𝕜 E).to_has_basis (λ s hs, _) (λ s hs, _), { refine ⟨s, ⟨_, rfl.subset⟩⟩, convert (gauge_seminorm_family _ _).basis_sets_singleton_mem ⟨s, hs⟩ one_pos, rw [gauge_seminorm_family_ball, subtype.coe_mk] }, refine ⟨s, ⟨_, rfl.subset⟩⟩, rw seminorm_family.basis_sets_iff at hs, rcases hs with ⟨t, r, hr, rfl⟩, rw [seminorm.ball_finset_sup_eq_Inter _ _ _ hr], -- We have to show that the intersection contains zero, is open, balanced, and convex refine ⟨mem_Inter₂.mpr (λ _ _, by simp [seminorm.mem_ball_zero, hr]), is_open_bInter (to_finite _) (λ S _, _), balanced_Inter₂ (λ _ _, seminorm.balanced_ball_zero _ _), convex_Inter₂ (λ _ _, seminorm.convex_ball _ _ _)⟩, -- The only nontrivial part is to show that the ball is open have hr' : r = ‖(r : 𝕜)‖ * 1 := by simp [abs_of_pos hr], have hr'' : (r : 𝕜) ≠ 0 := by simp [hr.ne'], rw [hr', ← seminorm.smul_ball_zero hr'', gauge_seminorm_family_ball], exact S.coe_is_open.smul₀ hr'' end
fc0b2d3ab8b679cf357367047e7ee65911db3312
d320d01276642370017b4ce56793b5f73e0016f9
/lean projects and notes/hw7_sa3tnc.lean
5feebdf6fe4a89146cd2ec861b2e7eabbd93ba3c
[]
no_license
samiazam00/my-work
388d815ddc7e47860375959ba31be2530be7f11e
e9a8218b2441dce00bf117d3d985d00e6ee14ec0
refs/heads/master
1,608,518,076,248
1,580,268,523,000
1,580,268,523,000
236,280,156
0
0
null
null
null
null
UTF-8
Lean
false
false
7,746
lean
--Samreen Azam (sa3tnc) import .prop_logic import .bool_sat open prop_logic open prop_logic.var open prop_logic.pExp /- An example: The 0th, 1st, and 2nd bits from the right in 100, the binary numeral for decimal 4, are 0, 0, and 1, respectively. -/ #eval mth_bit_from_right_in_n 2 4 /- #1. Write and evaluate expressions (using eval) to determine what is the bit in the 9th position from the right in the binary expansion of the decimal number 8485672345? Hint: don't use reduce here. Eval uses hardware (machine) int values to represent nats, while reduce uses the unary nat representation. Self-test: How much memory might it take to represent the decimal number, 8485672345, as a ℕ value in unary? -/ #eval mth_bit_from_right_in_n 9 8485672345 /- The next section presents examples to set up test cases for definitions to follow. -/ /- We define a few variables to use in the rest of this assignment. -/ def P : pExp:= varExp (mkVar 0) def Q: pExp := varExp (mkVar 1) def R : pExp := varExp (mkVar 2) /- We set parameter values used in some function definitions to follow. -/ def max_var_index := 2 def num_vars := max_var_index + 1 /- An example of a propositional logic expression. -/ def theExpr : pExp := (P ⇒ (P ∧ R)) /- An example using the truth_table_results function to compute and return a list of the truth values of theExpr under each of its possible interpretations. -/ #eval truth_table_results theExpr num_vars /- #2. Define interp5 to be the interpretation in the six row (m=5) of the truth table that our interps_for_n_vars functions returns for our three variables (P, Q, and R). Hint: use the mth_interp_n_vars function. Definitely check out the definition of the function, and any specification text, even if informal, given with the formal definition. -/ def interp5 := mth_interp_n_vars 5 (num_vars) /- #3. What Boolean values are assigned to P, Q, and R by this interpretation (interp5)? Use three #eval commands to compute answers by evaluating each variable expressions under the interp5 interpretation. -/ def varList := interps_for_n_vars num_vars #eval truth_table_results P 5 #eval truth_table_results Q 5 #eval truth_table_results R 5 #check varList /- #4. Write a truth table within this comment block showing the values for P, Q, and R, in each row in the truth table, represented by a corresponding valule in the list of interpretations returned by interps_for_n_vars. Label your columns as R, Q, and P, in that order. (Try to understand why.) Hint: Don't just write what you think the answers are:, evaluate each of the three variable expression under each interpretation. You can use the mth_interp_n_vars function if you want to obtain interpretation functions for each of the rows individually if you want. Answer: R Q P interps_for_n_vars - - - ------------------- 1 1 1 0 1 0 0 1 0 1 1 1 0 0 0 1 1 1 0 1 1 0 1 1 0 1 0 1 0 0 1 1 -/ #eval interps_for_n_vars num_vars #eval mth_interp_n_vars 0 3 /- #5. Write an expression here to compute the "results" column of the truth table for "theExpr" as defined above. -/ #eval truth_table_results theExpr /- #6. Copy and paste the truth table from question #4 here and extend it with the results you just obtained. Check the results for correctness. Answer here: R Q P interps_for_n_vars theExpr - - - ------------------- ------- 1 1 1 0 1 1 0 0 1 1 0 1 1 1 0 0 0 0 1 1 1 1 0 1 1 1 0 1 1 1 0 1 0 1 1 0 0 1 1 0 reminder that theExpr is (P ⇒ (P ∧ R)) -/ /- #7. Write a "predicate" function, isModel, that takes a propositional logic expression, e, and an interpretation, i, as its arguments and that returns the Boolean true (tt) value if and only if i is a model of e (otherwise false). -/ def isModel :pExp → (var → bool) → bool := if() /- #7. Write a one-line implementation of a function, is_valid, that takes as its arguments a propositional expression, e, and the number of variables, n, in its truth table, and that returns true if and only if it is valid, construed to mean tha every result in the list returned by the truth_table_results function is true. To do so, define and use a fold function to reduce returned lists of Boolean truth values to single truth values. Define and use a bool-specific function, fold_bool : (bool → bool → bool) → bool → (list bool) → bool, where the arguments are, respectively, a binary operator, an identity element for that operator, and a list of bools to be reduced to a single bool result. -/ def fold_bool : (bool → bool → bool) → bool → (list bool) → bool | f id nil := id | f id (cons h t) := f h (fold_bool f id t) def is_valid : pExp → ℕ → bool |e n := (fold_bool (band) (bit_to_bool n) (truth_table_results e n)) /- Write similar one-line implementations of the functions, is_satisfiable and is_unsatisfiable, respectively. Do not use fold (directly) in your implementation of is_unsatisfiable. -/ def is_satisfiable : pExp → ℕ → bool |e n := (fold_bool (bor) (bit_to_bool n) (truth_table_results e n)) def is_unsatisfiable : pExp → ℕ → bool |e n := bnot((fold_bool (bor) (bit_to_bool n) (truth_table_results e n))) /- 8. Use your is_valid function to determine which of the following putative valid laws of reasoning really are valid, and which ones are not. For each one that is not, give a real-world scenario that shows that the rule doesn't always lead to a valid deduction. Use #eval to evaluate the validity of each proposition. Use -- to put a comment after each of the following definitions indicating either "-- valid" or "-- NOT valid". -/ def true_intro : pExp := pTrue def false_elim := pFalse ⇒ P def and_intro := P ⇒ Q ⇒ (P ∧ Q) def and_elim_left := (P ∧ Q) ⇒ P def and_elim_right := (P ∧ Q) ⇒ Q def or_intro_left := P ⇒ (P ∨ Q) def or_intro_right := Q ⇒ (P ∨ Q) def or_elim := (P ∨ Q) ⇒ (P ⇒ R) ⇒ (Q ⇒ R) ⇒ R def iff_intro := (P ⇒ Q) ⇒ (Q ⇒ P) ⇒ (P ↔ Q) def iff_elim_left := (P ↔ Q) ⇒ (P ⇒ Q) def iff_elim_right := (P ↔ Q) ⇒ (Q ⇒ P) def arrow_elim := (P ⇒ Q) ⇒ P ⇒ Q def affirm_consequence := (P ⇒ Q) ⇒ Q ⇒ P def resolution := (P ∨ Q) ⇒ (¬ Q ∨ R) ⇒ (P ∨ R) def unit_resolution := (P ∨ Q) ⇒ (¬ Q) ⇒ P def syllogism := (P ⇒ Q) ⇒ (Q ⇒ R) ⇒ (P ⇒ R) def modus_tollens := (P ⇒ Q) ⇒ ¬ Q ⇒ ¬ P def neg_elim := ¬ ¬ P ⇒ P def excluded_middle := P ∨ ¬ P def neg_intro := (P ⇒ pFalse) ⇒ ¬ P def affirm_disjunct := (P ∨ Q) ⇒ P ⇒ ¬ Q def deny_antecedent := (P ⇒ Q) ⇒ (¬ P ⇒ ¬ Q) -- Answer below #eval true_intro --valid #eval false_elim --not valid #eval and_intro --not valid #eval and_elim_left #eval and_elim_right --valid #eval or_intro_left #eval or_intro_right #eval or_elim #eval iff_intro #eval iff_elim_left #eval iff_elim_right #eval arrow_elim #eval affirm_consequence #eval resolution #eval unit_resolution #eval syllogism #eval modus_tollens #eval neg_elim #eval excluded_middle #eval neg_intro #eval affirm_disjunct #eval deny_antecedent
3969fd750328639ea8379dde98493a7972cacd8f
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/typed_smt2/src/galois/smt2/test.lean
9b6be3f425f053c26a9b3f37b745f86ee52ecc6e
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
2,942
lean
import system.io import .file_writer import .semantics import .theories.bv section quantifiers variables {α : Sort*} {p q : α → Prop} {b : Prop} @[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib end quantifiers open smt2 /- Generte a proble mtaht asserts a constant x is equal to 3. -/ def generate_problem {m} [is_generator m ] : m unit := do let x := symbol.of_string "x", declare_const x (BitVec 32), assert (all_equal [var x (BitVec 32), bv.decimal (bitvec.of_nat 32 3)]), check_sat /- This actually generates the SMTLIB file. -/ def main : io unit := do smt2.file_writer.run "bar.smt2" $ do generate_problem /- This will either report an error because the problem is not well-formed, or return the property implied by the program. -/ def mkprop : except string Prop := semantics.run_and_collect_unsat generate_problem /- This is a hack to show that mkprop can be evaluated into a simpler proof. -/ example : mkprop = except.ok (¬∃(x : bitvec 32), x = bitvec.of_nat 32 3) := begin simp only [ mkprop , semantics.run_and_collect_unsat , id , generate_problem , declare_const , is_generator.declare_const , semantics.context.initial , semantics.declare_fun , semantics.register_symbol , semantics.context.add_binding , smt2.assert, is_generator.assert, semantics.assert , all_equal , check_sat, is_generator.check_sat, semantics.check_sat , semantics.check_sat_assuming , semantics.quantify_bindings , semantics.quantify_binding , pure, has_bind.bind , except.return , except.bind , except.map_poly , put , pwhen , mk_rbmap, mk_rbtree , has_mem.mem, rbmap.mem , get , state_t.pure, modify, state_t.modify, state_t.bind, state_t.get, state_t.put , monad_state.lift , list.forall_prop , list.reverse_core , interpretation.bind , apply_chainable , all_band , smt2.var , interpretation.lookup_var , rbmap.insert, rbtree.insert , has_emptyc.emptyc , interpretation.empty , rbmap.find , rbmap.find_entry , rbnode.find , rbnode.insert , rbnode.ins , rbnode.get_color , rbnode.mk_insert_result , rbtree.find , cmp_using, rbmap_lt , symbol.lt , symbol.of_string , except.is_ok.value , string.to_char_buffer , buffer.append_string , buffer.nil , rbmap.to_value , bv.decimal , if_false , list.map , dif_pos , band_tt , and_true , not_exists , coe_sort , to_bool_iff , cast ], exact rfl, end
b1c92b1d21f92f715f115d0019966256c936c260
f09e92753b1d3d2eb3ce2cfb5288a7f5d1d4bd89
/src/for_mathlib/topology.lean
74f41c4c6c2e2c2c38007c6c0c1e9cb87c747fb1
[ "Apache-2.0" ]
permissive
PatrickMassot/lean-perfectoid-spaces
7f63c581db26461b5a92d968e7563247e96a5597
5f70b2020b3c6d508431192b18457fa988afa50d
refs/heads/master
1,625,797,721,782
1,547,308,357,000
1,547,309,364,000
136,658,414
0
1
Apache-2.0
1,528,486,100,000
1,528,486,100,000
null
UTF-8
Lean
false
false
1,053
lean
import analysis.topology.topological_space import analysis.topology.uniform_space section opens variables (X : Type*) [topological_space X] include X @[class] def opens := {U : set X // is_open U} instance : has_coe (opens X) (set X) := ⟨λU, U.1⟩ instance : has_mem X (opens X) := ⟨λx U, x ∈ U.1⟩ instance : has_inter (opens X) := ⟨λ U V, ⟨U.1 ∩ V.1, is_open_inter U.2 V.2⟩⟩ instance : has_union (opens X) := ⟨λ U V, ⟨U.1 ∪ V.1, is_open_union U.2 V.2⟩⟩ instance : has_emptyc (opens X) := ⟨⟨∅, is_open_empty⟩⟩ end opens -- peredicates we need for topological rings -- We need to think whether we could directly use the class t2_space (which is not using opens though) definition is_hausdorff (α : Type*) [topological_space α] : Prop := ∀ x y, x ≠ y → ∃ u v : opens α, x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ -- Wedhorn Definition 5.31 page 38 definition is_complete_hausdorff (α : Type*) [uniform_space α] := is_hausdorff α ∧ ∀ {f : filter α}, cauchy f → ∃ x, f ≤ nhds x
ab86a7d7e1c9b1e638828e9b5bc32b3db01c7e0d
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/category/Module/abelian.lean
c442e1b8e89118262e2eb138a1869d62122629ed
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,288
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 linear_algebra.isomorphisms import algebra.category.Module.kernels import algebra.category.Module.limits import category_theory.abelian.exact /-! # The category of left R-modules is abelian. Additionally, two linear maps are exact in the categorical sense iff `range f = ker g`. -/ open category_theory open category_theory.limits noncomputable theory universes v u namespace Module variables {R : Type u} [ring R] {M N : Module.{v} R} (f : M ⟶ N) /-- In the category of modules, every monomorphism is normal. -/ def normal_mono (hf : mono f) : normal_mono f := { Z := of R f.range.quotient, g := f.range.mkq, w := linear_map.range_mkq_comp _, is_limit := is_kernel.iso_kernel _ _ (kernel_is_limit _) /- The following [invalid Lean code](https://github.com/leanprover-community/lean/issues/341) might help you understand what's going on here: ``` calc M ≃ₗ[R] f.ker.quotient : (submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] r.range.mkq.ker : linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm ``` -/ (linear_equiv.to_Module_iso' ((submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ≪≫ₗ ((linear_map.quot_ker_equiv_range f) ≪≫ₗ (linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm)))) $ by { ext, refl } } /-- In the category of modules, every epimorphism is normal. -/ def normal_epi (hf : epi f) : normal_epi f := { W := of R f.ker, g := f.ker.subtype, w := linear_map.comp_ker_subtype _, is_colimit := is_cokernel.cokernel_iso _ _ (cokernel_is_colimit _) (linear_equiv.to_Module_iso' /- The following invalid Lean code might help you understand what's going on here: ``` calc f.ker.subtype.range.quotient ≃ₗ[R] f.ker.quotient : submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _) ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] N : linear_equiv.of_top _ (range_eq_top_of_epi _) ``` -/ (((submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _)) ≪≫ₗ (linear_map.quot_ker_equiv_range f)) ≪≫ₗ (linear_equiv.of_top _ (range_eq_top_of_epi _)))) $ by { ext, refl } } /-- The category of R-modules is abelian. -/ instance : abelian (Module R) := { has_finite_products := ⟨by apply_instance⟩, has_kernels := by apply_instance, has_cokernels := has_cokernels_Module, normal_mono := λ X Y, normal_mono, normal_epi := λ X Y, normal_epi } variables {O : Module.{v} R} (g : N ⟶ O) open linear_map local attribute [instance] preadditive.has_equalizers_of_has_kernels theorem exact_iff : exact f g ↔ f.range = g.ker := begin rw abelian.exact_iff' f g (kernel_is_limit _) (cokernel_is_colimit _), exact ⟨λ h, le_antisymm (range_le_ker_iff.2 h.1) (ker_le_range_iff.2 h.2), λ h, ⟨range_le_ker_iff.1 $ le_of_eq h, ker_le_range_iff.1 $ le_of_eq h.symm⟩⟩ end end Module
8bc7b75b4075f5c2d2ba11b0cd65104a61d15e4c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/crash.lean
73caa27b9facb9a7f24f872dd50066c7ec4e5f7b
[ "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
143
lean
-- section parameter P : Prop. definition crash := assume H : P, have H' : ¬ P, from H, _. end
bd6b1db10db66c6cae040838c9d9293ee5570426
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/cubical/squareover.hlean
d2196084cdee8affd6e78c6dc602d9018d9a5081
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
19,085
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 Squareovers -/ import .square open eq equiv is_equiv sigma namespace eq -- we give the argument B explicitly, because Lean would find (λa, B a) by itself, which -- makes the type uglier (of course the two terms are definitionally equal) inductive squareover {A : Type} (B : A → Type) {a₀₀ : A} {b₀₀ : B a₀₀} : Π{a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₁₂ : a₀₂ = a₂₂} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} (q₁₀ : pathover B b₀₀ p₁₀ b₂₀) (q₁₂ : pathover B b₀₂ p₁₂ b₂₂) (q₀₁ : pathover B b₀₀ p₀₁ b₀₂) (q₂₁ : pathover B b₂₀ p₂₁ b₂₂), Type := idsquareo : squareover B ids idpo idpo idpo idpo variables {A A' : Type} {B : A → Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A} /-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ /-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} {b : B a} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂} {b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄} /-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/ /-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/ /-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/ {q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂} {q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄} definition squareo := @squareover A B a₀₀ definition idsquareo [reducible] [constructor] (b₀₀ : B a₀₀) := @squareover.idsquareo A B a₀₀ b₀₀ definition idso [reducible] [constructor] := @squareover.idsquareo A B a₀₀ b₀₀ definition apds (f : Πa, B a) (s : square p₁₀ p₁₂ p₀₁ p₂₁) : squareover B s (apd f p₁₀) (apd f p₁₂) (apd f p₀₁) (apd f p₂₁) := square.rec_on s idso definition vrflo : squareover B vrfl q₁₀ q₁₀ idpo idpo := by induction q₁₀; exact idso definition hrflo : squareover B hrfl idpo idpo q₁₀ q₁₀ := by induction q₁₀; exact idso definition vdeg_squareover {p₁₀'} {s : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (r : change_path s q₁₀ = q₁₀') : squareover B (vdeg_square s) q₁₀ q₁₀' idpo idpo := by induction s; esimp at *; induction r; exact vrflo definition hdeg_squareover {p₀₁'} {s : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (r : change_path s q₀₁ = q₀₁') : squareover B (hdeg_square s) idpo idpo q₀₁ q₀₁' := by induction s; esimp at *; induction r; exact hrflo definition hconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₃₁ : squareover B s₃₁ q₃₀ q₃₂ q₂₁ q₄₁) : squareover B (hconcat s₁₁ s₃₁) (q₁₀ ⬝o q₃₀) (q₁₂ ⬝o q₃₂) q₀₁ q₄₁ := by induction t₃₁; exact t₁₁ definition vconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₁₃ : squareover B s₁₃ q₁₂ q₁₄ q₀₃ q₂₃) : squareover B (vconcat s₁₁ s₁₃) q₁₀ q₁₄ (q₀₁ ⬝o q₀₃) (q₂₁ ⬝o q₂₃) := by induction t₁₃; exact t₁₁ definition hinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (hinverse s₁₁) q₁₀⁻¹ᵒ q₁₂⁻¹ᵒ q₂₁ q₀₁ := by induction t₁₁; constructor definition vinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (vinverse s₁₁) q₁₂ q₁₀ q₀₁⁻¹ᵒ q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition eq_vconcato {q : b₀₀ =[p₁₀] b₂₀} (r : q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q q₁₂ q₀₁ q₂₁ := by induction r; exact t₁₁ definition vconcato_eq {q : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₁₂ = q) : squareover B s₁₁ q₁₀ q q₀₁ q₂₁ := by induction r; exact t₁₁ definition eq_hconcato {q : b₀₀ =[p₀₁] b₀₂} (r : q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q q₂₁ := by induction r; exact t₁₁ definition hconcato_eq {q : b₂₀ =[p₂₁] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₂₁ = q) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q := by induction r; exact t₁₁ definition pathover_vconcato {p : a₀₀ = a₂₀} {sp : p = p₁₀} {q : b₀₀ =[p] b₂₀} (r : change_path sp q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝pv s₁₁) q q₁₂ q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ definition vconcato_pathover {p : a₀₂ = a₂₂} {sp : p₁₂ = p} {q : b₀₂ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₁₂ = q) : squareover B (s₁₁ ⬝vp sp) q₁₀ q q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ definition pathover_hconcato {p : a₀₀ = a₀₂} {sp : p = p₀₁} {q : b₀₀ =[p] b₀₂} (r : change_path sp q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝ph s₁₁) q₁₀ q₁₂ q q₂₁ := by induction sp; induction r; exact t₁₁ definition hconcato_pathover {p : a₂₀ = a₂₂} {sp : p = p₂₁} {s : square p₁₀ p₁₂ p₀₁ p} {q : b₂₀ =[p] b₂₂} (t₁₁ : squareover B (s ⬝hp sp) q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q = q₂₁) : squareover B s q₁₀ q₁₂ q₀₁ q := by induction sp; induction r; exact t₁₁ infix ` ⬝ho `:69 := hconcato --type using \tr infix ` ⬝vo `:70 := vconcato --type using \tr infix ` ⬝hop `:72 := hconcato_eq --type using \tr infix ` ⬝vop `:74 := vconcato_eq --type using \tr infix ` ⬝pho `:71 := eq_hconcato --type using \tr infix ` ⬝pvo `:73 := eq_vconcato --type using \tr -- relating squareovers to squares definition square_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁) := by induction t₁₁; esimp; constructor /- definition squareover_of_square (q : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁)) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := sorry -/ definition square_of_squareover_ids {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (so : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r)) : square t b l r := begin note H := square_of_squareover so, -- use apply ... in rewrite [▸* at H,+idp_con at H,+ap_id at H,↑pathover_idp_of_eq at H], rewrite [+to_right_inv !(pathover_equiv_tr_eq (refl a)) at H], exact H end definition squareover_ids_of_square {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (q : square t b l r) : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r) := square.rec_on q idso -- relating pathovers to squareovers definition pathover_of_squareover' (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := by induction t₁₁; constructor definition pathover_of_squareover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (t₁₁ : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂ := begin revert s t₁₁, refine equiv_rect' !square_equiv_eq⁻¹ᵉ (λa b, squareover B b _ _ _ _ → _) _, intro s, exact pathover_of_squareover' end definition squareover_of_pathover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (r : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂) : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₁₂; esimp [concato] at r;induction r;induction q₂₁;induction q₁₀;constructor definition pathover_top_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ =[eq_top_of_square s₁₁] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition squareover_of_pathover_top {s : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹} (r : q₁₀ =[s] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B (square_of_eq_top s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₂₁; induction q₁₂; esimp at r;induction r;induction q₁₀;constructor definition pathover_of_hdeg_squareover {p₀₁' : a₀₀ = a₀₂} {r : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (hdeg_square r) idpo idpo q₀₁ q₀₁') : q₀₁ =[r] q₀₁' := by induction r; induction q₀₁'; exact (pathover_of_squareover' t)⁻¹ᵒ definition pathover_of_vdeg_squareover {p₁₀' : a₀₀ = a₂₀} {r : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (t : squareover B (vdeg_square r) q₁₀ q₁₀' idpo idpo) : q₁₀ =[r] q₁₀' := by induction r; induction q₁₀'; exact pathover_of_squareover' t definition squareover_of_eq_top (r : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := begin induction s₁₁, revert q₁₂ q₁₀ r, eapply idp_rec_on q₂₁, clear q₂₁, intro q₁₂, eapply idp_rec_on q₁₂, clear q₁₂, esimp, intros, induction r, eapply idp_rec_on q₁₀, constructor end definition eq_top_of_squareover (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction r; reflexivity definition change_square {s₁₁'} (p : s₁₁ = s₁₁') (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁' q₁₀ q₁₂ q₀₁ q₂₁ := p ▸ r /- definition squareover_equiv_pathover (q₁₀ : b₀₀ =[p₁₀] b₂₀) (q₁₂ : b₀₂ =[p₁₂] b₂₂) (q₀₁ : b₀₀ =[p₀₁] b₀₂) (q₂₁ : b₂₀ =[p₂₁] b₂₂) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ ≃ q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := begin fapply equiv.MK, { exact pathover_of_squareover}, { intro r, rewrite [-to_left_inv !square_equiv_eq s₁₁], apply squareover_of_pathover, exact r}, { intro r, }, --need characterization of squareover lying over ids. { intro s, induction s, apply idp}, end -/ definition eq_of_vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (p : squareover B vrfl q₁₀ q₁₀' idpo idpo) : q₁₀ = q₁₀' := begin note H := square_of_squareover p, -- use apply ... in induction p₁₀, -- if needed we can remove this induction and use con_tr_idp in types/eq2 rewrite [▸* at H,idp_con at H,+ap_id at H], let H' := eq_of_vdeg_square H, exact inj !pathover_equiv_tr_eq H' end -- definition vdeg_tr_squareover {q₁₂ : p₀₁ ▸ b₀₀ =[p₁₂] p₂₁ ▸ b₂₀} (r : q₁₀ =[_] q₁₂) -- : squareover B s₁₁ q₁₀ q₁₂ !pathover_tr !pathover_tr := -- by induction p;exact vrflo /- A version of eq_pathover where the type of the equality also varies -/ definition eq_pathover_dep {f g : Πa, B a} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : squareover B hrfl (pathover_idp_of_eq q) (pathover_idp_of_eq r) (apd f p) (apd g p)) : q =[p] r := begin induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_square, exact square_of_squareover_ids s end /- charcaterization of pathovers in pathovers -/ -- in this version the fibration (B) of the pathover does not depend on the variable (a) definition pathover_pathover {a' a₂' : A'} {p : a' = a₂'} {f g : A' → A} {b : Πa, B (f a)} {b₂ : Πa, B (g a)} {q : Π(a' : A'), f a' = g a'} (r : pathover B (b a') (q a') (b₂ a')) (r₂ : pathover B (b a₂') (q a₂') (b₂ a₂')) (s : squareover B (natural_square q p) r r₂ (pathover_ap B f (apd b p)) (pathover_ap B g (apd b₂ p))) : pathover (λa, pathover B (b a) (q a) (b₂ a)) r p r₂ := begin induction p, esimp at s, apply pathover_idp_of_eq, apply eq_of_vdeg_squareover, exact s end definition squareover_change_path_left {p₀₁' : a₀₀ = a₀₂} (r : p₀₁' = p₀₁) {q₀₁ : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (r ⬝ph s₁₁) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ (change_path r q₀₁) q₂₁ := by induction r; exact t definition squareover_change_path_right {p₂₁' : a₂₀ = a₂₂} (r : p₂₁' = p₂₁) {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r⁻¹) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r q₂₁) := by induction r; exact t definition squareover_change_path_right' {p₂₁' : a₂₀ = a₂₂} (r : p₂₁ = p₂₁') {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r⁻¹ q₂₁) := by induction r; exact t /- You can construct a square in a sigma-type by giving a squareover -/ definition square_dpair_eq_dpair {a₀₀ a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂} {q₁₂ : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (dpair_eq_dpair p₁₀ q₁₀) (dpair_eq_dpair p₁₂ q₁₂) (dpair_eq_dpair p₀₁ q₀₁) (dpair_eq_dpair p₂₁ q₂₁) := by induction t₁₁; constructor definition sigma_square {v₀₀ v₂₀ v₀₂ v₂₂ : Σa, B a} {p₁₀ : v₀₀ = v₂₀} {p₀₁ : v₀₀ = v₀₂} {p₂₁ : v₂₀ = v₂₂} {p₁₂ : v₀₂ = v₂₂} (s₁₁ : square p₁₀..1 p₁₂..1 p₀₁..1 p₂₁..1) (t₁₁ : squareover B s₁₁ p₁₀..2 p₁₂..2 p₀₁..2 p₂₁..2) : square p₁₀ p₁₂ p₀₁ p₂₁ := begin induction v₀₀, induction v₂₀, induction v₀₂, induction v₂₂, rewrite [▸* at *, -sigma_eq_eta p₁₀, -sigma_eq_eta p₁₂, -sigma_eq_eta p₀₁, -sigma_eq_eta p₂₁], exact square_dpair_eq_dpair s₁₁ t₁₁ end definition move_right_of_top_over {p : a₀₀ = a} {p' : a = a₂₀} {s : square p p₁₂ p₀₁ (p' ⬝ p₂₁)} {q : b₀₀ =[p] b} {q' : b =[p'] b₂₀} (t : squareover B (move_top_of_right s) (q ⬝o q') q₁₂ q₀₁ q₂₁) : squareover B s q q₁₂ q₀₁ (q' ⬝o q₂₁) := begin induction q', induction q, induction q₂₁, exact t end variables (s₁₁ q₀₁ q₁₀ q₂₁ q₁₂) definition squareover_fill_t : Σ (q : b₀₀ =[p₁₀] b₂₀), squareover B s₁₁ q q₁₂ q₀₁ q₂₁ := begin induction s₁₁, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idpo, idso⟩ end definition squareover_fill_b : Σ (q : b₀₂ =[p₁₂] b₂₂), squareover B s₁₁ q₁₀ q q₀₁ q₂₁ := begin induction s₁₁, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₀ using idp_rec_on, exact ⟨idpo, idso⟩ end definition squareover_fill_l : Σ (q : b₀₀ =[p₀₁] b₀₂), squareover B s₁₁ q₁₀ q₁₂ q q₂₁ := begin induction s₁₁, induction q₁₀ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idpo, idso⟩ end definition squareover_fill_r : Σ (q : b₂₀ =[p₂₁] b₂₂) , squareover B s₁₁ q₁₀ q₁₂ q₀₁ q := begin induction s₁₁, induction q₀₁ using idp_rec_on, induction q₁₀ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idpo, idso⟩ end end eq
ff5ef4651fa5cef581bbd897a661af6f04bca1da
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Meta/Tactic/Simp/Rewrite.lean
9aa7bd8d92b763dbb031c60b44d6f42504c08cc1
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
6,240
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.SynthInstance import Lean.Meta.Tactic.Simp.Types namespace Lean.Meta.Simp def synthesizeArgs (lemmaName : Name) (xs : Array Expr) (bis : Array BinderInfo) (discharge? : Expr → SimpM (Option Expr)) : SimpM Bool := do for x in xs, bi in bis do let type ← inferType x if bi.isInstImplicit then unless (← synthesizeInstance x type) do return false else if (← instantiateMVars x).isMVar then if (← isProp type) then match ← discharge? type with | some proof => unless (← isDefEq x proof) do trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to assign proof{indentExpr type}" return false | none => trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to discharge hypotheses{indentExpr type}" return false else if (← isClass? type).isSome then unless (← synthesizeInstance x type) do return false return true where synthesizeInstance (x type : Expr) : SimpM Bool := do match ← trySynthInstance type with | LOption.some val => if (← isDefEq x val) then return true else trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to assign instance{indentExpr type}" return false | _ => trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to synthesize instance{indentExpr type}" return false /- Remark: the parameter tag is used for creating trace messages. It is irrelevant otherwise. -/ def rewrite (e : Expr) (s : DiscrTree SimpLemma) (erased : Std.PHashSet Name) (discharge? : Expr → SimpM (Option Expr)) (tag : String) : SimpM Result := do let lemmas ← s.getMatch e if lemmas.isEmpty then trace[Debug.Meta.Tactic.simp] "no theorems found for {tag}-rewriting {e}" return { expr := e } else let lemmas := lemmas.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority for lemma in lemmas do unless inErasedSet lemma do if let some result ← tryLemma? lemma then return result return { expr := e } where inErasedSet (lemma : SimpLemma) : Bool := match lemma.name? with | none => false | some name => erased.contains name tryLemma? (lemma : SimpLemma) : SimpM (Option Result) := withNewMCtxDepth do let val ← lemma.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let type ← instantiateMVars type let lhs := type.appFn!.appArg! if (← isDefEq lhs e) then unless (← synthesizeArgs lemma.getName xs bis discharge?) do return none let proof ← instantiateMVars (mkAppN val xs) if ← hasAssignableMVar proof then trace[Meta.Tactic.simp.rewrite] "{lemma}, has unassigned metavariables after unification" return none let rhs ← instantiateMVars type.appArg! if e == rhs then return none if lemma.perm && !Expr.lt rhs e then trace[Meta.Tactic.simp.rewrite] "{lemma}, perm rejected {e} ==> {rhs}" return none trace[Meta.Tactic.simp.rewrite] "{lemma}, {e} ==> {rhs}" return some { expr := rhs, proof? := proof } else unless lhs.isMVar do -- We do not report unification failures when `lhs` is a metavariable -- Example: `x = ()` -- TODO: reconsider if we want lemmas such as `(x : Unit) → x = ()` trace[Meta.Tactic.simp.unify] "{lemma}, failed to unify {lhs} with {e}" return none def rewriteCtorEq? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do match e.eq? with | none => return none | some (_, lhs, rhs) => let lhs ← whnf lhs let rhs ← whnf rhs let env ← getEnv match lhs.constructorApp? env, rhs.constructorApp? env with | some (c₁, _), some (c₂, _) => if c₁.name != c₂.name then withLocalDeclD `h e fun h => return some { expr := mkConst ``False, proof? := (← mkEqFalse' (← mkLambdaFVars #[h] (← mkNoConfusion (mkConst ``False) h))) } else return none | _, _ => return none @[inline] def tryRewriteCtorEq (e : Expr) (x : SimpM Step) : SimpM Step := do match (← rewriteCtorEq? e) with | some r => return Step.done r | none => x def rewriteUsingDecide? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do if e.hasFVar || e.hasMVar || e.isConstOf ``True || e.isConstOf ``False then return none else try let d ← mkDecide e let r ← withDefault <| whnf d if r.isConstOf ``true then return some { expr := mkConst ``True, proof? := mkAppN (mkConst ``eqTrueOfDecide) #[e, d.appArg!, (← mkEqRefl (mkConst ``true))] } else if r.isConstOf ``false then let h ← mkEqRefl d return some { expr := mkConst ``False, proof? := mkAppN (mkConst ``eqFalseOfDecide) #[e, d.appArg!, (← mkEqRefl (mkConst ``false))] } else return none catch _ => return none @[inline] def tryRewriteUsingDecide (e : Expr) (x : SimpM Step) : SimpM Step := do if (← read).config.decide then match (← rewriteUsingDecide? e) with | some r => return Step.done r | none => x else x def rewritePre (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.pre lemmas.erased discharge? (tag := "pre")) def rewritePost (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.post lemmas.erased discharge? (tag := "post")) def preDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := tryRewriteCtorEq e <| rewritePre e discharge? def postDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do -- TODO: try equation lemmas tryRewriteCtorEq e <| tryRewriteUsingDecide e <| rewritePost e discharge? end Lean.Meta.Simp
53925fa013a8fed2e25c8ee80a1650d41653c9e4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/tactic/interactive.lean
99efbbae0d15ffa5c27d686e61cdd440d775905f
[ "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
44,560
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import tactic.lint open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- Similar to `constructor`, but does not reorder goals. -/ meta def fconstructor : tactic unit := concat_tags tactic.fconstructor add_tactic_doc { name := "fconstructor", category := doc_category.tactic, decl_names := [`tactic.interactive.fconstructor], tags := ["logic", "goal management"] } /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) add_tactic_doc { name := "substs", category := doc_category.tactic, decl_names := [`tactic.interactive.substs], tags := ["rewriting"] } /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc add_tactic_doc { name := "unfold_coes", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_coes], tags := ["simplification"] } /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without requiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a non-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/ @[inline] protected meta def id (tac : itactic) : tactic unit := tac /-- `work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero), and does not require that the goal be solved at the end (any remaining subgoals are inserted back into the list of goals). Typically usage might look like: ```` intros, simp, apply lemma_1, work_on_goal 2 { dsimp, simp }, refl ```` See also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`. -/ meta def work_on_goal : parse small_nat → itactic → tactic unit | n t := do goals ← get_goals, let earlier_goals := goals.take n, let later_goals := goals.drop (n+1), set_goals (goals.nth n).to_list, t, new_goals ← get_goals, set_goals (earlier_goals ++ new_goals ++ later_goals) /-- `swap n` will move the `n`th goal to the front. `swap` defaults to `swap 2`, and so interchanges the first and second goals. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end add_tactic_doc { name := "swap", category := doc_category.tactic, decl_names := [`tactic.interactive.swap], tags := ["goal management"] } /-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. -/ meta def rotate (n := 1) : tactic unit := tactic.rotate n add_tactic_doc { name := "rotate", category := doc_category.tactic, decl_names := [`tactic.interactive.rotate], tags := ["goal management"] } /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h add_tactic_doc { name := "clear_", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_], tags := ["context management"] } meta def apply_iff_congr_core : tactic unit := applyc ``iff_of_eq meta def congr_core' : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> apply_iff_congr_core <|> fail "congr tactic failed" /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. If, at any point, a subgoal matches a hypothesis then the subgoal will be closed. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core' >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) add_tactic_doc { name := "congr'", category := doc_category.tactic, decl_names := [`tactic.interactive.congr', `tactic.interactive.congr], tags := ["congruence"], inherit_description_from := `tactic.interactive.congr' } /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end add_tactic_doc { name := "replace", category := doc_category.tactic, decl_names := [`tactic.interactive.replace], tags := ["context management"] } /-- Make every proposition in the context decidable. -/ meta def classical := tactic.classical add_tactic_doc { name := "classical", category := doc_category.tactic, decl_names := [`tactic.interactive.classical], tags := ["classical logic", "type class"] } private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux @[nolint def_lemma] lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end add_tactic_doc { name := "generalize_hyp", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize_hyp], tags := ["context management"] } /-- The `exact e` and `refine e` tactics require a term `e` whose type is definitionally equal to the goal. `convert e` is similar to `refine e`, but the type of `e` is not required to exactly match the goal. Instead, new goals are created for differences between the type of `e` and the goal. For example, in the proof state ```lean n : ℕ, e : prime (2 * n + 1) ⊢ prime (n + n + 1) ``` the tactic `convert e` will change the goal to ```lean ⊢ n + n = 2 * n ``` In this example, the new goal can be solved using `ring`. The syntax `convert ← e` will reverse the direction of the new goals (producing `⊢ 2 * n = n + n` in this example). Internally, `convert e` works by creating a new goal asserting that the goal equals the type of `e`, then simplifying it using `congr'`. The syntax `convert e using n` can be used to control the depth of matching (like `congr' n`). In the example, `convert e using 1` would produce a new goal `⊢ n + n + 1 = 2 * n + 1`. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], try (congr' n), gs' ← get_goals, set_goals $ gs' ++ gs add_tactic_doc { name := "convert", category := doc_category.tactic, decl_names := [`tactic.interactive.convert], tags := ["congruence"] } meta def compact_decl_aux : list name → binder_info → expr → list expr → tactic (list (list name × binder_info × expr)) | ns bi t [] := pure [(ns.reverse, bi, t)] | ns bi t (v'@(local_const n pp bi' t') :: xs) := do t' ← infer_type v', if bi = bi' ∧ t = t' then compact_decl_aux (pp :: ns) bi t xs else do vs ← compact_decl_aux [pp] bi' t' xs, pure $ (ns.reverse, bi, t) :: vs | ns bi t (_ :: xs) := compact_decl_aux ns bi t xs /-- go from (x₀ : t₀) (x₁ : t₀) (x₂ : t₀) to (x₀ x₁ x₂ : t₀) -/ meta def compact_decl : list expr → tactic (list (list name × binder_info × expr)) | [] := pure [] | (v@(local_const n pp bi t) :: xs) := do t ← infer_type v, compact_decl_aux [pp] bi t xs | (_ :: xs) := compact_decl xs /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.clean meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (dsimp_target simp_lemmas.mk), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ```lean refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` `have_field`, used after `refine_struct _`, poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `match_hyp h := t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern). We use this tactic for writing tests. -/ meta def match_hyp (n : parse ident) (p : parse $ tk ":=" *> texpr) (m := reducible) : tactic (list expr) := do h ← get_local n >>= infer_type >>= instantiate_mvars, match_expr p h m /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h := t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) := tactic.success_if_fail_with_msg tac meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc add_tactic_doc { name := "refine_struct", category := doc_category.tactic, decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field, `tactic.interactive.have_field], tags := ["structures"], inherit_description_from := `tactic.interactive.refine_struct } /-- `apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is optional, equal to 50 by default. You can pass an `apply_cfg` option argument as `apply_rules hs n opt`. (A typical usage would be with `apply_rules hs n { md := reducible })`, which asks `apply_rules` to not unfold `semireducible` definitions (i.e. most) when checking if a lemma matches the goal.) `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. For instance: ```lean @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := -- any of the following lines solve the goal: add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] by apply_rules [mono_rules] by apply_rules mono_rules ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) (opt : apply_cfg := {}) : tactic unit := tactic.apply_rules hs n opt add_tactic_doc { name := "apply_rules", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_rules], tags := ["lemma application"] } meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. - `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`; - `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`; - `h_generalize! Hx : e == x` reverts `Hx`; - when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) add_tactic_doc { name := "h_generalize", category := doc_category.tactic, decl_names := [`tactic.interactive.h_generalize], tags := ["context management"] } /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating `∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (interactive.simp none tt [simp_arg_type.expr ``(exists_prop)] [] (loc.ns $ some <$> names)), try (tactic.clear tgt) add_tactic_doc { name := "choose", category := doc_category.tactic, decl_names := [`tactic.interactive.choose], tags := ["classical logic"] } /-- The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d` where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by iterating the following steps: - write an inverse as a division - in any product, move the division to the right - if there are several divisions in a product, group them together at the end and write them as a single division - reduce a sum to a common denominator If the goal is an equality, this simpset will also clear the denominators, so that the proof can normally be concluded by an application of `ring` or `ring_exp`. `field_simp [hx, hy]` is a short form for `simp [-one_div_eq_inv, hx, hy] with field_simps` Note that this naive algorithm will not try to detect common factors in denominators to reduce the complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle complicated expressions in the next step. As always with the simplifier, reduction steps will only be applied if the preconditions of the lemmas can be checked. This means that proofs that denominators are nonzero should be included. The fact that a product is nonzero when all factors are, and that a power of a nonzero number is nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums) should be given explicitly. If your expression is not completely reduced by the simplifier invocation, check the denominators of the resulting expression and provide proofs that they are nonzero to enable further progress. The invocation of `field_simp` removes the lemma `one_div_eq_inv` (which is marked as a simp lemma in core) from the simpset, as this lemma works against the algorithm explained above. For example, ```lean example (a b c d x y : ℂ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x + c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x + c) / x) := begin field_simp [hx, hy], ring end See also the `cancel_denoms` tactic, which tries to do a similar simplification for expressions that have numerals in denominators. The tactics are not related: `cancel_denoms` will only handle numeric denominators, and will try to entirely remove (numeric) division from the expression by multiplying by a factor. ``` -/ meta def field_simp (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := let attr_names := `field_simps :: attr_names, hs := simp_arg_type.except `one_div_eq_inv :: hs in propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat) add_tactic_doc { name := "field_simp", category := doc_category.tactic, decl_names := [`tactic.interactive.field_simp], tags := ["simplification", "arithmetic"] } meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p add_tactic_doc { name := "guard_target'", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_target'], tags := ["testing"] } /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" add_tactic_doc { name := "triv", category := doc_category.tactic, decl_names := [`tactic.interactive.triv], tags := ["finishing"] } /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. It will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: ```lean example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ n > 0, n = n := begin use 1, -- goal is now 1 > 0 ∧ 1 = 1, whereas it would be ∃ (H : 1 > 0), 1 = 1 after existsi 1. exact ⟨zero_lt_one, rfl⟩, end example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] ``` -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := focus1 $ tactic.use l; try (triv <|> (do `(Exists %%p) ← target, to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip)) add_tactic_doc { name := "use", category := doc_category.tactic, decl_names := [`tactic.interactive.use, `tactic.interactive.existsi], tags := ["logic"], inherit_description_from := `tactic.interactive.use } /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. ```lean example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end ``` -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl add_tactic_doc { name := "clear_aux_decl", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl], tags := ["context management"], inherit_description_from := `tactic.interactive.clear_aux_decl } meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) add_tactic_doc { name := "change'", category := doc_category.tactic, decl_names := [`tactic.interactive.change', `tactic.interactive.change], tags := ["renaming"], inherit_description_from := `tactic.interactive.change' } meta def convert_to_core (r : pexpr) : tactic unit := do tgt ← target, h ← to_expr ``(_ : %%tgt = %%r), rewrite_target h, swap /-- `convert_to g using n` attempts to change the current goal to `g`, but unlike `change`, it will generate equality proof obligations using `congr' n` to resolve discrepancies. `convert_to g` defaults to using `congr' 1`. `ac_change` is `convert_to` followed by `ac_refl`. It is useful for rearranging/reassociating e.g. sums: ```lean example (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ N := begin ac_change a + d + e + f + c + g + b ≤ _, -- ⊢ a + d + e + f + c + g + b ≤ N end ``` -/ meta def convert_to (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := match n with | none := convert_to_core r >> `[congr' 1] | (some 0) := convert_to_core r | (some o) := convert_to_core r >> congr' o end /-- `ac_change g using n` is `convert_to g using n; try {ac_refl}`. -/ meta def ac_change (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := convert_to r n; try ac_refl add_tactic_doc { name := "convert_to", category := doc_category.tactic, decl_names := [`tactic.interactive.convert_to, `tactic.interactive.ac_change], tags := ["congruence"], inherit_description_from := `tactic.interactive.convert_to } private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. ```lean example (x : ℕ) (h : x = 3) : x + x + x = 9 := begin set y := x with ←h_xy, /- x : ℕ, y : ℕ := x, h_xy : x = y, h : y = 3 ⊢ y + y + y = 9 -/ end ``` -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do tp ← i_to_expr $ tp.get_or_else pexpr.mk_placeholder, pv ← to_expr ``(%%pv : %%tp), tp ← instantiate_mvars tp, definev a tp pv, when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id, reflexivity | none := skip end add_tactic_doc { name := "set", category := doc_category.tactic, decl_names := [`tactic.interactive.set], tags := ["context management"] } /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do n ← xs.mmap (try_core ∘ get_local) >>= revert_lst ∘ list.filter_map id, ls ← local_context, ls.reverse.mmap' $ try ∘ tactic.clear, intron_no_renames n add_tactic_doc { name := "clear_except", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_except], tags := ["context management"] } meta def format_names (ns : list name) : format := format.join $ list.intersperse " " (ns.map to_fmt) private meta def indent_bindents (l r : string) : option (list name) → expr → tactic format | none e := do e ← pp e, pformat!"{l}{format.nest l.length e}{r}" | (some ns) e := do e ← pp e, let ns := format_names ns, let margin := l.length + ns.to_string.length + " : ".length, pformat!"{l}{ns} : {format.nest margin e}{r}" private meta def format_binders : list name × binder_info × expr → tactic format | (ns, binder_info.default, t) := indent_bindents "(" ")" ns t | (ns, binder_info.implicit, t) := indent_bindents "{" "}" ns t | (ns, binder_info.strict_implicit, t) := indent_bindents "⦃" "⦄" ns t | ([n], binder_info.inst_implicit, t) := if "_".is_prefix_of n.to_string then indent_bindents "[" "]" none t else indent_bindents "[" "]" [n] t | (ns, binder_info.inst_implicit, t) := indent_bindents "[" "]" ns t | (ns, binder_info.aux_decl, t) := indent_bindents "(" ")" ns t private meta def partition_vars' (s : name_set) : list expr → list expr → list expr → tactic (list expr × list expr) | [] as bs := pure (as.reverse, bs.reverse) | (x :: xs) as bs := do t ← infer_type x, if t.has_local_in s then partition_vars' xs as (x :: bs) else partition_vars' xs (x :: as) bs private meta def partition_vars : tactic (list expr × list expr) := do ls ← local_context, partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] [] /-- Format the current goal as a stand-alone example. Useful for testing tactic. * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end extract_goal my_lemma -- prints: -- lemma my_lemma (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) -- (h₁ : p ≤ q) : -- i ≤ k := -- begin -- admit, -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {p i j k : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) : -- i ≤ k := -- begin -- admit, -- end end example : true := begin let n := 0, have m : ℕ, admit, have k : fin n, admit, have : n + m + k.1 = 0, extract_goal, -- prints: -- example (m : ℕ) : let n : ℕ := 0 in ∀ (k : fin n), n + m + k.val = 0 := -- begin -- intros n k, -- admit, -- end end ``` -/ meta def extract_goal (print_use : parse $ tt <$ tk "!" <|> pure ff) (n : parse ident?) (vs : parse with_ident_list) : tactic unit := do tgt ← target, solve_aux tgt $ do { ((cxt₀,cxt₁,ls,tgt),_) ← solve_aux tgt $ do { when (¬ vs.empty) (clear_except vs), ls ← local_context, ls ← ls.mfilter $ succeeds ∘ is_local_def, n ← revert_lst ls, (c₀,c₁) ← partition_vars, tgt ← target, ls ← intron' n, pure (c₀,c₁,ls,tgt) }, is_prop ← is_prop tgt, let title := match n, is_prop with | none, _ := to_fmt "example" | (some n), tt := format!"lemma {n}" | (some n), ff := format!"def {n}" end, cxt₀ ← compact_decl cxt₀ >>= list.mmap format_binders, cxt₁ ← compact_decl cxt₁ >>= list.mmap format_binders, stmt ← pformat!"{tgt} :=", let fmt := format.group $ format.nest 2 $ title ++ cxt₀.foldl (λ acc x, acc ++ format.group (format.line ++ x)) "" ++ format.join (list.map (λ x, format.line ++ x) cxt₁) ++ " :" ++ format.line ++ stmt, trace $ fmt.to_string $ options.mk.set_nat `pp.width 80, let var_names := format.intercalate " " $ ls.map (to_fmt ∘ local_pp_name), let call_intron := if ls.empty then to_fmt "" else format!"\n intros {var_names},", trace!"begin{call_intron}\n admit,\nend\n" }, skip add_tactic_doc { name := "extract_goal", category := doc_category.tactic, decl_names := [`tactic.interactive.extract_goal], tags := ["goal management", "proof extraction"] } /-- `inhabit α` tries to derive a `nonempty α` instance and then upgrades this to an `inhabited α` instance. If the target is a `Prop`, this is done constructively; otherwise, it uses `classical.choice`. ```lean example (α) [nonempty α] : ∃ a : α, true := begin inhabit α, existsi default α, trivial end ``` -/ meta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit := do ty ← i_to_expr t, nm ← returnopt inst_name <|> get_unused_name `inst, tgt ← target, tgt_is_prop ← is_prop tgt, if tgt_is_prop then do decorate_error "could not infer nonempty instance:" $ mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply, introI nm else do decorate_error "could not infer nonempty instance:" $ mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none, resetI add_tactic_doc { name := "inhabit", category := doc_category.tactic, decl_names := [`tactic.interactive.inhabit], tags := ["context management", "type class"] } /-- `revert_deps n₁ n₂ ...` reverts all the hypotheses that depend on one of `n₁, n₂, ...` It does not revert `n₁, n₂, ...` themselves (unless they depend on another `nᵢ`). -/ meta def revert_deps (ns : parse ident*) : tactic unit := propagate_tags $ ns.reverse.mmap' $ λ n, get_local n >>= tactic.revert_deps add_tactic_doc { name := "revert_deps", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_deps], tags := ["context management", "goal management"] } /-- `revert_after n` reverts all the hypotheses after `n`. -/ meta def revert_after (n : parse ident) : tactic unit := propagate_tags $ get_local n >>= tactic.revert_after >> skip add_tactic_doc { name := "revert_after", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_after], tags := ["context management", "goal management"] } /-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them into regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`. -/ meta def clear_value (ns : parse ident*) : tactic unit := propagate_tags $ ns.reverse.mmap' $ λ n, get_local n >>= tactic.clear_value add_tactic_doc { name := "clear_value", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_value], tags := ["context management"] } /-- `generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize' h : e = x` in addition registers the hypothesis `h : e = x`. `generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis `x` is not a local definition. -/ meta def generalize' (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize' e x >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize' e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h add_tactic_doc { name := "generalize'", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize'], tags := ["context management"] } end interactive end tactic
3c6401a7a290e873403faa5bf4b5d725ceca2a7d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq5.lean
cd555faeb98815c4db098ea84144b3fe57476c6a
[ "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
273
lean
open nat definition fib : nat → nat | fib 0 := 1 | fib 1 := 1 | fib (x+2) := fib x + fib (x+1) theorem fib0 : fib 0 = 1 := rfl theorem fib1 : fib 1 = 1 := rfl theorem fib_succ_succ (a : nat) : fib (a+2) = fib a + fib (a+1) := rfl example : fib 8 = 34 := rfl
64eb88c2522693973613bcfc5bc0b9421c95c9d9
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/condensed/condensed.lean
94c871241ff0c41d933fb7cfca7e8a0a8727ba2e
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,750
lean
import condensed.proetale_site /-! # Condensed sets Defines the category of condensed sets and condensed structures. *Strictly speaking* these are pyknotic, but we hope that in the context of Lean's type theory they serve the same purpose. -/ open category_theory category_theory.limits universes v u variables {C : Type u} [category.{v} C] /-- The category of condensed sets. -/ @[derive category] def CondensedSet : Type (u+1) := SheafOfTypes.{u} proetale_topology.{u} /-- The category of condensed `A`. Applying this to `A = Type*` is *equivalent* but not the same as `CondensedSet`. -/ @[derive category] def Condensed (A : Type (u+1)) [large_category A] : Type (u+1) := Sheaf.{u} proetale_topology A example : category.{u+1} (Condensed Ab.{u}) := infer_instance example : category.{u+1} (Condensed Ring.{u}) := infer_instance open opposite noncomputable theory variables (P : Profinite.{u}ᵒᵖ ⥤ Type u) lemma maps_comm {S S' : Profinite.{u}} (f : S' ⟶ S) : P.map f.op ≫ P.map (pullback.fst : pullback f f ⟶ S').op = P.map f.op ≫ P.map pullback.snd.op := by rw [←P.map_comp, ←op_comp, pullback.condition, op_comp, P.map_comp] def natural_fork {S S' : Profinite.{u}} (f : S' ⟶ S) : fork (P.map pullback.fst.op) (P.map pullback.snd.op) := fork.of_ι (P.map (quiver.hom.op f)) (maps_comm P f) -- TODO (BM): put this in mathlib (it's already in a mathlib branch with API) def category_theory.functor.preserves_terminal (P : Profinite.{u}ᵒᵖ ⥤ Type u) : Prop := sorry -- TODO (BM): put this in mathlib (it's already in a mathlib branch with API) def category_theory.functor.preserves_binary_products (P : Profinite.{u}ᵒᵖ ⥤ Type u) : Prop := sorry structure condensed_type_condition : Prop := (empty : nonempty P.preserves_terminal) (bin_prod : nonempty P.preserves_binary_products) (pullbacks : ∀ {S S' : Profinite.{u}} (f : S' ⟶ S) [epi f], nonempty (is_limit (natural_fork P f))) -- (BM): I'm 90% sure this is true as stated, the forward direction is about halfway done. lemma sheaf_condition_iff : presieve.is_sheaf proetale_topology P ↔ condensed_type_condition P := sorry -- TODO: State `sheaf_condition_iff` for presheaves taking values in `A` for `A` with appropriate -- structure. -- TODO: Use `sheaf_condition_iff` to define the functor of Example 1.5, it might look like this: def embed_Top : Top.{u} ⥤ CondensedSet.{u} := { obj := λ T, ⟨Profinite.to_Top.op ⋙ yoneda.obj T, sorry⟩, map := λ T₁ T₂ f, whisker_left Profinite.to_Top.op (yoneda.map f) } -- TODO: Use the above to prove the first part of Proposition 1.7: lemma embed_Top_faithful : faithful embed_Top := sorry -- TODO: Construct the left adjoint to `embed_Top` as in the second part of Proposition 1.7.
696392a0a0c71bbd49455d4de739e2f309b8b139
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/infoTree.lean
dd8e415458bd742d6295c93c21b6b29fc44506f8
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
618
lean
import Lean open Lean.Elab structure A where val : Nat → Nat structure B where pair : A × A set_option trace.Elab.info true def f (x : Nat) : Nat × Nat := let y := ⟨x, x⟩ id y def h : (x y : Nat) → (b : Bool) → x + 0 = x := fun x y b => by simp def f2 : (x y : Nat) → (b : Bool) → Nat := fun x y b => let (z, w) := (x + y, x - y) let z1 := z + w z + z1 def f3 (s : Nat × Array (Array Nat)) : Array Nat := s.2[1].push s.1 def f4 (arg : B) : Nat := arg.pair.fst.val 0 def f5 (x : Nat) : B := { pair := ({ val := id }, { val := id }) } open Nat in #print xor
6e74fb89b12685eda2aeeeae1e4d6342f7c70ff6
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/big_operators/fin.lean
01763403f776961f086aef10ba571ef5ffddcd49
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
9,528
lean
/- Copyright (c) 2020 Yury Kudryashov, Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Anne Baanen -/ import data.fintype.card import data.fintype.fin import logic.equiv.fin /-! # Big operators and `fin` Some results about products and sums over the type `fin`. The most important results are the induction formulas `fin.prod_univ_cast_succ` and `fin.prod_univ_succ`, and the formula `fin.prod_const` for the product of a constant function. These results have variants for sums instead of products. -/ open_locale big_operators open finset variables {α : Type*} {β : Type*} namespace finset @[to_additive] theorem prod_range [comm_monoid β] {n : ℕ} (f : ℕ → β) : ∏ i in finset.range n, f i = ∏ i : fin n, f i := prod_bij' (λ k w, ⟨k, mem_range.mp w⟩) (λ a ha, mem_univ _) (λ a ha, congr_arg _ (fin.coe_mk _).symm) (λ a m, a) (λ a m, mem_range.mpr a.prop) (λ a ha, fin.coe_mk _) (λ a ha, fin.eta _ _) end finset namespace fin @[to_additive] theorem prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) : ∏ i, f i = ((list.fin_range n).map f).prod := by simp [univ_def, finset.fin_range] @[to_additive] theorem prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) : (list.of_fn f).prod = ∏ i, f i := by rw [list.of_fn_eq_map, prod_univ_def] /-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/ @[to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"] theorem prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/ @[to_additive /- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/] theorem prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) := by rw [univ_succ_above, prod_cons, finset.prod_map, rel_embedding.coe_fn_to_embedding] /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f 0` plus the remaining product -/ @[to_additive /- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f 0` plus the remaining product -/] theorem prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := prod_univ_succ_above f 0 /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f (fin.last n)` plus the remaining product -/ @[to_additive /- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f (fin.last n)` plus the remaining sum -/] theorem prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (last n) := by simpa [mul_comm] using prod_univ_succ_above f (last n) @[to_additive] lemma prod_cons [comm_monoid β] {n : ℕ} (x : β) (f : fin n → β) : ∏ i : fin n.succ, (cons x f : fin n.succ → β) i = x * ∏ i : fin n, f i := by simp_rw [prod_univ_succ, cons_zero, cons_succ] @[to_additive sum_univ_one] theorem prod_univ_one [comm_monoid β] (f : fin 1 → β) : ∏ i, f i = f 0 := by simp @[simp, to_additive] theorem prod_univ_two [comm_monoid β] (f : fin 2 → β) : ∏ i, f i = f 0 * f 1 := by simp [prod_univ_succ] lemma sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b lemma prod_const [comm_monoid α] (n : ℕ) (x : α) : ∏ i : fin n, x = x ^ n := by simp lemma sum_const [add_comm_monoid α] (n : ℕ) (x : α) : ∑ i : fin n, x = n • x := by simp @[to_additive] lemma prod_Ioi_zero {M : Type*} [comm_monoid M] {n : ℕ} {v : fin n.succ → M} : ∏ i in Ioi 0, v i = ∏ j : fin n, v j.succ := by rw [Ioi_zero_eq_map, finset.prod_map, rel_embedding.coe_fn_to_embedding, coe_succ_embedding] @[to_additive] lemma prod_Ioi_succ {M : Type*} [comm_monoid M] {n : ℕ} (i : fin n) (v : fin n.succ → M) : ∏ j in Ioi i.succ, v j = ∏ j in Ioi i, v j.succ := by rw [Ioi_succ, finset.prod_map, rel_embedding.coe_fn_to_embedding, coe_succ_embedding] @[to_additive] lemma prod_congr' {M : Type*} [comm_monoid M] {a b : ℕ} (f : fin b → M) (h : a = b) : ∏ (i : fin a), f (cast h i) = ∏ (i : fin b), f i := by { subst h, congr, ext, congr, ext, rw coe_cast, } @[to_additive] lemma prod_univ_add {M : Type*} [comm_monoid M] {a b : ℕ} (f : fin (a+b) → M) : ∏ (i : fin (a+b)), f i = (∏ (i : fin a), f (cast_add b i)) * ∏ (i : fin b), f (nat_add a i) := begin rw fintype.prod_equiv fin_sum_fin_equiv.symm f (λ i, f (fin_sum_fin_equiv.to_fun i)), swap, { intro x, simp only [equiv.to_fun_as_coe, equiv.apply_symm_apply], }, apply prod_on_sum, end @[to_additive] lemma prod_trunc {M : Type*} [comm_monoid M] {a b : ℕ} (f : fin (a+b) → M) (hf : ∀ (j : fin b), f (nat_add a j) = 1) : ∏ (i : fin (a+b)), f i = ∏ (i : fin a), f (cast_le (nat.le.intro rfl) i) := by simpa only [prod_univ_add, fintype.prod_eq_one _ hf, mul_one] section partial_prod variables [monoid α] {n : ℕ} /-- For `f = (a₁, ..., aₙ)` in `αⁿ`, `partial_prod f` is `(1, a₁, a₁a₂, ..., a₁...aₙ)` in `αⁿ⁺¹`. -/ @[to_additive "For `f = (a₁, ..., aₙ)` in `αⁿ`, `partial_sum f` is `(0, a₁, a₁ + a₂, ..., a₁ + ... + aₙ)` in `αⁿ⁺¹`."] def partial_prod (f : fin n → α) (i : fin (n + 1)) : α := ((list.of_fn f).take i).prod @[simp, to_additive] lemma partial_prod_zero (f : fin n → α) : partial_prod f 0 = 1 := by simp [partial_prod] @[to_additive] lemma partial_prod_succ (f : fin n → α) (j : fin n) : partial_prod f j.succ = partial_prod f j.cast_succ * (f j) := by simp [partial_prod, list.take_succ, list.of_fn_nth_val, dif_pos j.is_lt, ←option.coe_def] @[to_additive] lemma partial_prod_succ' (f : fin (n + 1) → α) (j : fin (n + 1)) : partial_prod f j.succ = f 0 * partial_prod (fin.tail f) j := by simpa [partial_prod] end partial_prod end fin namespace list section comm_monoid variables [comm_monoid α] @[to_additive] lemma prod_take_of_fn {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ ((j : ℕ) < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), ((j : ℕ) < i.succ) = ((j : ℕ) < i), { assume j, have : (j : ℕ) < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end @[to_additive] lemma prod_of_fn {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), (j : ℕ) < n := λ j, j.is_lt, simp [this] } end end comm_monoid lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.is_lt | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := by simp | (g :: h :: L) := calc g + -h + L.alternating_sum = g + -h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) • list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
0f2af685c4a12c974240d9ff984737119d766b42
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/module/prod.lean
88b0ecd9b12b439eb8faf9739767d1a25790d6bc
[ "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
2,633
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.module.basic /-! # Prod instances for module and multiplicative actions This file defines instances for binary product of modules -/ variables {R : Type*} {S : Type*} {M : Type*} {N : Type*} namespace prod instance [has_scalar R M] [has_scalar R N] : has_scalar R (M × N) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar R M] [has_scalar R N] (a : R) (x : M × N) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar R M] [has_scalar R N] (a : R) (x : M × N) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar R M] [has_scalar R N] (a : R) (b : M) (c : N) : a • (b, c) = (a • b, a • c) := rfl instance [has_scalar R S] [has_scalar S M] [has_scalar R M] [has_scalar S N] [has_scalar R N] [is_scalar_tower R S M] [is_scalar_tower R S N] : is_scalar_tower R S (M × N) := ⟨λ x y z, mk.inj_iff.mpr ⟨smul_assoc _ _ _, smul_assoc _ _ _⟩⟩ instance [has_scalar R M] [has_scalar S M] [has_scalar R N] [has_scalar S N] [smul_comm_class R S M] [smul_comm_class R S N] : smul_comm_class R S (M × N) := { smul_comm := λ r s x, mk.inj_iff.mpr ⟨smul_comm _ _ _, smul_comm _ _ _⟩ } instance {r : monoid R} [mul_action R M] [mul_action R N] : mul_action R (M × N) := { mul_smul := λ a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩ } instance {r : monoid R} [add_monoid M] [add_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] : distrib_mul_action R (M × N) := { smul_add := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, smul_zero := λ a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩ } instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : semimodule R (M × N) := { add_smul := λ a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, zero_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, .. prod.distrib_mul_action } instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [no_zero_smul_divisors R M] [no_zero_smul_divisors R N] : no_zero_smul_divisors R (M × N) := ⟨λ c ⟨x, y⟩ h, or_iff_not_imp_left.mpr (λ hc, mk.inj_iff.mpr ⟨(smul_eq_zero.mp (congr_arg fst h)).resolve_left hc, (smul_eq_zero.mp (congr_arg snd h)).resolve_left hc⟩)⟩ end prod
4dbf756aa1cf33f4b1b715aab2b78a7f59b68439
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Init/Data/Option/Instances.lean
4ada2159bca9a2e7665c6f744f67fab531b56191
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
662
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Option.Basic universes u v theorem Option.eqOfEqSome {α : Type u} : ∀ {x y : Option α}, (∀z, x = some z ↔ y = some z) → x = y | none, none, h => rfl | none, some z, h => Option.noConfusion ((h z).2 rfl) | some z, none, h => Option.noConfusion ((h z).1 rfl) | some z, some w, h => Option.noConfusion ((h w).2 rfl) (congrArg some) theorem Option.eqNoneOfIsNone {α : Type u} : ∀ {o : Option α}, o.isNone = true → o = none | none, h => rfl
e7d8ee05522e602ca737d51f77885a46de8e2929
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/free_algebra.lean
720c977291e642c44c581cc06f4cc84bd2e1af93
[ "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
1,130
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.basis import algebra.free_algebra import linear_algebra.finsupp_vector_space /-! # Linear algebra properties of `free_algebra R X` This file provides a `free_monoid X` basis on the `free_algebra R X`, and uses it to show the dimension of the algebra is the cardinality of `list X` -/ universes u v namespace free_algebra /-- The `free_monoid X` basis on the `free_algebra R X`, mapping `[x₁, x₂, ..., xₙ]` to the "monomial" `1 • x₁ * x₂ * ⋯ * xₙ` -/ @[simps] noncomputable def basis_free_monoid (R : Type u) (X : Type v) [comm_ring R] : basis (free_monoid X) R (free_algebra R X) := finsupp.basis_single_one.map (equiv_monoid_algebra_free_monoid.symm.to_linear_equiv : _ ≃ₗ[R] free_algebra R X) -- TODO: generalize to `X : Type v` lemma dim_eq {K : Type u} {X : Type (max u v)} [field K] : module.rank K (free_algebra K X) = cardinal.mk (list X) := (cardinal.lift_inj.mp (basis_free_monoid K X).mk_eq_dim).symm end free_algebra
322fb91e18a290b213f9f8b5001c6a2ca32e6077
d5ecf6c46a2f605470a4a7724909dc4b9e7350e0
/tactic/ring.lean
472ba4d5432c22d6f7b18d793281f9075755c691
[ "Apache-2.0" ]
permissive
MonoidMusician/mathlib
41f79df478987a636b735c338396813d2e8e44c4
72234ef1a050eea3a2197c23aeb345fc13c08ff3
refs/heads/master
1,583,672,205,771
1,522,892,143,000
1,522,892,143,000
128,144,032
0
0
Apache-2.0
1,522,892,144,000
1,522,890,892,000
Lean
UTF-8
Lean
false
false
17,174
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Evaluate expressions in the language of (semi-)rings. Based on http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf . -/ import algebra.group_power tactic.norm_num universes u v w open tactic def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b namespace tactic namespace ring meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) meta def mk_cache (e : expr) : tactic cache := do α ← infer_type e, c ← mk_app ``comm_semiring [α] >>= mk_instance, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, c⟩ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app meta inductive destruct_ty : Type | const : ℚ → destruct_ty | xadd : expr → expr → expr → ℕ → expr → destruct_ty open destruct_ty meta def destruct (e : expr) : option destruct_ty := match expr.to_rat e with | some n := some $ const n | none := match e with | `(horner %%a %%x %%n %%b) := do n' ← expr.to_nat n, some (xadd a x n n' b) | _ := none end end meta def normal_form_to_string : expr → string | e := match destruct e with | some (const n) := to_string n | some (xadd a x _ n b) := "(" ++ normal_form_to_string a ++ ") * (" ++ to_string x ++ ")^" ++ to_string n ++ " + " ++ normal_form_to_string b | none := to_string e end theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e meta def eval_horner (c : cache) (a x n b : expr) : tactic (expr × expr) := do d ← destruct a, match d with | const q := if q = 0 then return (b, c.cs_app ``zero_horner [x, n, b]) else refl_conv $ c.cs_app ``horner [a, x, n, b] | xadd a₁ x₁ n₁ _ b₁ := if x₁ = x ∧ b₁.to_nat = some 0 then do (n', h) ← mk_app ``has_add.add [n₁, n] >>= norm_num, return (c.cs_app ``horner [a₁, x, n', b], c.cs_app ``horner_horner [a₁, x, n₁, n, b, n', h]) else refl_conv $ c.cs_app ``horner [a, x, n, b] end theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner] theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k b') (h₁ : n₁ + k = n₂) (h₂ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner (horner a₂ x k a₁) x n₁ b' := by simp [h₂.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm] theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k b') (h₁ : n₂ + k = n₁) (h₂ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner (horner a₁ x k a₂) x n₂ b' := by simp [h₂.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm] theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm] meta def eval_add (c : cache) : expr → expr → tactic (expr × expr) | e₁ e₂ := do d₁ ← destruct e₁, d₂ ← destruct e₂, match d₁, d₂ with | const n₁, const n₂ := mk_app ``has_add.add [e₁, e₂] >>= norm_num | const k, xadd a x n _ b := if k = 0 then do p ← mk_app ``zero_add [e₂], return (e₂, p) else do (b', h) ← eval_add e₁ b, return (c.cs_app ``horner [a, x, n, b'], c.cs_app ``const_add_horner [e₁, a, x, n, b, b', h]) | xadd a x n _ b, const k := if k = 0 then do p ← mk_app ``add_zero [e₁], return (e₁, p) else do (b', h) ← eval_add b e₂, return (c.cs_app ``horner [a, x, n, b'], c.cs_app ``horner_add_const [a, x, n, b, e₂, b', h]) | xadd a₁ x₁ en₁ n₁ b₁, xadd a₂ x₂ en₂ n₂ b₂ := if expr.lex_lt x₁ x₂ then do (b', h) ← eval_add b₁ e₂, return (c.cs_app ``horner [a₁, x₁, en₁, b'], c.cs_app ``horner_add_const [a₁, x₁, en₁, b₁, e₂, b', h]) else if x₁ ≠ x₂ then do (b', h) ← eval_add e₁ b₂, return (c.cs_app ``horner [a₂, x₂, en₂, b'], c.cs_app ``const_add_horner [e₁, a₂, x₂, en₂, b₂, b', h]) else if n₁ < n₂ then do k ← expr.of_nat (expr.const `nat []) (n₂ - n₁), (_, h₁) ← mk_app ``has_add.add [en₁, k] >>= norm_num, (b', h₂) ← eval_add b₁ b₂, return (c.cs_app ``horner [c.cs_app ``horner [a₂, x₁, k, a₁], x₁, en₁, b'], c.cs_app ``horner_add_horner_lt [a₁, x₁, en₁, b₁, a₂, en₂, b₂, k, b', h₁, h₂]) else if n₁ ≠ n₂ then do k ← expr.of_nat (expr.const `nat []) (n₁ - n₂), (_, h₁) ← mk_app ``has_add.add [en₂, k] >>= norm_num, (b', h₂) ← eval_add b₁ b₂, return (c.cs_app ``horner [c.cs_app ``horner [a₁, x₁, k, a₂], x₁, en₂, b'], c.cs_app ``horner_add_horner_gt [a₁, x₁, en₁, b₁, a₂, en₂, b₂, k, b', h₁, h₂]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner c a' x₁ en₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁, en₁, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) end theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner] meta def eval_neg (c : cache) : expr → tactic (expr × expr) | e := do d ← destruct e, match d with | const _ := mk_app ``has_neg.neg [e] >>= norm_num | xadd a x n _ b := do (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← mk_app ``horner_neg [a, x, n, b, a', b', h₁, h₂], return (c.cs_app ``horner [a', x, n, b'], p) end theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] meta def eval_const_mul (c : cache) (k : expr) : expr → tactic (expr × expr) | e := do d ← destruct e, match d with | const _ := mk_app ``has_mul.mul [k, e] >>= norm_num | xadd a x n _ b := do (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (c.cs_app ``horner [a', x, n, b'], c.cs_app ``horner_const_mul [k, a, x, n, b, a', b', h₁, h₂]) end theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] meta def eval_mul (c : cache) : expr → expr → tactic (expr × expr) | e₁ e₂ := do d₁ ← destruct e₁, d₂ ← destruct e₂, match d₁, d₂ with | const n₁, const n₂ := mk_app ``has_mul.mul [e₁, e₂] >>= norm_num | const n₁, _ := if n₁ = 0 then do α0 ← expr.of_nat c.α 0, p ← mk_app ``zero_mul [e₂], return (α0, p) else if n₁ = 1 then do p ← mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul c e₁ e₂ | _, const _ := do p₁ ← mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul e₂ e₁, p ← mk_eq_trans p₁ p₂, return (e', p) | xadd a₁ x₁ en₁ n₁ b₁, xadd a₂ x₂ en₂ n₂ b₂ := if expr.lex_lt x₁ x₂ then do (a', h₁) ← eval_mul a₁ e₂, (b', h₂) ← eval_mul b₁ e₂, return (c.cs_app ``horner [a', x₁, en₁, b'], c.cs_app ``horner_mul_const [a₁, x₁, en₁, b₁, e₂, a', b', h₁, h₂]) else if x₁ ≠ x₂ then do (a', h₁) ← eval_mul e₁ a₂, (b', h₂) ← eval_mul e₁ b₂, return (c.cs_app ``horner [a', x₂, en₂, b'], c.cs_app ``horner_const_mul [e₁, a₂, x₂, en₂, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul e₁ a₂, α0 ← expr.of_nat c.α 0, (haa, h₂) ← eval_horner c aa x₁ en₂ α0, if b₂.to_nat = some 0 then do return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁, en₁, b₁, a₂, en₂, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add c haa (c.cs_app ``horner [ab, x₁, en₁, bb]), return (t, c.cs_app ``horner_mul_horner [a₁, x₁, en₁, b₁, a₂, en₂, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) end theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] meta def eval_pow (c : cache) : expr → nat → tactic (expr × expr) | e 0 := do α1 ← expr.of_nat c.α 1, p ← mk_app ``pow_zero [e], return (α1, p) | e 1 := do p ← mk_app ``pow_one [e], return (e, p) | e m := do d ← destruct e, let N : expr := expr.const `nat [], match d with | const _ := do e₂ ← expr.of_nat N m, mk_app ``monoid.pow [e, e₂] >>= norm_num.derive | xadd a x n _ b := match b.to_nat with | some 0 := do e₂ ← expr.of_nat N m, (n', h₁) ← mk_app ``has_mul.mul [n, e₂] >>= norm_num, (a', h₂) ← eval_pow a m, α0 ← expr.of_nat c.α 0, return (c.cs_app ``horner [a', x, n', α0], c.cs_app ``horner_pow [a, x, n, e₂, n', a', h₁, h₂]) | _ := do e₂ ← expr.of_nat N (m-1), l ← mk_app ``monoid.pow [e, e₂], (tl, hl) ← eval_pow e (m-1), (t, p₂) ← eval_mul c tl e, hr ← mk_eq_refl e, p₂ ← mk_app ``norm_num.subst_into_prod [l, e, tl, e, t, hl, hr, p₂], p₁ ← mk_app ``pow_succ' [e, e₂], p ← mk_eq_trans p₁ p₂, return (t, p) end end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] meta def eval_atom (c : cache) (e : expr) : tactic (expr × expr) := do α0 ← expr.of_nat c.α 0, α1 ← expr.of_nat c.α 1, n1 ← expr.of_nat (expr.const `nat []) 1, return (c.cs_app ``horner [α1, e, n1, α0], c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : (tl : α) ^ tr = t) : l ^ r = t := by simp [prl, prr, prt] meta def eval (c : cache) : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add c e₁' e₂', p ← mk_app ``norm_num.subst_into_sum [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | `(%%e₁ - %%e₂) := do e₂' ← mk_app ``has_neg.neg [e₂], mk_app ``has_add.add [e₁, e₂'] >>= eval | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg c e₁, p ← mk_app ``subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul c e₁' e₂', p ← mk_app ``norm_num.subst_into_prod [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← norm_num.derive e, e'.to_rat, return (e', p)) <|> eval_atom c e | e@`(%%e₁ / %%e₂) := do e₂' ← mk_app ``has_inv.inv [e₂], mk_app ``has_mul.mul [e₁, e₂'] >>= eval | e@`(%%e₁ ^ %%e₂) := do (e₂', p₂) ← eval e₂, match e₂'.to_nat with | none := eval_atom c e | some k := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow c e₁' k, p ← mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) end | e := match e.to_nat with | some _ := refl_conv e | none := eval_atom c e end theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a b : α) (m n) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α : Type u} [add_group α] (a b : α) : a + -b = a - b := rfl @[derive has_reflect] inductive normalize_mode | raw | SOP | horner meta def normalize (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do c ← mk_cache e, (new_e, pr) ← match mode with | normalize_mode.raw := eval c | normalize_mode.horner := trans_conv (eval c) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval c) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 : tactic unit := do `(%%e₁ = %%e₂) ← target, c ← mk_cache e₁, (e₁', p₁) ← eval c e₁, (e₂', p₂) ← eval c e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. -/ meta def ring (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := ring1 | _ := failed end <|> do ns ← loc.get_locals, tt ← tactic.replace_at (normalize SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity end interactive end tactic -- TODO(Mario): fix -- example (x : ℤ) : x^3 + x^2 + x = x^3 + (x^2 + x) := by ring
5b5bebade22219ba15748a705aa32e99dcc2dc18
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/deprecated/subring.lean
1a7f48b10ae97fe626a6bf0671bfbbf14269725b
[ "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,558
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import deprecated.subgroup import deprecated.group universes u v open group variables {R : Type u} [ring R] /-- `S` is a subring: a set containing 1 and closed under multiplication, addition and additive inverse. -/ class is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop. /-- The ring structure on a subring coerced to a type. -/ local attribute [instance] def subset.ring {S : set R} [is_subring S] : ring S := { left_distrib := λ x y z, subtype.eq $ left_distrib x.1 y.1 z.1, right_distrib := λ x y z, subtype.eq $ right_distrib x.1 y.1 z.1, .. subtype.add_comm_group, .. subtype.monoid } /-- The ring structure on a subring coerced to a type. -/ def subtype.ring {S : set R} [is_subring S] : ring (subtype S) := subset.ring namespace ring_hom instance is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] : is_subring (f ⁻¹' s) := {} instance is_subring_image {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set R) [is_subring s] : is_subring (f '' s) := {} instance is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : is_subring (set.range f) := {} end ring_hom /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def ring_hom.cod_restrict {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- Coersion `S → R` as a ring homormorphism-/ def is_subring.subtype (S : set R) [is_subring S] : S →+* R := ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ @[simp] lemma is_subring.coe_subtype {S : set R} [is_subring S] : ⇑(is_subring.subtype S) = coe := rfl variables {cR : Type u} [comm_ring cR] /-- The commutative ring structure on a subring coerced to a type. -/ def subset.comm_ring {S : set cR} [is_subring S] : comm_ring S := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subset.ring } /-- The commutative ring structure on a subring coerced to a type. -/ def subtype.comm_ring {S : set cR} [is_subring S] : comm_ring (subtype S) := subset.comm_ring /-- The integral domain structure on a subring of an integral domain coerced to a type. -/ def subring.domain {D : Type*} [integral_domain D] (S : set D) [is_subring S] : integral_domain S := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.1 zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨x, hx⟩ ⟨y, hy⟩, by { simp only [subtype.ext_iff_val, subtype.coe_mk], exact eq_zero_or_eq_zero_of_mul_eq_zero }, .. subset.comm_ring } instance is_subring.inter (S₁ S₂ : set R) [is_subring S₁] [is_subring S₂] : is_subring (S₁ ∩ S₂) := { } instance is_subring.Inter {ι : Sort*} (S : ι → set R) [h : ∀ y : ι, is_subring (S y)] : is_subring (set.Inter S) := { } lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set R) [∀ i, is_subring (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subring (⋃i, s i) := { to_is_add_subgroup := is_add_subgroup_Union_of_directed s directed, to_is_submonoid := is_submonoid_Union_of_directed s directed } namespace ring def closure (s : set R) := add_group.closure (monoid.closure s) variable {s : set R} local attribute [reducible] closure theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) : (∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) := add_group.in_closure.rec_on h (λ x hx, match x, monoid.exists_list_of_mem_closure hx with | _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩ end) ⟨[], list.forall_mem_nil _, rfl⟩ (λ b _ ih, match b, ih with | _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)), λ L2 h2, match L2, list.mem_map.1 h2 with | _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩ end, by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul]; exact list.rec_on L1 neg_zero.symm (λ hd tl ih, by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩ end) (λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with | _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩, by rw [list.map_append, list.sum_append]⟩ end) @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end instance : is_subring (closure s) := { one_mem := add_group.mem_closure is_submonoid.one_mem, mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb (λ b hb, add_group.in_closure.rec_on ha (λ a ha, add_group.subset_closure (is_submonoid.mul_mem ha hb)) ((zero_mul b).symm ▸ is_add_submonoid.zero_mem) (λ a ha hab, (neg_mul_eq_neg_mul a b) ▸ is_add_subgroup.neg_mem hab) (λ a c ha hc hab hcb, (add_mul a c b).symm ▸ is_add_submonoid.add_mem hab hcb)) ((mul_zero a).symm ▸ is_add_submonoid.zero_mem) (λ b hb hab, (neg_mul_eq_mul_neg a b) ▸ is_add_subgroup.neg_mem hab) (λ b c hb hc hab hac, (mul_add a b c).symm ▸ is_add_submonoid.add_mem hab hac), .. add_group.closure.is_add_subgroup _ } theorem mem_closure {a : R} : a ∈ s → a ∈ closure s := add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _ theorem subset_closure : s ⊆ closure s := λ _, mem_closure theorem closure_subset {t : set R} [is_subring t] : s ⊆ t → closure s ⊆ t := add_group.closure_subset ∘ monoid.closure_subset theorem closure_subset_iff (s t : set R) [is_subring t] : closure s ⊆ t ↔ s ⊆ t := (add_group.closure_subset_iff _ t).trans ⟨set.subset.trans monoid.subset_closure, monoid.closure_subset⟩ theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { rw [f.map_one], apply is_submonoid.one_mem }, { rw [f.map_neg, f.map_one], apply is_add_subgroup.neg_mem, apply is_submonoid.one_mem }, { rw [f.map_mul], apply is_submonoid.mul_mem; solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [f.map_add], apply is_add_submonoid.add_mem, assumption' }, end (closure_subset $ set.image_subset _ subset_closure) end ring
5ee892f15fc9af7301fb789cd3d2a8210da7f0c2
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/real/cardinality.lean
71d21193a0601942ca72213e8c8624217f774444
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,558
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 [countable_iff, 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
67e745e7a438682a759d9fffd9d392b9ddb76778
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/constructions/over/default.lean
d99232cb397003644b679631fa28fd69939fec58
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,322
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.constructions.over.products import Mathlib.category_theory.limits.constructions.over.connected import Mathlib.category_theory.limits.constructions.limits_of_products_and_equalizers import Mathlib.category_theory.limits.constructions.equalizers import Mathlib.PostPort universes v u namespace Mathlib /-! # Limits in the over category Declare instances for limits in the over category: If `C` has finite wide pullbacks, `over B` has finite limits, and if `C` has arbitrary wide pullbacks then `over B` has limits. -/ namespace category_theory.over /-- Make sure we can derive pullbacks in `over B`. -/ /-- Make sure we can derive equalizers in `over B`. -/ protected instance has_finite_limits {C : Type u} [category C] {B : C} [limits.has_finite_wide_pullbacks C] : limits.has_finite_limits (over B) := limits.finite_limits_from_equalizers_and_finite_products protected instance has_limits {C : Type u} [category C] {B : C} [limits.has_wide_pullbacks C] : limits.has_limits (over B) := limits.limits_from_equalizers_and_products
9d50791395a6334b683027a609656fcebd917fab
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Meta/Tactic/Util.lean
d830b380195be762baa5bed3c03e557973ebd76b
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,139
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.Basic import Lean.Meta.AppBuilder import Lean.Meta.LevelDefEq import Lean.Meta.PPGoal namespace Lean.Meta /-- Aka user name -/ def getMVarTag (mvarId : MVarId) : MetaM Name := do let mvarDecl ← getMVarDecl mvarId pure mvarDecl.userName def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do modify fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag } def appendTag (tag : Name) (suffix : Name) : Name := tag.modifyBase (. ++ suffix.eraseMacroScopes) def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do let tag ← getMVarTag mvarId setMVarTag mvarId (appendTag tag suffix) def mkFreshExprSyntheticOpaqueMVar (type : Expr) (tag : Name := Name.anonymous) : MetaM Expr := mkFreshExprMVar type MetavarKind.syntheticOpaque tag def throwTacticEx {α} (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ref := Syntax.missing) : MetaM α := throwError "tactic '{tacticName}' failed, {msg}\n{MessageData.ofGoal mvarId}" def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do if (← isExprMVarAssigned mvarId) then throwTacticEx tacticName mvarId "metavariable has already been assigned" def getMVarType (mvarId : MVarId) : MetaM Expr := do pure (← getMVarDecl mvarId).type def getMVarType' (mvarId : MVarId) : MetaM Expr := do whnf (← instantiateMVars (← getMVarDecl mvarId).type) builtin_initialize registerTraceClass `Meta.Tactic /-- Assign `mvarId` to `sorryAx` -/ def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := withMVarContext mvarId do checkNotAssigned mvarId `admit let mvarType ← getMVarType mvarId let val ← mkSorry mvarType synthetic assignExprMVar mvarId val /-- Beta reduce the metavariable type head -/ def headBetaMVarType (mvarId : MVarId) : MetaM Unit := do setMVarType mvarId (← getMVarType mvarId).headBeta /-- Collect nondependent hypotheses that are propositions. -/ def getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := withMVarContext mvarId do let mut candidates : NameHashSet := {} for localDecl in (← getLCtx) do unless localDecl.isAuxDecl do candidates ← removeDeps localDecl.type candidates match localDecl.value? with | none => pure () | some value => candidates ← removeDeps value candidates if (← isProp localDecl.type) && !localDecl.hasValue then candidates := candidates.insert localDecl.fvarId candidates ← removeDeps (← getMVarType mvarId) candidates if candidates.isEmpty then return #[] else let mut result := #[] for localDecl in (← getLCtx) do if candidates.contains localDecl.fvarId then result := result.push localDecl.fvarId return result where removeDeps (e : Expr) (candidates : NameHashSet) : MetaM NameHashSet := do let e ← instantiateMVars e let visit : StateRefT NameHashSet MetaM NameHashSet := do e.forEach fun | Expr.fvar fvarId _ => modify fun s => s.erase fvarId | _ => pure () get visit |>.run' candidates partial def saturate (mvarId : MVarId) (x : MVarId → MetaM (Option (List MVarId))) : MetaM (List MVarId) := do let (_, r) ← go mvarId |>.run #[] return r.toList where go (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := withIncRecDepth do match (← x mvarId) with | none => modify fun s => s.push mvarId | some mvarIds => mvarIds.forM go def exactlyOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM MVarId := match mvarIds with | [mvarId] => return mvarId | _ => throwError msg def ensureAtMostOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM (Option MVarId) := match mvarIds with | [] => return none | [mvarId] => return some mvarId | _ => throwError msg end Lean.Meta
7f07fbd5b0c01177df880b267739753330e6051d
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Elab/PreDefinition/Structural.lean
6bcdc4ce300451fdb63c8fc690b507f84dba1f10
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,344
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.ForEachExpr import Lean.Meta.RecursorInfo import Lean.Meta.Match.Match import Lean.Elab.PreDefinition.Basic namespace Lean.Elab open Meta private def getFixedPrefix (declName : Name) (xs : Array Expr) (value : Expr) : Nat := let visitor {ω} : StateRefT Nat (ST ω) Unit := value.forEach' fun e => if e.isAppOf declName then do let args := e.getAppArgs modify fun numFixed => if args.size < numFixed then args.size else numFixed -- we continue searching if the e's arguments are not a prefix of `xs` pure !args.isPrefixOf xs else pure true runST fun _ => do let (_, numFixed) ← visitor.run xs.size; pure numFixed structure RecArgInfo := /- `fixedParams ++ ys` are the arguments of the function we are trying to justify termination using structural recursion. -/ (fixedParams : Array Expr) (ys : Array Expr) -- recursion arguments (pos : Nat) -- position in `ys` of the argument we are recursing on (indicesPos : Array Nat) -- position in `ys` of the inductive datatype indices we are recursing on (indName : Name) -- inductive datatype name of the argument we are recursing on (indLevels : List Level) -- inductice datatype universe levels of the argument we are recursing on (indParams : Array Expr) -- inductive datatype parameters of the argument we are recursing on (indIndices : Array Expr) -- inductive datatype indices of the argument we are recursing on, it is equal to `indicesPos.map fun i => ys.get! i` (reflexive : Bool) -- true if we are recursing over a reflexive inductive datatype private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed {α} : MetaM α := throwError "structural recursion cannot be used" private partial def findRecArg {α} (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → MetaM α) : MetaM α := let rec loop (i : Nat) : MetaM α := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => loop (i+1)) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then loop (i+1) else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) then loop (i+1) else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.nparams let indIndices := indArgs.extract indInfo.nparams indArgs.size if !indIndices.all Expr.isFVar then orelseMergeErrors (throwError! "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (loop (i+1)) else if !indIndices.allDiff then orelseMergeErrors (throwError! "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (loop (i+1)) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match ← hasBadIndexDep? ys indIndices with | some (index, y) => orelseMergeErrors (throwError! "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (loop (i+1)) | none => match ← hasBadParamDep? ys indParams with | some (indParam, y) => orelseMergeErrors (throwError! "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (loop (i+1)) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelseMergeErrors (mapError (k { fixedParams := fixedParams, ys := ys, pos := i - fixedParams.size, indicesPos := indicesPos, indName := indInfo.name, indLevels := us, indParams := indParams, indIndices := indIndices, reflexive := indInfo.isReflexive }) (fun msg => msg!"argument #{i+1} was not used for structural recursion{indentD msg}")) (loop (i+1)) else throwStructuralFailed loop numFixed private def containsRecFn (recFnName : Name) (e : Expr) : Bool := (e.find? fun e => e.isConstOf recFnName).isSome private def ensureNoRecFn (recFnName : Name) (e : Expr) : MetaM Expr := do if containsRecFn recFnName e then Meta.forEachExpr e fun e => do if e.isAppOf recFnName then throwError! "unexpected occurrence of recursive application{indentExpr e}" pure e else pure e private def throwToBelowFailed {α} : MetaM α := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr → Expr → Expr → MetaM Expr | belowDict, arg, F => do let belowDict ← whnf belowDict trace[Elab.definition.structural]! "belowDict: {belowDict}, arg: {arg}" match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F])) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `And.left #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `And.right #[F])) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs unless argArgs.size >= xs.size do throwToBelowFailed let n := argArgs.size let argTailArgs := argArgs.extract (n - xs.size) n let belowDict := belowDict.replaceFVars xs argTailArgs match belowDict with | Expr.app belowDictFun belowDictArg _ => unless belowDictFun.getAppFn == C do throwToBelowFailed unless ← isDefEq belowDictArg arg do throwToBelowFailed pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict {α} (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do let belowType ← inferType below trace[Elab.definition.structural]! "belowType: {belowType}" belowType.withApp fun f args => do let motivePos := numIndParams + 1 unless motivePos < args.size do throwError! "unexpected 'below' type{indentExpr belowType}" let pre := mkAppN f (args.extract 0 numIndParams) let preType ← inferType pre forallBoundedTelescope preType (some 1) fun x _ => do let motiveType ← inferType x[0] let C ← mkFreshUserName `C withLocalDeclD C motiveType fun C => let belowDict := mkApp pre C let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size) k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat → List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below /-- Return true iff `e` contains an application `recFnName .. t ..` where the term `t` is the argument we are trying to recurse on, and it contains loose bound variables. We use this test to decide whether we should process a matcher-application as a regular applicaton or not. That is, whether we should push the `below` argument should be affected by the matcher or not. If `e` does not contain an application of the form `recFnName .. t ..`, then we know the recursion doesn't depend on any pattern variable in this matcher. -/ private def recArgHasLooseBVarsAt (recFnName : Name) (recArgInfo : RecArgInfo) (e : Expr) : Bool := let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos let app? := e.find? fun e => e.isAppOf recFnName && e.getAppNumArgs > recArgPos && (e.getArg! recArgPos).hasLooseBVars app?.isSome private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : MetaM Expr := let rec loop : Expr → Expr → MetaM Expr | below, e@(Expr.lam n d b c) => do withLocalDecl n c.binderInfo (← loop below d) fun x => do mkLambdaFVars #[x] (← loop below (b.instantiate1 x)) | below, e@(Expr.forallE n d b c) => do withLocalDecl n c.binderInfo (← loop below d) fun x => do mkForallFVars #[x] (← loop below (b.instantiate1 x)) | below, Expr.letE n type val body _ => do withLetDecl n (← loop below type) (← loop below val) fun x => do mkLetFVars #[x] (← loop below (body.instantiate1 x)) | below, Expr.mdata d e _ => do pure $ mkMData d (← loop below e) | below, Expr.proj n i e _ => do pure $ mkProj n i (← loop below e) | below, e@(Expr.app _ _ _) => do let processApp (e : Expr) : MetaM Expr := e.withApp fun f args => do if f.isConstOf recFnName then let numFixed := recArgInfo.fixedParams.size let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos if recArgPos >= args.size then throwError! "insufficient number of parameters at recursive application {indentExpr e}" let recArg := args[recArgPos] let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError! "failed to eliminate recursive application{indentExpr e}" -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let mut fArgs := #[] for i in [:argsNonFixed.size] do if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then let arg := argsNonFixed[i] let arg ← replaceRecApps recFnName recArgInfo below arg fArgs := fArgs.push arg pure $ mkAppN f fArgs else pure $ mkAppN (← loop below f) (← args.mapM (loop below)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !recArgHasLooseBVarsAt recFnName recArgInfo e then processApp e else /- Here is an example we currently not handle ``` def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 1 | _::_::zs => g zs + 1 | zs => g ys + 2 ``` We are matching on `ys`, but still using `ys` in the third alternative. If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`. To make it work, users have to write the third alternative as `| zs => g zs + 2` If this is too annoying in practice, we may replace `ys` with the matching term, but this may generate weird error messages, when it doesn't work. -/ let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg) let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do trace[Elab.definition.structural]! "altNumParams: {numParams}, xs: {xs}" unless xs.size >= numParams do throwError! "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let belowForAlt := xs[numParams - 1] mkLambdaFVars xs (← loop belowForAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | _, e => ensureNoRecFn recFnName e loop below e private def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : MetaM Expr := do let type := (← inferType value).headBeta let major := recArgInfo.ys[recArgInfo.pos] let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y let motive ← mkForallFVars otherArgs type let mut brecOnUniv ← getLevel motive trace[Elab.definition.structural]! "brecOn univ: {brecOnUniv}" let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero if recArgInfo.reflexive && brecOnUniv != levelZero then brecOnUniv ← decLevel brecOnUniv let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive trace[Elab.definition.structural]! "brecOn motive: {motive}" let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels) let brecOn := mkAppN brecOn recArgInfo.indParams let brecOn := mkApp brecOn motive let brecOn := mkAppN brecOn recArgInfo.indIndices let brecOn := mkApp brecOn major check brecOn let brecOnType ← inferType brecOn trace[Elab.definition.structural]! "brecOn {brecOn}" trace[Elab.definition.structural]! "brecOnType {brecOnType}" forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F[0] let FType ← inferType F let numIndices := recArgInfo.indIndices.size forallBoundedTelescope FType (some $ numIndices + 1 /- major -/ + 1 /- below -/ + otherArgs.size) fun Fargs _ => do let indicesNew := Fargs.extract 0 numIndices let majorNew := Fargs[numIndices] let below := Fargs[numIndices+1] let otherArgsNew := Fargs.extract (numIndices+2) Fargs.size let valueNew := value.replaceFVars recArgInfo.indIndices indicesNew let valueNew := valueNew.replaceFVar major majorNew let valueNew := valueNew.replaceFVars otherArgs otherArgsNew let valueNew ← replaceRecApps recFnName recArgInfo below valueNew let Farg ← mkLambdaFVars Fargs valueNew let brecOn := mkApp brecOn Farg pure $ mkAppN brecOn otherArgs private def elimRecursion (preDef : PreDefinition) : MetaM PreDefinition := withoutModifyingEnv do lambdaTelescope preDef.value fun xs value => do addAsAxiom preDef trace[Elab.definition.structural]! "{preDef.declName} {xs} :=\n{value}" let numFixed := getFixedPrefix preDef.declName xs value findRecArg numFixed xs fun recArgInfo => do -- when (recArgInfo.indName == `Nat) throwStructuralFailed -- HACK to skip Nat argument let valueNew ← mkBRecOn preDef.declName recArgInfo value let valueNew ← mkLambdaFVars xs valueNew trace[Elab.definition.structural]! "result: {valueNew}" -- Recursive applications may still occur in expressions that were not visited by replaceRecApps (e.g., in types) let valueNew ← ensureNoRecFn preDef.declName valueNew pure { preDef with value := valueNew } def structuralRecursion (preDefs : Array PreDefinition) : TermElabM Unit := if preDefs.size != 1 then throwError "structural recursion does not handle mutually recursive functions" else do let preDefNonRec ← elimRecursion preDefs[0] mapError (addNonRec preDefNonRec) (fun msg => msg!"structural recursion failed, produced type incorrect term{indentD msg}") addAndCompileUnsafeRec preDefs builtin_initialize registerTraceClass `Elab.definition.structural end Lean.Elab
8485e43c6ef872ddd5e656d68fec200b524da7ae
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/combinatorics/partition/fin_map.lean
20ae4b5fbf84194a3e778af49ac7e5e7b9a1d9d0
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,588
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import data.vector data.list.sort data.fintype algebra.big_operators import data.fin_extra order.sort_rank data.heq_extra data.enumeration import combinatorics.partition.basic combinatorics.stirling /- Elsewhere, we have defined a type (partition α) for any finite type α, representing the set of partitions of α. In particular, for any natural number n we have a finite type (fin n) of numbers less than n, and thus a type (partition (fin n)) of partitions. From this, we can extract a subtype of partitions of rank r (where the rank is defined to be the number of blocks). However, this is defined in a way that is not well-designed for efficient computation. The aim of this file is to define an equivalent type (fin_map n r) that has better computational properties. Specifically, an element of (fin_map n r) is essentially a structure consisting of maps b : (fin n) → (fin r) and t : (fin r) → (fin n) and proofs of three properties: that b ∘ t is the identity, that t ∘ b is everywhere greater than or equal to the identity, and that t is strictly increasing. Given any such pair, we can partition (fin n) using the fibres of the map b. It is not hard to see that each partition of rank r arises from a unique pair (b,t) in this way. The word "essentially" in the above paragraph covers the following technicality. For any type α, maps (fin k) → α biject in an obvious way with lists in α of length k. Such lists can be considered as elements of the subtype (vector α k). Lists and vectors are standard data structures that can be represented efficiently in the Lean virtual machine, especially when the entries are just natural numbers. For this reason, in the definition of (fin_map n r), we encode b and t as vectors rather than functions. -/ namespace combinatorics.partition open fin fintype combinatorics combinatorics.partition section block_max variables {n : ℕ} {p : partition (fin n)} /- As a basic ingredient of all the constructions in this file, we need to order the blocks of a given partition by declaring that b < c iff (largest element of b) < (largest element of c), and we need to sort the set of blocks according to this order. -/ /- We start with a function that extracts the largest element of each block. For this to make sense we need to know that each block is nonempty; this is proved by the lemma block_not_empty from partition.lean. -/ def block_max (b : p.block_type) : fin n := (finset_largest_element b.val (block_not_empty b.property)).val /- This defines a lemma showing that (block_max b) has the expected defining properties (it lies in b and is maximal subject to that). -/ def block_max_spec (b : p.block_type) := (finset_largest_element b.val (block_not_empty b.property)).property /- The block containing (block_max b) is just b. -/ lemma block_max_block (b : p.block_type) : b = p.block_alt (block_max b) := block_eq_of_mem (block_max_spec b).left variable (p) /- We now define our order on the set of blocks, packaging it as an instance of the linear_order typeclass. -/ instance block_order : linear_order p.block_type := { le := λ b c ,(block_max b) ≤ (block_max c), lt := λ b c ,(block_max b) < (block_max c), lt_iff_le_not_le := λ b c, @lt_iff_le_not_le (fin n) _ (block_max b) (block_max c), le_refl := λ b,le_refl (block_max b), le_trans := λ (a b c : p.block_type) (a_le_b : block_max a ≤ block_max b) (b_le_c : block_max b ≤ block_max c), le_trans a_le_b b_le_c, le_antisymm := λ (a b : p.block_type) (a_le_b : block_max a ≤ block_max b) (b_le_a : block_max b ≤ block_max a), begin have s_eq_s : block_max a = block_max b := le_antisymm a_le_b b_le_a, exact ((block_max_block a).trans (congr_arg p.block_alt s_eq_s)).trans (block_max_block b).symm, end, le_total := λ (a b : p.block_type), le_total (block_max a) (block_max b), } /- The order is decidable -/ instance block_order_dec : decidable_rel (@has_le.le p.block_type _) := λ b c, fin.decidable_le (block_max b) (block_max c) /- If the number of blocks is r, then the following function returns the unique order-equivalence from the set of blocks to (fin r). -/ def block_rank_equiv {r : ℕ} (p_rank : p.rank = r) := fintype.rank_equiv ((block_type_card p).trans p_rank) end block_max /- We now define the type (fin_map n r). The elements are structures with data fields block and top, together with three propositional fields (which will be ignored in compiled code for the Lean virtual machine). The block field is a vector of length n with entries in (fin r). This gives rise to a map (fin n) → (fin r), which is called block.nth in Lean notation. Similarly, the top field is a vector of length r with entries in (fin n), corresponding to a map top.nth : (fin r) → (fin n). -/ structure fin_map (n r : ℕ) := (block : vector (fin r) n) (top : vector (fin n) r) (block_top : ∀ j, block.nth (top.nth j) = j) (top_block : ∀ i, top.nth (block.nth i) ≥ i) (top_mono : ∀ j1 j2, j1 < j2 → top.nth j1 < top.nth j2) /- -------------------------------------------------------------- -/ /- -------------------------------------------------------------- -/ /- -------------------------------------------------------------- -/ /- -------------------------------------------------------------- -/ namespace fin_map open fin_map def tot (n : ℕ) := Σ (r : ℕ), fin_map n r def to_tot {n r : ℕ} (p : fin_map n r) : tot n := ⟨r,p⟩ variables {n r : ℕ} /- The next definition tells Lean how to convert a term of type `(fin_map n r)` to a string, for display to the user. Lean already knows how to display terms of type `(fin r)`, and also knows a rule for how to display lists if it already knows how to display each entry. If `p` is of type `(fin_map n r)` then `p.block` is a vector and so `p.block.val` is a list. We tell Lean to use the string representation of `p.block.val` as a representation for `p` itself. (Lemma `eq_of_block_eq` below will verify that `p.block.val` determines all of `p`.) -/ instance (n r : ℕ) : has_repr (fin_map n r) := ⟨λ p, repr p.block.val⟩ /- One of our axioms is that the map top : (fin r) → (fin n) should preserve strict inequalities. We now prove the obvious consequence that it also preserves weak inequalities. -/ lemma top_mono_weak (p : fin_map n r) (j1 j2 : fin r) : j1 ≤ j2 → p.top.nth j1 ≤ p.top.nth j2 := begin by_cases e : j1 = j2, {rw[e],intro,exact le_refl _,}, {intro j1_le_j2, exact le_of_lt (p.top_mono j1 j2 (lt_of_le_of_ne j1_le_j2 e)), } end lemma top_mono_iff (p : fin_map n r) (j1 j2 : fin r) : j1 < j2 ↔ p.top.nth j1 < p.top.nth j2 := begin split, {exact top_mono p j1 j2}, {intro top_lt, by_cases h : j1 < j2, {exact h}, {exfalso, let top_ge := top_mono_weak p j2 j1 (le_of_not_lt h), exact not_lt_of_ge top_ge top_lt, } } end @[extensionality] lemma eq_of_block_eq (p1 p2 : fin_map n r) (e_block : ∀ i, p1.block.nth i = p2.block.nth i) : p1 = p2 := begin rcases p1, rcases p2, simp at e_block, have e_block1 : p1_block = p2_block := vector.ext e_block, have e_top : ∀ j, p1_top.nth j = p2_top.nth j := begin intro j, let h0 := (congr_arg p1_top.nth ((e_block (p2_top.nth j)).trans (p2_block_top j))).subst (p1_top_block (p2_top.nth j)), let h1 := (congr_arg p2_top.nth ((e_block (p1_top.nth j)).symm.trans (p1_block_top j))).subst (p2_top_block (p1_top.nth j)), exact le_antisymm h1 h0, end, have e_top1 : p1_top = p2_top := vector.ext e_top, simp[e_block1,e_top1], end /- This function converts an element of (fin_map n r) to the corresponding partition of the set (fin n). -/ def to_partition (p : fin_map n r) : partition (fin n) := partition.fiber_partition p.block.nth lemma to_partition_top (p : fin_map n r) (i : fin n) : block_max ((to_partition p).block_alt i) = p.top.nth (p.block.nth i) := begin let q := to_partition p, let b := q.block_alt i, have i_in_b : i ∈ b.val := partition.mem_block _ i, let j := p.block.nth i, let i1 := p.top.nth j, have i_blocks0 : p.block.nth i1 = j := p.block_top j, have i_blocks1 : q.block_alt i1 = b := (partition.fiber_partition_blocks_alt p.block.nth i1 i).mpr i_blocks0, have i_blocks2 : q.block i1 = b.val := partition.block_veq_of_eq i_blocks1, have i1_in_b : i1 ∈ b.val := i_blocks2.subst (partition.mem_block q i1), let m := block_max b, let m_in_b : m ∈ b.val := (block_max_spec b).left, let i1_le_m : i1 ≤ m := (block_max_spec b).right i1 i1_in_b, have m_block : b = q.block_alt m := partition.block_eq_of_mem m_in_b, let h0 := (congr_arg p.top.nth ((partition.fiber_partition_blocks_alt p.block.nth i1 m).mp (i_blocks1.trans m_block))), let h1 := p.top_block m, let h2 := h0.symm.trans (congr_arg p.top.nth i_blocks0), let m_le_i1 : m ≤ i1 := h2.subst h1, exact le_antisymm m_le_i1 i1_le_m, end /- Given an element of (fin_map n r), the above definition gives us a partition of (fin n), and thus a set of blocks. The next definition gives a bijection from that block set to (fin r). This bijection is packaged using the framework set up in the standard library file data.equiv.lean, so we have a structure involving maps to_fun and inv_fun together with proofs (named left_inv and right_inv) that their composites are equal (pointwise) to identity functions. -/ def to_partition_blocks (p : fin_map n r) : (to_partition p).block_type ≃ fin r := begin let q := (to_partition p), let to_fun : q.block_type → fin r := λ b, p.block.nth (block_max b), let inv_fun : fin r → q.block_type := λ j, q.block_alt (p.top.nth j), have left_inv : ∀ b, inv_fun (to_fun b) = b := begin intro b, let i1 := block_max b, let j1 := p.block.nth i1, let i2 := p.top.nth j1, let e : p.block.nth i2 = p.block.nth i1 := p.block_top j1, let h0 : q.block_alt i1 = q.block_alt i2 := subtype.eq ((partition.fiber_partition_blocks p.block.nth i1 i2).mpr e.symm), let h1 : b = q.block_alt i1 := block_max_block b, exact (h1.trans h0).symm end, have right_inv : ∀ j, to_fun (inv_fun j) = j := begin intro j, let i1 := p.top.nth j, let b := q.block_alt i1, have i1_in_b : i1 ∈ b.val := q.mem_block i1, let i2 := block_max b, let h0 := block_max_spec b, have i2_in_b : i2 ∈ b.val := h0.left, have i1_le_i2 : i1 ≤ i2 := h0.right i1 i1_in_b, have i2_block : q.block i1 = q.block i2 := partition.block_alt_eq.mpr (block_max_block b), let h1 : p.block.nth i1 = p.block.nth i2 := (partition.fiber_partition_blocks p.block.nth i1 i2).mp i2_block, let h2 : p.block.nth i1 = j := p.block_top j, let h3 : j = p.block.nth i2 := h2.symm.trans h1, let h4 : p.top.nth (p.block.nth i2) = i1 := (congr_arg p.top.nth h3).symm, let h5 : p.top.nth (p.block.nth i2) ≥ i2 := (p.top_block i2), let i1_ge_i2 : i1 ≥ i2 := h4.subst h5, let i1_eq_i2 := le_antisymm i1_le_i2 i1_ge_i2, have h6 : to_fun (inv_fun j) = p.block.nth i2 := rfl, exact (h6.trans (congr_arg p.block.nth i1_eq_i2.symm)).trans h2, end, exact ⟨to_fun,inv_fun,left_inv,right_inv⟩ end /- From the above bijection it is clear that the relevant partition of (fin n) has rank r. -/ lemma to_partition_rank (p : fin_map n r) : (to_partition p).rank = r := begin let q := to_partition p, let e0 := (partition.block_type_card q).symm, let e1 := fintype.card_congr (to_partition_blocks p), let e2 := fintype.card_fin r, exact e0.trans (e1.trans e2) end lemma to_partition_block_type_card (p : fin_map n r) : fintype.card (to_partition p).block_type = r := (partition.block_type_card (to_partition p)).trans (to_partition_rank p) lemma to_partition_blocks_ordered (p : fin_map n r) (j1 j2 : fin r) : j1 < j2 ↔ (to_partition_blocks p).inv_fun j1 < (to_partition_blocks p).inv_fun j2 := begin let q := to_partition p, let i1 := p.top.nth j1, let i2 := p.top.nth j2, let b1 := q.block_alt i1, let b2 := q.block_alt i2, let max1 : block_max b1 = i1 := (to_partition_top p i1).trans (congr_arg p.top.nth (p.block_top j1)), let max2 : block_max b2 = i2 := (to_partition_top p i2).trans (congr_arg p.top.nth (p.block_top j2)), let h : j1 < j2 ↔ i1 < i2 := top_mono_iff p j1 j2, rw[max1.symm,max2.symm] at h, exact h, end lemma to_partition_blocks_ordered_alt (p : fin_map n r) (b1 b2 : (to_partition p).block_type) : b1 < b2 ↔ (to_partition_blocks p).to_fun b1 < (to_partition_blocks p).to_fun b2 := begin let j1 := (to_partition_blocks p).to_fun b1, let j2 := (to_partition_blocks p).to_fun b2, let h := (to_partition_blocks_ordered p j1 j2).symm, rw[(to_partition_blocks p).left_inv] at h, rw[(to_partition_blocks p).left_inv] at h, exact h, end lemma block_rank_equiv_eq (p : fin_map n r) : (block_rank_equiv (to_partition p) (to_partition_rank p)) = (to_partition_blocks p) := begin let q := to_partition p, let f := block_rank_equiv q (to_partition_rank p), let g := to_partition_blocks p, let h : fin r → fin r := λ j, f.to_fun (g.inv_fun j), have h_mono : ∀ j1 j2, j1 < j2 → (h j1) < (h j2) := begin intros j1 j2 j1_lt_j2, let r0 : g.inv_fun j1 < g.inv_fun j2 := (to_partition_blocks_ordered p j1 j2).mp j1_lt_j2, exact (@fintype.rank_lt q.block_type _ _ _ r (to_partition_block_type_card p) (g.inv_fun j1) (g.inv_fun j2)).mp r0, end, have h_id : ∀ j, h j = j := fin.rigid h_mono, ext b, exact (congr_arg f.to_fun (g.left_inv b)).symm.trans (h_id (g.to_fun b)), end /- This function accepts a partition of (fin n) of rank r and produces the corresponding element of (fin_map n r). -/ def of_partition (q : partition (fin n)) (e : q.rank = r) : fin_map n r := begin let r0 := fintype.card q.block_type, have e0 : r0 = r := q.block_type_card.trans e, let f := block_rank_equiv q e, let block_map : fin n → fin r := λ i, f.to_fun (q.block_alt i), let top_map : fin r → fin n := λ j, block_max (f.inv_fun j), let block_vec := vector.of_fn block_map, let top_vec := vector.of_fn top_map, have block_top : ∀ j, block_vec.nth (top_vec.nth j) = j := begin intro j,dsimp[block_vec,top_vec], simp only [vector.nth_of_fn top_map,vector.nth_of_fn block_map], dsimp[top_map,block_map], let h0 := (block_max_block (f.inv_fun j)).symm, rw[h0], exact f.right_inv j, end, have top_block : ∀ i, top_vec.nth (block_vec.nth i) ≥ i := begin intro i,dsimp[top_vec,block_vec], simp only [vector.nth_of_fn top_map,vector.nth_of_fn block_map], dsimp[top_map,block_map], let h0 := f.left_inv (q.block_alt i), rw[h0], let h1 := (block_max_spec (q.block_alt i)).right i (partition.mem_block q i), exact h1, end, have top_mono : ∀ j1 j2, j1 < j2 → top_vec.nth j1 < top_vec.nth j2 := begin intros j1 j2 j1_lt_j2, simp only[top_vec,vector.nth_of_fn,top_map], exact (@fintype.seq_lt q.block_type (combinatorics.partition.block_order q) _ _ r e0 j1 j2).mp j1_lt_j2, end, exact { block := block_vec, top := top_vec, block_top := block_top, top_block := top_block, top_mono := top_mono }, end lemma of_partition_block (q : partition (fin n)) (e : q.rank = r) (i : fin n) : ((of_partition q e).block.nth i) = ((block_rank_equiv q e).to_fun (q.block_alt i)) := begin cases e, simp[of_partition], end lemma of_partition_to_partition (p : fin_map n r) : of_partition (to_partition p) (to_partition_rank p) = p := begin ext i, simp[of_partition], rw[block_rank_equiv_eq p], dsimp[to_partition_blocks], rw[to_partition_top p i,p.block_top (p.block.nth i)] end lemma to_partition_of_partition (q : partition (fin n)) (e : q.rank = r) : to_partition (of_partition q e) = q := begin let p := of_partition q e, let r := to_partition p, ext i1 i2, let b1 := q.block_alt i1, let b2 := q.block_alt i2, let j1 := p.block.nth i1, let j2 := p.block.nth i2, have h0 : i2 ∈ r.block i1 ↔ j2 = j1 := begin let h1 := partition.fiber_partition_blocks p.block.nth i2 i1, split; intro h2, { have h3 : i2 ∈ (r.block_alt i1).val := h2, exact h1.mp (partition.block_val_eq_of_mem h3).symm, },{ exact (h1.mpr h2).subst (partition.mem_block r i2), } end, rw[h0], have h1 : i2 ∈ q.block i1 ↔ b2 = b1 := begin split, {intro i2_in_b1, let i2_in_b1_alt : i2 ∈ b1.val := i2_in_b1, exact (partition.block_eq_of_mem i2_in_b1_alt).symm, },{ intro b2_eq_b1, exact (partition.block_veq_of_eq b2_eq_b1).subst (partition.mem_block q i2), } end, rw[h1], let f := block_rank_equiv q e, have e1a : j1 = f.to_fun b1 := of_partition_block q e i1, have e2a : j2 = f.to_fun b2 := of_partition_block q e i2, have e1b : b1 = f.inv_fun j1 := ((congr_arg f.inv_fun e1a).trans (f.left_inv b1)).symm, have e2b : b2 = f.inv_fun j2 := ((congr_arg f.inv_fun e2a).trans (f.left_inv b2)).symm, split, {intro j1_eq_j2,rw[e1b,e2b,j1_eq_j2],}, {intro b1_eq_b2,rw[e1a,e2a,b1_eq_b2],}, end def partition_equiv : (fin_map n r) ≃ { q : partition (fin n) // q.rank = r} := { to_fun := λ p, ⟨to_partition p,to_partition_rank p⟩, inv_fun := λ q, of_partition q.val q.property, left_inv := λ p, of_partition_to_partition p, right_inv := begin intro q, cases q, exact subtype.eq (to_partition_of_partition q_val q_property), end } def partition_equiv_tot : tot n ≃ partition (fin n) := { to_fun := λ rp, to_partition rp.2, inv_fun := λ q, ⟨q.rank,@of_partition n q.rank q rfl⟩, right_inv := λ q, @to_partition_of_partition n q.rank q rfl, left_inv := begin intro rp,cases rp with r p, let q := @to_partition n r p, let r_eq := to_partition_rank p, let p_eq := of_partition_to_partition p, let C : ∀ (r1 : ℕ) (u1 : q.rank = r1), Prop := λ r1 u1, @of_partition n q.rank q rfl == @of_partition n r1 q u1, let c : C q.rank rfl := by simp[C], simp[r_eq,p_eq], exact (@eq.dcases_on ℕ q.rank C r r_eq c).trans (heq_of_eq p_eq), end } /- A convenience function for manipulating vectors. -/ def bump {p q : ℕ} (v : vector (fin p) q) : vector (fin p.succ) q.succ := vector.cons (0 : fin p.succ) (vector.map fin.succ v) /- Three obvious lemmas about vectors and the corresponding functions. -/ lemma vector.zth {α : Type*} {n : ℕ} (a : α) (v : vector α n) (h : 0 < n.succ) : (vector.cons a v).nth ⟨0,h⟩ = a := vector.nth_cons_zero a v lemma vector.sth {α : Type*} {n : ℕ} (a : α) (v : vector α n) (i0 : ℕ) (h0 : i0 < n) (h1 : i0.succ < n.succ): (vector.cons a v).nth ⟨i0.succ,h1⟩ = v.nth ⟨i0,h0⟩ := vector.nth_cons_succ a v ⟨i0,h0⟩ lemma vector.nth_map {α β : Type*} (f : α → β) {n : ℕ} (v : vector α n) (i : fin n) : (vector.map f v).nth i = f (v.nth i) := begin cases v,cases i, dsimp[vector.map,vector.nth], apply list.nth_le_map end /- Suppose that p is a partition of (fin n), of rank r. We can then produce a partition of (fin (n + 1)) of rank r + 1, as follows: we take 0 as a block on its own, and then shift all the blocks of p up by one. The resulting partition is called (add p). -/ def add (p : fin_map n r) : fin_map n.succ r.succ := begin let block := bump p.block, let top := bump p.top, have block_top : ∀ j, block.nth (top.nth j) = j := begin intro j,cases j,cases j_val with j0_val; dsimp[block,top,bump], {simp[vector.zth],refl}, { have j0_is_lt : j0_val < r := nat.lt_of_succ_lt_succ j_is_lt, let j0 : fin r := ⟨j0_val,j0_is_lt⟩, simp [vector.sth _ _ j0_val j0_is_lt,vector.nth_map,p.block_top j0,fin.succ], } end, have top_block : ∀ i, top.nth (block.nth i) ≥ i := begin intro i,cases i,cases i_val with i0_val; dsimp[block,top,bump], {simp[vector.zth],exact le_refl 0,}, { have i0_is_lt : i0_val < n := nat.lt_of_succ_lt_succ i_is_lt, let i0 : fin n := ⟨i0_val,i0_is_lt⟩, simp[vector.sth _ _ i0_val i0_is_lt,vector.nth_map], exact fin.succ_le_succ (p.top_block i0), } end, have top_mono : ∀ j1 j2, j1 < j2 → top.nth j1 < top.nth j2 := begin intros j1 j2 j1_lt_j2, cases j2,cases j2_val with j20_val, {exact false.elim (nat.not_lt_zero j1.val j1_lt_j2),}, {have j20_is_lt : j20_val < r := nat.lt_of_succ_lt_succ j2_is_lt, cases j1,cases j1_val with j10_val, {simp[top,bump,vector.zth,vector.sth _ _ j20_val j20_is_lt,vector.nth_map,fin.zero_lt_succ],}, {have j10_is_lt : j10_val < r := nat.lt_of_succ_lt_succ j1_is_lt, simp[top,bump, vector.sth _ _ j10_val j10_is_lt, vector.sth _ _ j20_val j20_is_lt, vector.nth_map], apply fin.succ_lt_succ,apply p.top_mono, exact fin.lt_of_succ_lt_succ j1_lt_j2, } } end, exact ⟨block,top,block_top,top_block,top_mono⟩ end /- Suppose that p is a partition of (fin n), of rank r, and that u is in (fin r). We can then produce a partition of (fin (n + 1)) of rank r, as follows: we shift all the blocks of p up by one, and then add 0 as an extra element in the u'th block. The resulting partition is called (join p u). -/ def join (p : fin_map n r) (u : fin r) : fin_map n.succ r := begin let block := vector.cons u p.block, let top := vector.map fin.succ p.top, have block_top : ∀ j, block.nth (top.nth j) = j := begin intro j,dsimp[top,block], simp[vector.nth_map,p.block_top j], end, have top_block : ∀ i, top.nth (block.nth i) ≥ i := begin intro i, cases i, cases i_val with i0_val, {simp[vector.zth],exact fin.zero_le _,}, {have i0_is_lt : i0_val < n := nat.lt_of_succ_lt_succ i_is_lt, let h0 := fin.succ_le_succ (p.top_block ⟨i0_val,i0_is_lt⟩), dsimp[block,top], simp[vector.sth _ _ i0_val i0_is_lt,vector.nth_map], exact h0, } end, have top_mono : ∀ j1 j2, j1 < j2 → top.nth j1 < top.nth j2 := begin intros j1 j2 j1_lt_j2, simp[top,vector.nth_map], exact fin.succ_lt_succ (p.top_mono j1 j2 j1_lt_j2), end, exact ⟨block,top,block_top,top_block,top_mono⟩ end def add_cond (q : fin_map n.succ r.succ) := (q.top.nth 0 = 0) def join_cond (q : fin_map n.succ r.succ) := (q.top.nth 0 ≠ 0) lemma add_add_cond (p : fin_map n r) : add_cond (add p) := begin dsimp[add_cond,add,bump], exact vector.zth 0 _ _, end lemma join_join_cond (p : fin_map n r.succ) (u : fin r.succ) : join_cond (join p u) := begin intro e, exact fin.zero_ne_succ (e.symm.trans (vector.nth_map fin.succ p.top 0)), end /- Let q be a partition of (fin (n + 1)), with rank r + 1. Suppose also that the map q.top.nth : (fin (r + 1)) → (fin (n + 1)) sends 0 to 0. It is then not hard to see that there is a unique p in (fin_map n r) with (add p) = q. The present function produces this p. -/ def add_res (q : fin_map n.succ r.succ) (e : add_cond q) : {p : fin_map n r // q = add p} := begin let block_map_aux : ∀ (i0 : fin n), { j0 : fin r // j0.succ = q.block.nth i0.succ } := begin dsimp[add_cond] at e, intro i0, let j := q.block.nth i0.succ, by_cases e1 : j = 0, {exfalso, let h0 : i0.succ ≤ q.top.nth j := q.top_block i0.succ, let h1 : 0 < q.top.nth j := @lt_of_lt_of_le (fin n.succ) _ 0 i0.succ _ fin.zero_lt_succ h0, rw[e1,e] at h1,exact fin.not_lt_zero (0 : fin n.succ) h1, },{ exact ⟨ fin.pred j e1, fin.succ_pred j e1⟩, } end, let block_map := λ i0, (block_map_aux i0).val, let block_map_spec : ∀ i0, (block_map i0).succ = q.block.nth i0.succ := λ i0,(block_map_aux i0).property, let top_map_aux : ∀ (j0 : fin r), { i0 : fin n // i0.succ = q.top.nth j0.succ }:= begin dsimp[add_cond] at e, intro j0, let i := q.top.nth j0.succ, let e1 := (ne_of_lt (q.top_mono 0 j0.succ fin.zero_lt_succ)).symm, rw[e] at e1, exact ⟨fin.pred i e1, fin.succ_pred i e1⟩ end, let top_map := λ j0, (top_map_aux j0).val, let top_map_spec : ∀ j0, (top_map j0).succ = q.top.nth j0.succ := λ j0,(top_map_aux j0).property, let block_vec := vector.of_fn block_map, let top_vec := vector.of_fn top_map, have block_top : ∀ j0, block_vec.nth (top_vec.nth j0) = j0 := begin intro j0, dsimp[block_vec,top_vec], simp[vector.nth_of_fn], apply fin.succ_inj, let h0 := block_map_spec (top_map j0), let h1 := congr_arg q.block.nth (top_map_spec j0), let h2 := q.block_top j0.succ, let h3 := h0.trans (h1.trans h2), exact h3, end, have top_block : ∀ i0, top_vec.nth (block_vec.nth i0) ≥ i0 := begin intro i0, dsimp[block_vec,top_vec], simp[vector.nth_of_fn], apply fin.le_of_succ_le_succ, let h0 := top_map_spec (block_map i0), let h1 := congr_arg q.top.nth (block_map_spec i0), let h2 : i0.succ ≤ q.top.nth (q.block.nth i0.succ) := (q.top_block i0.succ), let h3 := (h0.trans h1).symm.subst h2, exact h3, end, have top_mono : ∀ j10 j20, j10 < j20 → top_vec.nth j10 < top_vec.nth j20 := begin intros j10 j20 j10_lt_j20, dsimp[block_vec,top_vec], simp[vector.nth_of_fn], apply fin.lt_of_succ_lt_succ,rw[top_map_spec,top_map_spec], exact q.top_mono j10.succ j20.succ (fin.succ_lt_succ j10_lt_j20), end, let p : fin_map n r := ⟨block_vec,top_vec,block_top,top_block,top_mono⟩, have eq : q = add p := begin ext i,cases i, cases i_val with i0_val, { exact ((congr_arg q.block.nth e).symm.trans (q.block_top 0)).trans (vector.zth 0 (vector.map fin.succ block_vec) i_is_lt).symm, },{ dsimp[add,p,bump], let i0_is_lt := nat.lt_of_succ_lt_succ i_is_lt, exact (((vector.sth 0 (vector.map fin.succ block_vec) i0_val i0_is_lt i_is_lt).trans (vector.nth_map fin.succ block_vec ⟨i0_val,i0_is_lt⟩)).trans ((congr_arg fin.succ (vector.nth_of_fn block_map ⟨i0_val,i0_is_lt⟩)).trans (block_map_spec ⟨i0_val,i0_is_lt⟩))).symm, } end, exact ⟨p,eq⟩, end lemma res_add (p : fin_map n r) (e : add_cond (add p)) : (add_res (add p) e) = ⟨p,rfl⟩ := begin apply subtype.eq, ext i, have h0 : (add p).block.nth i.succ = (p.block.nth i).succ := by simp[add,bump,vector.nth_map], have h1 : (add p).block.nth i.succ ≠ 0 := λ h2, fin.zero_ne_succ (h2.symm.trans h0), simp[add,add_res,e,h1,bump,vector.nth_map], end /- Let q be a partition of (fin (n + 1)), with rank r + 1. Suppose also that the map q.top.nth : (fin (r + 1)) → (fin (n + 1)) does not send 0 to 0. It is then not hard to see that there is a unique p in (fin_map n (r + 1)) and u in (fin (r + 1)) with (join p u) = q. The present function produces this p and u. -/ def join_res (q : fin_map n.succ r.succ) (e : q.top.nth 0 ≠ 0) : { pu : (fin_map n r.succ) × (fin r.succ) // q = (join pu.1 pu.2) } := begin have e0 : 0 < q.top.nth 0 := lt_of_le_of_ne (fin.zero_le (q.top.nth 0)) e.symm, let block_map : fin n → fin r.succ := λ i0, q.block.nth i0.succ, let top_map_aux : ∀ (j : fin r.succ), { i0 : fin n // i0.succ = q.top.nth j }:= begin intro j, let i := q.top.nth j, let e1 : 0 < q.top.nth j := lt_of_lt_of_le e0 (top_mono_weak q 0 j (fin.zero_le j)), let e2 := (ne_of_lt e1).symm, exact ⟨fin.pred i e2, fin.succ_pred i e2⟩ end, let top_map := λ j, (top_map_aux j).val, let top_map_spec : ∀ j, (top_map j).succ = q.top.nth j := λ j,(top_map_aux j).property, let block_vec := vector.of_fn block_map, let top_vec := vector.of_fn top_map, have block_top : ∀ j, block_vec.nth (top_vec.nth j) = j := begin intro j, dsimp[block_vec,top_vec], simp[vector.nth_of_fn,block_map], exact q.block_top j, end, have top_block : ∀ i0, top_vec.nth (block_vec.nth i0) ≥ i0 := begin intro i0, dsimp[block_vec,top_vec], simp[vector.nth_of_fn,block_map], apply fin.le_of_succ_le_succ, rw[top_map_spec], exact q.top_block i0.succ, end, have top_mono : ∀ j1 j2, j1 < j2 → top_vec.nth j1 < top_vec.nth j2 := begin intros j1 j2 j1_lt_j2, dsimp[block_vec,top_vec], simp[vector.nth_of_fn], apply fin.lt_of_succ_lt_succ,rw[top_map_spec,top_map_spec], exact q.top_mono j1 j2 j1_lt_j2, end, let p : fin_map n r.succ := ⟨block_vec,top_vec,block_top,top_block,top_mono⟩, let u : fin r.succ := q.block.nth 0, have eq : q = join p u := begin ext i,cases i, cases i_val with i0_val, {exact (vector.zth u block_vec i_is_lt).symm,}, { let i0_is_lt := nat.lt_of_succ_lt_succ i_is_lt, exact (vector.nth_of_fn block_map ⟨i0_val,i0_is_lt⟩).symm.trans (vector.sth u block_vec i0_val i0_is_lt i_is_lt).symm, } end, exact ⟨⟨p,u⟩,eq⟩, end lemma res_join (p : fin_map n r.succ) (u : fin r.succ) (e : join_cond (join p u)) : (join_res (join p u) e) = ⟨⟨p,u⟩,rfl⟩ := begin apply subtype.eq, ext i; simp[join_res,join], end variables (n r) def empty : (fin_map 0 0) := { block := vector.nil, top := vector.nil, block_top := begin intro i, exact fin.elim0 i, end, top_block := begin intro j, exact fin.elim0 j, end, top_mono := begin intros j1 j2, exact fin.elim0 j1, end, } end fin_map /- -------------------------------------------------------------- -/ /- -------------------------------------------------------------- -/ /- -------------------------------------------------------------- -/ /- -------------------------------------------------------------- -/ @[derive decidable_eq] inductive fin_ind_partition : ℕ → ℕ → Type | empty : (fin_ind_partition 0 0) | add : ∀ {n r : ℕ}, (fin_ind_partition n r) → (fin_ind_partition n.succ r.succ) | join : ∀ {n r : ℕ}, (fin_ind_partition n r) → (fin r) → (fin_ind_partition n.succ r) namespace fin_ind_partition def tot (n : ℕ) := Σ (r : ℕ), fin_ind_partition n r def to_tot {n r : ℕ} (p : fin_ind_partition n r) : tot n := ⟨r,p⟩ private def repr_aux : ∀{n r : ℕ}, (fin_ind_partition n r) → string | 0 0 empty := "O" | _ _ (add p) := "A" ++ (repr_aux p) | _ _ (join p u) := "J" ++ (repr u) ++ (repr_aux p) instance (n r : ℕ) : has_repr (fin_ind_partition n r) := ⟨@repr_aux n r⟩ lemma rank_bound : ∀ {n r : ℕ} (p : fin_ind_partition n r), r ≤ n | 0 0 empty := le_refl 0 | _ _ (@add n r p) := nat.succ_le_succ (rank_bound p) | _ _ (@join n r p u) := le_trans (rank_bound p) (nat.le_succ n) def to_map_partition : ∀ {n r : ℕ} (p : fin_ind_partition n r), fin_map n r | 0 0 empty := fin_map.empty | _ _ (add p) := fin_map.add (to_map_partition p) | _ _ (join p u) := fin_map.join (to_map_partition p) u def of_map_partition : ∀ {n r : ℕ} (q : fin_map n r), fin_ind_partition n r := begin intro n, induction n with n0 ih_n; intros r q; cases r with r0, {exact empty,}, {exact fin.elim0 (q.top.nth 0),}, {exact fin.elim0 (q.block.nth 0),}, { by_cases h : q.top.nth 0 = 0, {exact add (ih_n (fin_map.add_res q h).val),}, { let pr := (fin_map.join_res q h).val, exact join (ih_n pr.1) pr.2, } } end lemma of_add {n r : ℕ} (q : fin_map n r) : of_map_partition q.add = (of_map_partition q).add := begin have h0 : q.add.top.nth 0 = 0 := fin_map.add_add_cond q, let h1 := q.res_add h0, simp[of_map_partition,h0,h1] end lemma of_join {n r : ℕ} (q : fin_map n r) (u : fin r) : of_map_partition (q.join u) = (of_map_partition q).join u := begin cases r with r0, {exact fin.elim0 u,}, { have h0 : (q.join u).top.nth 0 ≠ 0 := fin_map.join_join_cond q u, let h1 := q.res_join u h0, simp[of_map_partition,h0,h1], } end lemma of_to_map_partition : ∀ {n r : ℕ} (p : fin_ind_partition n r), of_map_partition (to_map_partition p) = p | 0 0 empty := rfl | _ _ (@add n r p) := (of_add (to_map_partition p)).trans (congr_arg add (of_to_map_partition p)) | _ _ (@join n r p u) := (of_join (to_map_partition p) u).trans (congr_fun (congr_arg join (of_to_map_partition p)) u) lemma to_of_map_partition : ∀ {n r : ℕ} (q : fin_map n r), to_map_partition (of_map_partition q) = q | 0 0 q := by {ext i, exact fin.elim0 i,} | 0 (nat.succ r) q := fin.elim0 (q.top.nth fin.has_zero.zero) | (nat.succ n) 0 q := fin.elim0 (q.block.nth fin.has_zero.zero) | (nat.succ n) (nat.succ r) q := begin by_cases h : q.top.nth 0 = 0, { let q0e0 := fin_map.add_res q h, let q0 := q0e0.val, let e0 : q = q0.add := q0e0.property, exact calc to_map_partition (of_map_partition q) = to_map_partition (of_map_partition q0.add) : by rw[← e0] ... = to_map_partition (of_map_partition q0).add : by rw[of_add q0] ... = (to_map_partition (of_map_partition q0)).add : rfl ... = q0.add : by rw[to_of_map_partition q0] ... = q : by rw[e0], },{ let q0ue0 := fin_map.join_res q h, let q0 := q0ue0.val.1, let u := q0ue0.val.2, let e0 : q = q0.join u := q0ue0.property, exact calc to_map_partition (of_map_partition q) = to_map_partition (of_map_partition (q0.join u)) : by rw[← e0] ... = to_map_partition ((of_map_partition q0).join u) : by rw[of_join q0 u] ... = (to_map_partition (of_map_partition q0)).join u : rfl ... = q0.join u : by rw[to_of_map_partition q0] ... = q : by rw[e0], } end def map_equiv (n r : ℕ) : fin_ind_partition n r ≃ fin_map n r := { to_fun := @to_map_partition n r, inv_fun := @of_map_partition n r, left_inv := @of_to_map_partition n r, right_inv := @to_of_map_partition n r } private def tot_to_fun {n : ℕ} : fin_ind_partition.tot n → fin_map.tot n | ⟨r,p⟩ := ⟨r,(map_equiv n r).to_fun p⟩ private def tot_inv_fun {n : ℕ} : fin_map.tot n → fin_ind_partition.tot n | ⟨r,q⟩ := ⟨r,(map_equiv n r).inv_fun q⟩ private def tot_left_inv {n : ℕ} : ∀ rp : fin_ind_partition.tot n, tot_inv_fun (tot_to_fun rp) = rp | ⟨r,p⟩ := by { simp[tot_inv_fun,tot_to_fun,(map_equiv n r).left_inv p] } private def tot_right_inv {n : ℕ} : ∀ rq : fin_map.tot n, tot_to_fun (tot_inv_fun rq) = rq | ⟨r,q⟩ := by { simp[tot_inv_fun,tot_to_fun,(map_equiv n r).right_inv q] } def map_equiv_tot (n : ℕ) : fin_ind_partition.tot n ≃ fin_map.tot n := { to_fun := @tot_to_fun n, inv_fun := @tot_inv_fun n, left_inv := @tot_left_inv n, right_inv := @tot_right_inv n, } instance enum : ∀ (n r : ℕ), enumeration (fin_ind_partition n r) | 0 0 := { elems := [empty], nodup := list.nodup_singleton empty, complete := begin intro p,cases p,exact list.mem_cons_self empty list.nil end } | 0 (r + 1) := { elems := list.nil, nodup := list.nodup_nil, complete := by {intro p, cases p} } | (n + 1) 0 := { elems := list.nil, nodup := list.nodup_nil, complete := by {intro p, exfalso, cases p,apply fin.elim0,assumption} } | (n + 1) (r + 1) := begin let e0 := enum n r, let e1 := enum n (r + 1), let L_add := e0.elems.map add, let R := fin.elems_list (r + 1), let f : fin (r + 1) → list (fin_ind_partition (n + 1) (r + 1)) := λ u, e1.elems.map (λ p, join p u), let LL_join := R.map f, let L_join := list.join LL_join, let elems := list.append L_add L_join, let complete : ∀ p : fin_ind_partition (n + 1) (r + 1), p ∈ elems := begin intro p, cases p with _ _ p0 _ _ p0 u, { have p0_mem : p0 ∈ e0.elems := (@enumeration.complete _ e0 p0), exact list.mem_append_left _ (list.mem_map_of_mem add p0_mem), },{ have p0_mem : p0 ∈ e1.elems := (@enumeration.complete _ e1 p0), let h0 := fin.elems_list_complete u, let h1 : f u ∈ LL_join := list.mem_map_of_mem f h0, let h2 : join p0 u ∈ f u := list.mem_map_of_mem (λ q,join q u) p0_mem, let h3 : join p0 u ∈ L_join := list.mem_join_of_mem h1 h2, exact list.mem_append_right _ h3, } end, let nodup : list.nodup elems := begin have add_inj : function.injective (@add n r) := by simp[function.injective], have L_add_nodup : L_add.nodup := list.nodup_map add_inj e0.nodup, have LL_nodup : ∀ u, (f u).nodup := λ u, list.nodup_map (by simp[function.injective]) e1.nodup, have LL_disjoint_aux : ∀ u v : fin (r + 1), u ≠ v → list.disjoint (f u) (f v) := begin intros u v u_ne_v p p_in_f_u p_in_f_v, rcases (list.mem_map.mp p_in_f_u) with ⟨pu,⟨pu_in_elems,pu_eq⟩⟩, rcases (list.mem_map.mp p_in_f_v) with ⟨pv,⟨pv_in_elems,pv_eq⟩⟩, injection (pu_eq.trans pv_eq.symm) with _ u_eq_v, exact u_ne_v u_eq_v, end, have LL_disjoint : list.pairwise list.disjoint LL_join := begin apply (@list.pairwise_map _ (fin (r + 1)) list.disjoint f R).mpr, exact list.pairwise.imp LL_disjoint_aux (fin.elems_list_nodup (r + 1)), end, have L_join_nodup : L_join.nodup := begin apply list.nodup_join.mpr, split, {intros l l_in_LL, rcases (list.mem_map.mp l_in_LL) with ⟨u,⟨u_in_R,f_u_eq_l⟩⟩, rw[← f_u_eq_l], exact (LL_nodup u), },{ exact LL_disjoint, } end, have L_disjoint : list.disjoint L_add L_join := begin intros p p_in_L_add p_in_L_join, rcases (list.mem_map.mp p_in_L_add) with ⟨p0,⟨p0_in_elems,p0_eq⟩⟩, rcases list.mem_join.mp p_in_L_join with ⟨l,⟨l_in_LL_join,p_in_l⟩⟩, rcases (list.mem_map.mp l_in_LL_join) with ⟨u,⟨u_in_R,f_u_eq_l⟩⟩, rw[← f_u_eq_l] at p_in_l, rcases (list.mem_map.mp p_in_l) with ⟨p1,⟨p1_in_elems,p1_eq⟩⟩, injection (p0_eq.trans p1_eq.symm), end, exact list.nodup_append.mpr ⟨L_add_nodup,L_join_nodup,L_disjoint⟩, end, exact { elems := elems, nodup := nodup, complete := complete }, end lemma card_step (n r : ℕ) : (fin_ind_partition.enum n.succ r.succ).elems.length = (fin_ind_partition.enum n r).elems.length + (fin_ind_partition.enum n r.succ).elems.length * r.succ := begin let e0 := fin_ind_partition.enum n r, let e1 := fin_ind_partition.enum n (r + 1), let e2 := fin_ind_partition.enum (n + 1) (r + 1), let n0 := e0.elems.length, let n1 := e1.elems.length, let n2 := e2.elems.length, let L_add := e0.elems.map add, let R := fin.elems_list (r + 1), let f : fin (r + 1) → list (fin_ind_partition (n + 1) (r + 1)) := λ u, e1.elems.map (λ p, join p u), let LL_join := R.map f, let L_join := list.join LL_join, have h0 : n2 = L_add.length + L_join.length := list.length_append L_add L_join, have h1 : L_add.length = n0 := list.length_map add _, let h2 : LL_join.length = r.succ := (list.length_map f R).trans (fin.elems_list_length r.succ), have h3 : ∀ u, (f u).length = n1 := λ u,list.length_map (λ p, join p u) _, let h4 : LL_join.map list.length = list.repeat n1 r.succ := begin apply list.eq_repeat.mpr, split, {exact ((list.length_map list.length LL_join).trans h2),}, {intros k k_in_ks, rcases (list.mem_map.mp k_in_ks) with ⟨l,⟨l_in_LL_join,l_len⟩⟩, rcases (list.mem_map.mp l_in_LL_join) with ⟨u,⟨u_in_R,f_u_eq_l⟩⟩, rw[← l_len,← f_u_eq_l], exact h3 u, } end, have h5 : L_join.length = n1 * r.succ := (list.length_join LL_join).trans ((congr_arg list.sum h4).trans (list.sum_const_nat n1 r.succ)), exact calc n2 = L_add.length + L_join.length : h0 ... = n0 + n1 * r.succ : by rw[h1,h5] end lemma card_stirling : ∀ (n r : ℕ), (fintype.card (fin_ind_partition n r)) = partition.number.stirling2 n r | 0 0 := rfl | 0 (r + 1) := rfl | (n + 1) 0 := rfl | (n + 1) (r + 1) := begin rw[partition.number.stirling2,enumeration.enum_card,card_step n r], rw[← enumeration.enum_card,← enumeration.enum_card], rw[card_stirling n r,card_stirling n (r + 1)], end instance tot_enum (n : ℕ) : enumeration (tot n) := begin let e0 := fin_ind_partition.enum n, let elems0 : ℕ → list (tot n) := λ r, (e0 r).elems.map to_tot, let elems1 := ((list.range n.succ).map elems0), let elems := elems1.join, let nodup0 : ∀ r, (elems0 r).nodup := begin intro r, have tot_inj : function.injective (@to_tot n r) := begin intros p1 p2 tot_eq, injection tot_eq with r_eq p_heq, cases r_eq, exact eq_of_heq p_heq, end, exact list.nodup_map tot_inj (e0 r).nodup, end, let nodup1 : ∀ l, l ∈ elems1 → (list.nodup l) := begin intros l l_in_elems1, rcases (list.mem_map.mp l_in_elems1) with ⟨r,⟨r_mem,l_eq⟩⟩, rw[← l_eq], exact nodup0 r, end, let disjoint0 : ∀ r1 r2, r1 ≠ r2 → list.disjoint (elems0 r1) (elems0 r2) := begin intros r1 r2 r_ne q q_in_l1 q_in_l2, rcases (list.mem_map.mp q_in_l1) with ⟨p1,⟨p1_in_elems,p1_eq⟩⟩, rcases (list.mem_map.mp q_in_l2) with ⟨p2,⟨p2_in_elems,p2_eq⟩⟩, let r_eq : r1 = r2 := (congr_arg sigma.fst p1_eq).trans (congr_arg sigma.fst p2_eq).symm, exact r_ne r_eq, end, let disjoint1 := @list.pairwise.imp ℕ ne (λ r1 r2, list.disjoint (elems0 r1) (elems0 r2)) disjoint0 _ (list.nodup_range n.succ), let disjoint2 := (list.pairwise_map elems0).mpr disjoint1, let nodup := list.nodup_join.mpr ⟨nodup1,disjoint2⟩, let complete : ∀ rp : tot n, rp ∈ elems := begin intro rp, rcases rp with ⟨r,p⟩, have rp_eq : to_tot p = ⟨r,p⟩ := rfl, rw[← rp_eq], have mem0 : p ∈ (e0 r).elems := @enumeration.complete _ (e0 r) p, have mem1 : to_tot p ∈ elems0 r := list.mem_map_of_mem to_tot mem0, have mem2 : elems0 r ∈ elems1 := list.mem_map_of_mem elems0 (list.mem_range.mpr (nat.lt_succ_of_le (rank_bound p))), exact list.mem_join.mpr ⟨elems0 r,⟨mem2,mem1⟩⟩, end, exact {elems := elems, nodup := nodup, complete := complete}, end lemma card_bell (n : ℕ) : fintype.card (tot n) = partition.number.bell n := begin let f := λ (r : ℕ), list.map to_tot (enumeration.elems (fin_ind_partition n r)), have h : list.length ∘ f = partition.number.stirling2 n := begin ext r,simp,rw[← enumeration.enum_card],exact card_stirling n r, end, rw[enumeration.enum_card,partition.number.bell], dsimp[enumeration.elems], rw[list.length_join,list.map_map,h], end end fin_ind_partition namespace fin_map instance enum (n r : ℕ) : enumeration (fin_map n r) := enumeration.of_equiv (fin_ind_partition n r) (fin_ind_partition.map_equiv n r) lemma card_stirling (n r : ℕ) : (fintype.card (fin_map n r)) = partition.number.stirling2 n r := (fintype.card_congr (fin_ind_partition.map_equiv n r)).symm.trans (fin_ind_partition.card_stirling n r) instance enum_tot (n : ℕ) : enumeration (fin_map.tot n) := enumeration.of_equiv (fin_ind_partition.tot n) (fin_ind_partition.map_equiv_tot n) lemma card_bell (n : ℕ) : (fintype.card (fin_map.tot n)) = partition.number.bell n := (fintype.card_congr (fin_ind_partition.map_equiv_tot n)).symm.trans (fin_ind_partition.card_bell n) end fin_map lemma card_stirling (n r : ℕ) : fintype.card { p : partition (fin n) // p.rank = r } = partition.number.stirling2 n r := (fintype.card_congr (@fin_map.partition_equiv n r)).symm.trans (fin_map.card_stirling n r) lemma card_bell (n : ℕ) : fintype.card (partition (fin n)) = partition.number.bell n := (fintype.card_congr (@fin_map.partition_equiv_tot n)).symm.trans (fin_map.card_bell n) lemma card_bell' (α : Type*) [fintype α] [decidable_eq α] : fintype.card (partition α) = partition.number.bell (fintype.card α) := begin refine trunc.induction_on (fintype.equiv_fin α) _, intro equiv_fin, exact (fintype.card_congr (isofunctor equiv_fin)).trans (card_bell (fintype.card α)), end end combinatorics.partition
4e2b3a134ecf75541daa3b6061bbc81689ff2d9a
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/measure/regular.lean
a025ef6c8720b8433c95a16c4839bbf0470a43fa
[ "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
33,656
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris Van Doorn, Yury Kudryashov -/ import measure_theory.constructions.borel_space /-! # Regular measures A measure is `outer_regular` if the measure of any measurable set `A` is the infimum of `μ U` over all open sets `U` containing `A`. A measure is `regular` if it satisfies the following properties: * it is finite on compact sets; * it is outer regular; * it is inner regular for open sets with respect to compacts sets: the measure of any open set `U` is the supremum of `μ K` over all compact sets `K` contained in `U`. A measure is `weakly_regular` if it satisfies the following properties: * it is outer regular; * it is inner regular for open sets with respect to closed sets: the measure of any open set `U` is the supremum of `μ F` over all closed sets `F` contained in `U`. In a Hausdorff topological space, regularity implies weak regularity. These three conditions are registered as typeclasses for a measure `μ`, and this implication is recorded as an instance. In order to avoid code duplication, we also define a measure `μ` to be `inner_regular` for sets satisfying a predicate `q` with respect to sets satisfying a predicate `p` if for any set `U ∈ {U | q U}` and a number `r < μ U` there exists `F ⊆ U` such that `p F` and `r < μ F`. We prove that inner regularity for open sets with respect to compact sets or closed sets implies inner regularity for all measurable sets of finite measure (with respect to compact sets or closed sets respectively), and register some corollaries for (weakly) regular measures. Note that a similar statement for measurable sets of infinite mass can fail. For a counterexample, consider the group `ℝ × ℝ` where the first factor has the discrete topology and the second one the usual topology. It is a locally compact Hausdorff topological group, with Haar measure equal to Lebesgue measure on each vertical fiber. The set `ℝ × {0}` has infinite measure (by outer regularity), but any compact set it contains has zero measure (as it is finite). Several authors require as a definition of regularity that all measurable sets are inner regular. We have opted for the slightly weaker definition above as it holds for all Haar measures, it is enough for essentially all applications, and it is equivalent to the other definition when the measure is finite. The interest of the notion of weak regularity is that it is enough for many applications, and it is automatically satisfied by any finite measure on a metric space. ## Main definitions * `measure_theory.measure.outer_regular μ`: a typeclass registering that a measure `μ` on a topological space is outer regular. * `measure_theory.measure.regular μ`: a typeclass registering that a measure `μ` on a topological space is regular. * `measure_theory.measure.weakly_regular μ`: a typeclass registering that a measure `μ` on a topological space is weakly regular. * `measure_theory.measure.inner_regular μ p q`: a non-typeclass predicate saying that a measure `μ` is inner regular for sets satisfying `q` with respect to sets satisfying `p`. ## Main results ### Outer regular measures * `set.measure_eq_infi_is_open` asserts that, when `μ` is outer regular, the measure of a set is the infimum of the measure of open sets containing it. * `set.exists_is_open_lt_of_lt` asserts that, when `μ` is outer regular, for every set `s` and `r > μ s` there exists an open superset `U ⊇ s` of measure less than `r`. * push forward of an outer regular measure is outer regular, and scalar multiplication of a regular measure by a finite number is outer regular. ### Weakly regular measures * `is_open.measure_eq_supr_is_closed` asserts that the measure of an open set is the supremum of the measure of closed sets it contains. * `is_open.exists_lt_is_closed`: for an open set `U` and `r < μ U`, there exists a closed `F ⊆ U` of measure greater than `r`; * `measurable_set.measure_eq_supr_is_closed_of_ne_top` asserts that the measure of a measurable set of finite measure is the supremum of the measure of closed sets it contains. * `measurable_set.exists_lt_is_closed_of_ne_top` and `measurable_set.exists_is_closed_lt_add`: a measurable set of finite measure can be approximated by a closed subset (stated as `r < μ F` and `μ s < μ F + ε`, respectively). * `measure_theory.measure.weakly_regular.of_pseudo_emetric_space_of_is_finite_measure` is an instance registering that a finite measure on a metric space is weakly regular (in fact, a pseudo emetric space is enough); * `measure_theory.measure.weakly_regular.of_pseudo_emetric_second_countable_of_locally_finite` is an instance registering that a locally finite measure on a second countable metric space (or even a pseudo emetric space) is weakly regular. ### Regular measures * `is_open.measure_eq_supr_is_compact` asserts that the measure of an open set is the supremum of the measure of compact sets it contains. * `is_open.exists_lt_is_compact`: for an open set `U` and `r < μ U`, there exists a compact `K ⊆ U` of measure greater than `r`; * `measurable_set.measure_eq_supr_is_compact_of_ne_top` asserts that the measure of a measurable set of finite measure is the supremum of the measure of compact sets it contains. * `measurable_set.exists_lt_is_compact_of_ne_top` and `measurable_set.exists_is_compact_lt_add`: a measurable set of finite measure can be approximated by a compact subset (stated as `r < μ K` and `μ s < μ K + ε`, respectively). * `measure_theory.measure.regular.of_sigma_compact_space_of_is_locally_finite_measure` is an instance registering that a locally finite measure on a `σ`-compact metric space is regular (in fact, an emetric space is enough). ## Implementation notes The main nontrivial statement is `measure_theory.measure.inner_regular.weakly_regular_of_finite`, expressing that in a finite measure space, if every open set can be approximated from inside by closed sets, then the measure is in fact weakly regular. To prove that we show that any measurable set can be approximated from inside by closed sets and from outside by open sets. This statement is proved by measurable induction, starting from open sets and checking that it is stable by taking complements (this is the point of this condition, being symmetrical between inside and outside) and countable disjoint unions. Once this statement is proved, one deduces results for `σ`-finite measures from this statement, by restricting them to finite measure sets (and proving that this restriction is weakly regular, using again the same statement). ## References [Halmos, Measure Theory, §52][halmos1950measure]. Note that Halmos uses an unusual definition of Borel sets (for him, they are elements of the `σ`-algebra generated by compact sets!), so his proofs or statements do not apply directly. [Billingsley, Convergence of Probability Measures][billingsley1999] -/ open set filter open_locale ennreal topology nnreal big_operators namespace measure_theory namespace measure /-- We say that a measure `μ` is *inner regular* with respect to predicates `p q : set α → Prop`, if for every `U` such that `q U` and `r < μ U`, there exists a subset `K ⊆ U` satisfying `p K` of measure greater than `r`. This definition is used to prove some facts about regular and weakly regular measures without repeating the proofs. -/ def inner_regular {α} {m : measurable_space α} (μ : measure α) (p q : set α → Prop) := ∀ ⦃U⦄, q U → ∀ r < μ U, ∃ K ⊆ U, p K ∧ r < μ K namespace inner_regular variables {α : Type*} {m : measurable_space α} {μ : measure α} {p q : set α → Prop} {U : set α} {ε : ℝ≥0∞} lemma measure_eq_supr (H : inner_regular μ p q) (hU : q U) : μ U = ⨆ (K ⊆ U) (hK : p K), μ K := begin refine le_antisymm (le_of_forall_lt $ λ r hr, _) (supr₂_le $ λ K hK, supr_le $ λ _, μ.mono hK), simpa only [lt_supr_iff, exists_prop] using H hU r hr end lemma exists_subset_lt_add (H : inner_regular μ p q) (h0 : p ∅) (hU : q U) (hμU : μ U ≠ ∞) (hε : ε ≠ 0) : ∃ K ⊆ U, p K ∧ μ U < μ K + ε := begin cases eq_or_ne (μ U) 0 with h₀ h₀, { refine ⟨∅, empty_subset _, h0, _⟩, rwa [measure_empty, h₀, zero_add, pos_iff_ne_zero] }, { rcases H hU _ (ennreal.sub_lt_self hμU h₀ hε) with ⟨K, hKU, hKc, hrK⟩, exact ⟨K, hKU, hKc, ennreal.lt_add_of_sub_lt_right (or.inl hμU) hrK⟩ } end lemma map {α β} [measurable_space α] [measurable_space β] {μ : measure α} {pa qa : set α → Prop} (H : inner_regular μ pa qa) (f : α ≃ β) (hf : ae_measurable f μ) {pb qb : set β → Prop} (hAB : ∀ U, qb U → qa (f ⁻¹' U)) (hAB' : ∀ K, pa K → pb (f '' K)) (hB₁ : ∀ K, pb K → measurable_set K) (hB₂ : ∀ U, qb U → measurable_set U) : inner_regular (map f μ) pb qb := begin intros U hU r hr, rw [map_apply_of_ae_measurable hf (hB₂ _ hU)] at hr, rcases H (hAB U hU) r hr with ⟨K, hKU, hKc, hK⟩, refine ⟨f '' K, image_subset_iff.2 hKU, hAB' _ hKc, _⟩, rwa [map_apply_of_ae_measurable hf (hB₁ _ $ hAB' _ hKc), f.preimage_image] end lemma smul (H : inner_regular μ p q) (c : ℝ≥0∞) : inner_regular (c • μ) p q := begin intros U hU r hr, rw [smul_apply, H.measure_eq_supr hU, smul_eq_mul] at hr, simpa only [ennreal.mul_supr, lt_supr_iff, exists_prop] using hr end lemma trans {q' : set α → Prop} (H : inner_regular μ p q) (H' : inner_regular μ q q') : inner_regular μ p q' := begin intros U hU r hr, rcases H' hU r hr with ⟨F, hFU, hqF, hF⟩, rcases H hqF _ hF with ⟨K, hKF, hpK, hrK⟩, exact ⟨K, hKF.trans hFU, hpK, hrK⟩ end end inner_regular variables {α β : Type*} [measurable_space α] [topological_space α] {μ : measure α} /-- A measure `μ` is outer regular if `μ(A) = inf {μ(U) | A ⊆ U open}` for a measurable set `A`. This definition implies the same equality for any (not necessarily measurable) set, see `set.measure_eq_infi_is_open`. -/ @[protect_proj] class outer_regular (μ : measure α) : Prop := (outer_regular : ∀ ⦃A : set α⦄, measurable_set A → ∀ r > μ A, ∃ U ⊇ A, is_open U ∧ μ U < r) /-- A measure `μ` is regular if - it is finite on all compact sets; - it is outer regular: `μ(A) = inf {μ(U) | A ⊆ U open}` for `A` measurable; - it is inner regular for open sets, using compact sets: `μ(U) = sup {μ(K) | K ⊆ U compact}` for `U` open. -/ @[protect_proj] class regular (μ : measure α) extends is_finite_measure_on_compacts μ, outer_regular μ : Prop := (inner_regular : inner_regular μ is_compact is_open) /-- A measure `μ` is weakly regular if - it is outer regular: `μ(A) = inf {μ(U) | A ⊆ U open}` for `A` measurable; - it is inner regular for open sets, using closed sets: `μ(U) = sup {μ(F) | F ⊆ U compact}` for `U` open. -/ @[protect_proj] class weakly_regular (μ : measure α) extends outer_regular μ : Prop := (inner_regular : inner_regular μ is_closed is_open) /-- A regular measure is weakly regular. -/ @[priority 100] -- see Note [lower instance priority] instance regular.weakly_regular [t2_space α] [regular μ] : weakly_regular μ := { inner_regular := λ U hU r hr, let ⟨K, hKU, hcK, hK⟩ := regular.inner_regular hU r hr in ⟨K, hKU, hcK.is_closed, hK⟩ } namespace outer_regular instance zero : outer_regular (0 : measure α) := ⟨λ A hA r hr, ⟨univ, subset_univ A, is_open_univ, hr⟩⟩ /-- Given `r` larger than the measure of a set `A`, there exists an open superset of `A` with measure less than `r`. -/ lemma _root_.set.exists_is_open_lt_of_lt [outer_regular μ] (A : set α) (r : ℝ≥0∞) (hr : μ A < r) : ∃ U ⊇ A, is_open U ∧ μ U < r := begin rcases outer_regular.outer_regular (measurable_set_to_measurable μ A) r (by rwa measure_to_measurable) with ⟨U, hAU, hUo, hU⟩, exact ⟨U, (subset_to_measurable _ _).trans hAU, hUo, hU⟩ end /-- For an outer regular measure, the measure of a set is the infimum of the measures of open sets containing it. -/ lemma _root_.set.measure_eq_infi_is_open (A : set α) (μ : measure α) [outer_regular μ] : μ A = (⨅ (U : set α) (h : A ⊆ U) (h2 : is_open U), μ U) := begin refine le_antisymm (le_infi₂ $ λ s hs, le_infi $ λ h2s, μ.mono hs) _, refine le_of_forall_lt' (λ r hr, _), simpa only [infi_lt_iff, exists_prop] using A.exists_is_open_lt_of_lt r hr end lemma _root_.set.exists_is_open_lt_add [outer_regular μ] (A : set α) (hA : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ U ⊇ A, is_open U ∧ μ U < μ A + ε := A.exists_is_open_lt_of_lt _ (ennreal.lt_add_right hA hε) lemma _root_.set.exists_is_open_le_add (A : set α) (μ : measure α) [outer_regular μ] {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ U ⊇ A, is_open U ∧ μ U ≤ μ A + ε := begin rcases eq_or_ne (μ A) ∞ with H|H, { exact ⟨univ, subset_univ _, is_open_univ, by simp only [H, _root_.top_add, le_top]⟩ }, { rcases A.exists_is_open_lt_add H hε with ⟨U, AU, U_open, hU⟩, exact ⟨U, AU, U_open, hU.le⟩ } end lemma _root_.measurable_set.exists_is_open_diff_lt [outer_regular μ] {A : set α} (hA : measurable_set A) (hA' : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ U ⊇ A, is_open U ∧ μ U < ∞ ∧ μ (U \ A) < ε := begin rcases A.exists_is_open_lt_add hA' hε with ⟨U, hAU, hUo, hU⟩, use [U, hAU, hUo, hU.trans_le le_top], exact measure_diff_lt_of_lt_add hA hAU hA' hU, end protected lemma map [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] (f : α ≃ₜ β) (μ : measure α) [outer_regular μ] : (measure.map f μ).outer_regular := begin refine ⟨λ A hA r hr, _⟩, rw [map_apply f.measurable hA, ← f.image_symm] at hr, rcases set.exists_is_open_lt_of_lt _ r hr with ⟨U, hAU, hUo, hU⟩, have : is_open (f.symm ⁻¹' U), from hUo.preimage f.symm.continuous, refine ⟨f.symm ⁻¹' U, image_subset_iff.1 hAU, this, _⟩, rwa [map_apply f.measurable this.measurable_set, f.preimage_symm, f.preimage_image], end protected lemma smul (μ : measure α) [outer_regular μ] {x : ℝ≥0∞} (hx : x ≠ ∞) : (x • μ).outer_regular := begin rcases eq_or_ne x 0 with rfl|h0, { rw zero_smul, exact outer_regular.zero }, { refine ⟨λ A hA r hr, _⟩, rw [smul_apply, A.measure_eq_infi_is_open, smul_eq_mul] at hr, simpa only [ennreal.mul_infi_of_ne h0 hx, gt_iff_lt, infi_lt_iff, exists_prop] using hr } end end outer_regular /-- If a measure `μ` admits finite spanning open sets such that the restriction of `μ` to each set is outer regular, then the original measure is outer regular as well. -/ protected lemma finite_spanning_sets_in.outer_regular [opens_measurable_space α] {μ : measure α} (s : μ.finite_spanning_sets_in {U | is_open U ∧ outer_regular (μ.restrict U)}) : outer_regular μ := begin refine ⟨λ A hA r hr, _⟩, have hm : ∀ n, measurable_set (s.set n), from λ n, (s.set_mem n).1.measurable_set, haveI : ∀ n, outer_regular (μ.restrict (s.set n)) := λ n, (s.set_mem n).2, -- Note that `A = ⋃ n, A ∩ disjointed s n`. We replace `A` with this sequence. obtain ⟨A, hAm, hAs, hAd, rfl⟩ : ∃ A' : ℕ → set α, (∀ n, measurable_set (A' n)) ∧ (∀ n, A' n ⊆ s.set n) ∧ pairwise (disjoint on A') ∧ A = ⋃ n, A' n, { refine ⟨λ n, A ∩ disjointed s.set n, λ n, hA.inter (measurable_set.disjointed hm _), λ n, (inter_subset_right _ _).trans (disjointed_subset _ _), (disjoint_disjointed s.set).mono (λ k l hkl, hkl.mono inf_le_right inf_le_right), _⟩, rw [← inter_Union, Union_disjointed, s.spanning, inter_univ] }, rcases ennreal.exists_pos_sum_of_countable' (tsub_pos_iff_lt.2 hr).ne' ℕ with ⟨δ, δ0, hδε⟩, rw [lt_tsub_iff_right, add_comm] at hδε, have : ∀ n, ∃ U ⊇ A n, is_open U ∧ μ U < μ (A n) + δ n, { intro n, have H₁ : ∀ t, μ.restrict (s.set n) t = μ (t ∩ s.set n), from λ t, restrict_apply' (hm n), have Ht : μ.restrict (s.set n) (A n) ≠ ⊤, { rw H₁, exact ((measure_mono $ inter_subset_right _ _).trans_lt (s.finite n)).ne }, rcases (A n).exists_is_open_lt_add Ht (δ0 n).ne' with ⟨U, hAU, hUo, hU⟩, rw [H₁, H₁, inter_eq_self_of_subset_left (hAs _)] at hU, exact ⟨U ∩ s.set n, subset_inter hAU (hAs _), hUo.inter (s.set_mem n).1, hU⟩ }, choose U hAU hUo hU, refine ⟨⋃ n, U n, Union_mono hAU, is_open_Union hUo, _⟩, calc μ (⋃ n, U n) ≤ ∑' n, μ (U n) : measure_Union_le _ ... ≤ ∑' n, (μ (A n) + δ n) : ennreal.tsum_le_tsum (λ n, (hU n).le) ... = ∑' n, μ (A n) + ∑' n, δ n : ennreal.tsum_add ... = μ (⋃ n, A n) + ∑' n, δ n : congr_arg2 (+) (measure_Union hAd hAm).symm rfl ... < r : hδε end namespace inner_regular variables {p q : set α → Prop} {U s : set α} {ε r : ℝ≥0∞} /-- If a measure is inner regular (using closed or compact sets), then every measurable set of finite measure can by approximated by a (closed or compact) subset. -/ lemma measurable_set_of_open [outer_regular μ] (H : inner_regular μ p is_open) (h0 : p ∅) (hd : ∀ ⦃s U⦄, p s → is_open U → p (s \ U)) : inner_regular μ p (λ s, measurable_set s ∧ μ s ≠ ∞) := begin rintros s ⟨hs, hμs⟩ r hr, obtain ⟨ε, hε, hεs, rfl⟩ : ∃ ε ≠ 0, ε + ε ≤ μ s ∧ r = μ s - (ε + ε), { use (μ s - r) / 2, simp [*, hr.le, ennreal.add_halves, ennreal.sub_sub_cancel, le_add_right] }, rcases hs.exists_is_open_diff_lt hμs hε with ⟨U, hsU, hUo, hUt, hμU⟩, rcases (U \ s).exists_is_open_lt_of_lt _ hμU with ⟨U', hsU', hU'o, hμU'⟩, replace hsU' := diff_subset_comm.1 hsU', rcases H.exists_subset_lt_add h0 hUo hUt.ne hε with ⟨K, hKU, hKc, hKr⟩, refine ⟨K \ U', λ x hx, hsU' ⟨hKU hx.1, hx.2⟩, hd hKc hU'o, ennreal.sub_lt_of_lt_add hεs _⟩, calc μ s ≤ μ U : μ.mono hsU ... < μ K + ε : hKr ... ≤ μ (K \ U') + μ U' + ε : add_le_add_right (tsub_le_iff_right.1 le_measure_diff) _ ... ≤ μ (K \ U') + ε + ε : by { mono*, exacts [hμU'.le, le_rfl] } ... = μ (K \ U') + (ε + ε) : add_assoc _ _ _ end open finset /-- In a finite measure space, assume that any open set can be approximated from inside by closed sets. Then the measure is weakly regular. -/ lemma weakly_regular_of_finite [borel_space α] (μ : measure α) [is_finite_measure μ] (H : inner_regular μ is_closed is_open) : weakly_regular μ := begin have hfin : ∀ {s}, μ s ≠ ⊤ := measure_ne_top μ, suffices : ∀ s, measurable_set s → ∀ ε ≠ 0, ∃ (F ⊆ s) (U ⊇ s), is_closed F ∧ is_open U ∧ μ s ≤ μ F + ε ∧ μ U ≤ μ s + ε, { refine { outer_regular := λ s hs r hr, _, inner_regular := H }, rcases exists_between hr with ⟨r', hsr', hr'r⟩, rcases this s hs _ (tsub_pos_iff_lt.2 hsr').ne' with ⟨-, -, U, hsU, -, hUo, -, H⟩, refine ⟨U, hsU, hUo, _⟩, rw [add_tsub_cancel_of_le hsr'.le] at H, exact H.trans_lt hr'r }, refine measurable_set.induction_on_open _ _ _, /- The proof is by measurable induction: we should check that the property is true for the empty set, for open sets, and is stable by taking the complement and by taking countable disjoint unions. The point of the property we are proving is that it is stable by taking complements (exchanging the roles of closed and open sets and thanks to the finiteness of the measure). -/ -- check for open set { intros U hU ε hε, rcases H.exists_subset_lt_add is_closed_empty hU hfin hε with ⟨F, hsF, hFc, hF⟩, exact ⟨F, hsF, U, subset.rfl, hFc, hU, hF.le, le_self_add⟩ }, -- check for complements { rintros s hs H ε hε, rcases H ε hε with ⟨F, hFs, U, hsU, hFc, hUo, hF, hU⟩, refine ⟨Uᶜ, compl_subset_compl.2 hsU, Fᶜ, compl_subset_compl.2 hFs, hUo.is_closed_compl, hFc.is_open_compl, _⟩, simp only [measure_compl_le_add_iff, *, hUo.measurable_set, hFc.measurable_set, true_and] }, -- check for disjoint unions { intros s hsd hsm H ε ε0, have ε0' : ε / 2 ≠ 0, from (ennreal.half_pos ε0).ne', rcases ennreal.exists_pos_sum_of_countable' ε0' ℕ with ⟨δ, δ0, hδε⟩, choose F hFs U hsU hFc hUo hF hU using λ n, H n (δ n) (δ0 n).ne', -- the approximating closed set is constructed by considering finitely many sets `s i`, which -- cover all the measure up to `ε/2`, approximating each of these by a closed set `F i`, and -- taking the union of these (finitely many) `F i`. have : tendsto (λ t, ∑ k in t, μ (s k) + ε / 2) at_top (𝓝 $ μ (⋃ n, s n) + ε / 2), { rw measure_Union hsd hsm, exact tendsto.add ennreal.summable.has_sum tendsto_const_nhds }, rcases (this.eventually $ lt_mem_nhds $ ennreal.lt_add_right hfin ε0').exists with ⟨t, ht⟩, -- the approximating open set is constructed by taking for each `s n` an approximating open set -- `U n` with measure at most `μ (s n) + δ n` for a summable `δ`, and taking the union of these. refine ⟨⋃ k ∈ t, F k, Union_mono $ λ k, Union_subset $ λ _, hFs _, ⋃ n, U n, Union_mono hsU, is_closed_bUnion t.finite_to_set $ λ k _, hFc k, is_open_Union hUo, ht.le.trans _, _⟩, { calc ∑ k in t, μ (s k) + ε / 2 ≤ ∑ k in t, μ (F k) + ∑ k in t, δ k + ε / 2 : by { rw ← sum_add_distrib, exact add_le_add_right (sum_le_sum $ λ k hk, hF k) _ } ... ≤ ∑ k in t, μ (F k) + ε / 2 + ε / 2 : add_le_add_right (add_le_add_left ((ennreal.sum_le_tsum _).trans hδε.le) _) _ ... = μ (⋃ k ∈ t, F k) + ε : _, rw [measure_bUnion_finset, add_assoc, ennreal.add_halves], exacts [λ k _ n _ hkn, (hsd hkn).mono (hFs k) (hFs n), λ k hk, (hFc k).measurable_set] }, { calc μ (⋃ n, U n) ≤ ∑' n, μ (U n) : measure_Union_le _ ... ≤ ∑' n, (μ (s n) + δ n) : ennreal.tsum_le_tsum hU ... = μ (⋃ n, s n) + ∑' n, δ n : by rw [measure_Union hsd hsm, ennreal.tsum_add] ... ≤ μ (⋃ n, s n) + ε : add_le_add_left (hδε.le.trans ennreal.half_le_self) _ } } end /-- In a metric space (or even a pseudo emetric space), an open set can be approximated from inside by closed sets. -/ lemma of_pseudo_emetric_space {X : Type*} [pseudo_emetric_space X] [measurable_space X] (μ : measure X) : inner_regular μ is_closed is_open := begin intros U hU r hr, rcases hU.exists_Union_is_closed with ⟨F, F_closed, -, rfl, F_mono⟩, rw measure_Union_eq_supr F_mono.directed_le at hr, rcases lt_supr_iff.1 hr with ⟨n, hn⟩, exact ⟨F n, subset_Union _ _, F_closed n, hn⟩ end /-- In a `σ`-compact space, any closed set can be approximated by a compact subset. -/ lemma is_compact_is_closed {X : Type*} [topological_space X] [sigma_compact_space X] [measurable_space X] (μ : measure X) : inner_regular μ is_compact is_closed := begin intros F hF r hr, set B : ℕ → set X := compact_covering X, have hBc : ∀ n, is_compact (F ∩ B n), from λ n, (is_compact_compact_covering X n).inter_left hF, have hBU : (⋃ n, F ∩ B n) = F, by rw [← inter_Union, Union_compact_covering, set.inter_univ], have : μ F = ⨆ n, μ (F ∩ B n), { rw [← measure_Union_eq_supr, hBU], exact monotone.directed_le (λ m n h, inter_subset_inter_right _ (compact_covering_subset _ h)) }, rw this at hr, rcases lt_supr_iff.1 hr with ⟨n, hn⟩, exact ⟨_, inter_subset_left _ _, hBc n, hn⟩ end end inner_regular namespace regular instance zero : regular (0 : measure α) := ⟨λ U hU r hr, ⟨∅, empty_subset _, is_compact_empty, hr⟩⟩ /-- If `μ` is a regular measure, then any open set can be approximated by a compact subset. -/ lemma _root_.is_open.exists_lt_is_compact [regular μ] ⦃U : set α⦄ (hU : is_open U) {r : ℝ≥0∞} (hr : r < μ U) : ∃ K ⊆ U, is_compact K ∧ r < μ K := regular.inner_regular hU r hr /-- The measure of an open set is the supremum of the measures of compact sets it contains. -/ lemma _root_.is_open.measure_eq_supr_is_compact ⦃U : set α⦄ (hU : is_open U) (μ : measure α) [regular μ] : μ U = (⨆ (K : set α) (h : K ⊆ U) (h2 : is_compact K), μ K) := regular.inner_regular.measure_eq_supr hU lemma exists_compact_not_null [regular μ] : (∃ K, is_compact K ∧ μ K ≠ 0) ↔ μ ≠ 0 := by simp_rw [ne.def, ← measure_univ_eq_zero, is_open_univ.measure_eq_supr_is_compact, ennreal.supr_eq_zero, not_forall, exists_prop, subset_univ, true_and] /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_is_compact_lt_add` and `measurable_set.exists_lt_is_compact_of_ne_top`. -/ lemma inner_regular_measurable [regular μ] : inner_regular μ is_compact (λ s, measurable_set s ∧ μ s ≠ ∞) := regular.inner_regular.measurable_set_of_open is_compact_empty (λ _ _, is_compact.diff) /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_lt_is_compact_of_ne_top`. -/ lemma _root_.measurable_set.exists_is_compact_lt_add [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ K ⊆ A, is_compact K ∧ μ A < μ K + ε := regular.inner_regular_measurable.exists_subset_lt_add is_compact_empty ⟨hA, h'A⟩ h'A hε /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_is_compact_lt_add` and `measurable_set.exists_lt_is_compact_of_ne_top`. -/ lemma _root_.measurable_set.exists_is_compact_diff_lt [opens_measurable_space α] [t2_space α] [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ K ⊆ A, is_compact K ∧ μ (A \ K) < ε := begin rcases hA.exists_is_compact_lt_add h'A hε with ⟨K, hKA, hKc, hK⟩, exact ⟨K, hKA, hKc, measure_diff_lt_of_lt_add hKc.measurable_set hKA (ne_top_of_le_ne_top h'A $ measure_mono hKA) hK⟩ end /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_is_compact_lt_add`. -/ lemma _root_.measurable_set.exists_lt_is_compact_of_ne_top [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {r : ℝ≥0∞} (hr : r < μ A) : ∃ K ⊆ A, is_compact K ∧ r < μ K := regular.inner_regular_measurable ⟨hA, h'A⟩ _ hr /-- Given a regular measure, any measurable set of finite mass can be approximated from inside by compact sets. -/ lemma _root_.measurable_set.measure_eq_supr_is_compact_of_ne_top [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) : μ A = (⨆ (K ⊆ A) (h : is_compact K), μ K) := regular.inner_regular_measurable.measure_eq_supr ⟨hA, h'A⟩ protected lemma map [opens_measurable_space α] [measurable_space β] [topological_space β] [t2_space β] [borel_space β] [regular μ] (f : α ≃ₜ β) : (measure.map f μ).regular := begin haveI := outer_regular.map f μ, haveI := is_finite_measure_on_compacts.map μ f, exact ⟨regular.inner_regular.map f.to_equiv f.measurable.ae_measurable (λ U hU, hU.preimage f.continuous) (λ K hK, hK.image f.continuous) (λ K hK, hK.measurable_set) (λ U hU, hU.measurable_set)⟩ end protected lemma smul [regular μ] {x : ℝ≥0∞} (hx : x ≠ ∞) : (x • μ).regular := begin haveI := outer_regular.smul μ hx, haveI := is_finite_measure_on_compacts.smul μ hx, exact ⟨regular.inner_regular.smul x⟩ end /-- A regular measure in a σ-compact space is σ-finite. -/ @[priority 100] -- see Note [lower instance priority] instance sigma_finite [sigma_compact_space α] [regular μ] : sigma_finite μ := ⟨⟨{ set := compact_covering α, set_mem := λ n, trivial, finite := λ n, (is_compact_compact_covering α n).measure_lt_top, spanning := Union_compact_covering α }⟩⟩ end regular namespace weakly_regular /-- If `μ` is a weakly regular measure, then any open set can be approximated by a closed subset. -/ lemma _root_.is_open.exists_lt_is_closed [weakly_regular μ] ⦃U : set α⦄ (hU : is_open U) {r : ℝ≥0∞} (hr : r < μ U) : ∃ F ⊆ U, is_closed F ∧ r < μ F := weakly_regular.inner_regular hU r hr /-- If `μ` is a weakly regular measure, then any open set can be approximated by a closed subset. -/ lemma _root_.is_open.measure_eq_supr_is_closed ⦃U : set α⦄ (hU : is_open U) (μ : measure α) [weakly_regular μ] : μ U = (⨆ (F ⊆ U) (h : is_closed F), μ F) := weakly_regular.inner_regular.measure_eq_supr hU lemma inner_regular_measurable [weakly_regular μ] : inner_regular μ is_closed (λ s, measurable_set s ∧ μ s ≠ ∞) := weakly_regular.inner_regular.measurable_set_of_open is_closed_empty (λ _ _ h₁ h₂, h₁.inter h₂.is_closed_compl) /-- If `s` is a measurable set, a weakly regular measure `μ` is finite on `s`, and `ε` is a positive number, then there exist a closed set `K ⊆ s` such that `μ s < μ K + ε`. -/ lemma _root_.measurable_set.exists_is_closed_lt_add [weakly_regular μ] {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ K ⊆ s, is_closed K ∧ μ s < μ K + ε := inner_regular_measurable.exists_subset_lt_add is_closed_empty ⟨hs, hμs⟩ hμs hε lemma _root_.measurable_set.exists_is_closed_diff_lt [opens_measurable_space α] [weakly_regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ F ⊆ A, is_closed F ∧ μ (A \ F) < ε := begin rcases hA.exists_is_closed_lt_add h'A hε with ⟨F, hFA, hFc, hF⟩, exact ⟨F, hFA, hFc, measure_diff_lt_of_lt_add hFc.measurable_set hFA (ne_top_of_le_ne_top h'A $ measure_mono hFA) hF⟩ end /-- Given a weakly regular measure, any measurable set of finite mass can be approximated from inside by closed sets. -/ lemma _root_.measurable_set.exists_lt_is_closed_of_ne_top [weakly_regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {r : ℝ≥0∞} (hr : r < μ A) : ∃ K ⊆ A, is_closed K ∧ r < μ K := inner_regular_measurable ⟨hA, h'A⟩ _ hr /-- Given a weakly regular measure, any measurable set of finite mass can be approximated from inside by closed sets. -/ lemma _root_.measurable_set.measure_eq_supr_is_closed_of_ne_top [weakly_regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) : μ A = (⨆ (K ⊆ A) (h : is_closed K), μ K) := inner_regular_measurable.measure_eq_supr ⟨hA, h'A⟩ /-- The restriction of a weakly regular measure to a measurable set of finite measure is weakly regular. -/ lemma restrict_of_measurable_set [borel_space α] [weakly_regular μ] (A : set α) (hA : measurable_set A) (h'A : μ A ≠ ∞) : weakly_regular (μ.restrict A) := begin haveI : fact (μ A < ∞) := ⟨h'A.lt_top⟩, refine inner_regular.weakly_regular_of_finite _ (λ V V_open, _), simp only [restrict_apply' hA], intros r hr, have : μ (V ∩ A) ≠ ∞, from ne_top_of_le_ne_top h'A (measure_mono $ inter_subset_right _ _), rcases (V_open.measurable_set.inter hA).exists_lt_is_closed_of_ne_top this hr with ⟨F, hFVA, hFc, hF⟩, refine ⟨F, hFVA.trans (inter_subset_left _ _), hFc, _⟩, rwa inter_eq_self_of_subset_left (hFVA.trans $ inter_subset_right _ _) end /-- Any finite measure on a metric space (or even a pseudo emetric space) is weakly regular. -/ @[priority 100] -- see Note [lower instance priority] instance of_pseudo_emetric_space_of_is_finite_measure {X : Type*} [pseudo_emetric_space X] [measurable_space X] [borel_space X] (μ : measure X) [is_finite_measure μ] : weakly_regular μ := (inner_regular.of_pseudo_emetric_space μ).weakly_regular_of_finite μ /-- Any locally finite measure on a second countable metric space (or even a pseudo emetric space) is weakly regular. -/ @[priority 100] -- see Note [lower instance priority] instance of_pseudo_emetric_second_countable_of_locally_finite {X : Type*} [pseudo_emetric_space X] [topological_space.second_countable_topology X] [measurable_space X] [borel_space X] (μ : measure X) [is_locally_finite_measure μ] : weakly_regular μ := begin haveI : outer_regular μ, { refine (μ.finite_spanning_sets_in_open'.mono' $ λ U hU, _).outer_regular, haveI : fact (μ U < ∞), from ⟨hU.2⟩, exact ⟨hU.1, infer_instance⟩ }, exact ⟨inner_regular.of_pseudo_emetric_space μ⟩ end end weakly_regular local attribute [instance] emetric.second_countable_of_sigma_compact /-- Any locally finite measure on a `σ`-compact (e)metric space is regular. -/ @[priority 100] -- see Note [lower instance priority] instance regular.of_sigma_compact_space_of_is_locally_finite_measure {X : Type*} [emetric_space X] [sigma_compact_space X] [measurable_space X] [borel_space X] (μ : measure X) [is_locally_finite_measure μ] : regular μ := { lt_top_of_is_compact := λ K hK, hK.measure_lt_top, inner_regular := (inner_regular.is_compact_is_closed μ).trans (inner_regular.of_pseudo_emetric_space μ) } end measure end measure_theory
a8d8394f511bb466b1b5613c010c1aaf39aa8be2
a7dd8b83f933e72c40845fd168dde330f050b1c9
/src/category_theory/instances/TopCommRing/default.lean
e4c0ff49fedbf0bfd848f964bfa278aa89af700f
[ "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
51
lean
import category_theory.instances.TopCommRing.basic
edb306c1ace7d12341d33c7769b37a4a6a62e724
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/mk_dec_eq_instance.lean
97f39f31aec80c9ecc1e9ebf1889ca0b0306ca51
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
5,628
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 Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics import init.meta.rec_util init.meta.interactive namespace tactic open expr environment list /-- Retrieve the name of the type we are building a decidable equality proof for. -/ private meta def get_dec_eq_type_name : tactic name := do { (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const n ls) ← return (get_app_fn b), when (n ≠ `decidable) failed, (const I ls) ← return (get_app_fn d1), return I } <|> fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)" /-- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/ private meta def get_lhs_rhs : tactic (expr × expr) := do (app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case", match_eq lhs_eq_rhs private meta def find_next_target : list expr → list expr → tactic (expr × expr) | (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r) | l1 l2 := failed /-- Create an inhabitant of (decidable (lhs = rhs)) -/ private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr := do lhs_type ← infer_type lhs, dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf, do { inst ← mk_instance dec_type, return $ inst lhs rhs } <|> do { f ← pp dec_type, fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) } private meta def apply_eq_of_heq (h : expr) : tactic unit := do pr ← mk_app `eq_of_heq [h], ty ← infer_type pr, assertv `h' ty pr >> skip /-- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/ private meta def dec_eq_same_constructor : name → name → nat → tactic unit | I_name F_name num_rec := do (lhs, rhs) ← get_lhs_rhs, -- Try easy case first, where the proof is just reflexivity (unify lhs rhs >> right >> reflexivity) <|> do { let lhs_list := get_app_args lhs, let rhs_list := get_app_args rhs, when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"), (lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list, rec ← is_type_app_of lhs_arg I_name, inst ← if rec then do { inst_fn ← mk_brec_on_rec_value F_name num_rec, return $ app inst_fn rhs_arg } else do { mk_dec_eq_for lhs_arg rhs_arg }, `[eapply @decidable.by_cases _ _ %%inst], -- discharge first (positive) case by recursion intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec), -- discharge second (negative) case by contradiction intro1, left, -- decidable.is_false intro1 >>= injection, intros, contradiction <|> do { lc ← local_context, lc.mmap' (λ h, try (apply_eq_of_heq h) <|> skip), contradiction }, return () } /-- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/ private meta def dec_eq_diff_constructor : tactic unit := left >> intron 1 >> contradiction /-- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number of constructors. -/ private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit := do (lhs, rhs) ← get_lhs_rhs, let lhs_fn := get_app_fn lhs, let rhs_fn := get_app_fn rhs, if lhs_fn = rhs_fn then dec_eq_same_constructor I_name F_name 0 else dec_eq_diff_constructor private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit := intro `w >>= cases >> all_goals' (dec_eq_case_2 I_name F_name) meta def mk_dec_eq_instance_core : tactic unit := do I_name ← get_dec_eq_type_name, env ← get_env, let v_name := `_v, let F_name := `_F, let num_indices := inductive_num_indices env I_name, let idx_names := list.map (λ (p : name × nat), mk_num_name p.fst p.snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)), -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro1 >>= (λ x, induction x (idx_names ++ [v_name, F_name]) (some $ I_name <.> "brec_on") >> return ()) else intro v_name >> return (), -- Apply cases to first element of type (I ...) get_local v_name >>= cases, all_goals' (dec_eq_case_1 I_name F_name) meta def mk_dec_eq_instance : tactic unit := do env ← get_env, (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const I_name ls) ← return (get_app_fn d1), when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $ do { d1' ← whnf d1, (app I_basic_const I_idx) ← return d1', I_idx_type ← infer_type I_idx, new_goal ← to_expr ``(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)), assert `_basic_dec_eq new_goal, swap, `[exact _basic_dec_eq %%I_idx], intro1, return () }, mk_dec_eq_instance_core meta instance binder_info.has_decidable_eq : decidable_eq binder_info := by mk_dec_eq_instance @[derive_handler] meta def decidable_eq_derive_handler := instance_derive_handler ``decidable_eq tactic.mk_dec_eq_instance end tactic
5e871e3719f697b43edb2ebbfb775f7f6acb121b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/smul_with_zero.lean
8295f45187d2633ac2741ea8421d700f34f04a69
[ "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,447
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import group_theory.group_action.defs import algebra.group_power.basic /-! # Introduce `smul_with_zero` In analogy with the usual monoid action on a Type `M`, we introduce an action of a `monoid_with_zero` on a Type with `0`. In particular, for Types `R` and `M`, both containing `0`, we define `smul_with_zero R M` to be the typeclass where the products `r • 0` and `0 • m` vanish for all `r : R` and all `m : M`. Moreover, in the case in which `R` is a `monoid_with_zero`, we introduce the typeclass `mul_action_with_zero R M`, mimicking group actions and having an absorbing `0` in `R`. Thus, the action is required to be compatible with * the unit of the monoid, acting as the identity; * the zero of the monoid_with_zero, acting as zero; * associativity of the monoid. We also add an `instance`: * any `monoid_with_zero` has a `mul_action_with_zero R R` acting on itself. -/ variables {R R' M M' : Type*} section has_zero variables (R M) /-- `smul_with_zero` is a class consisting of a Type `R` with `0 ∈ R` and a scalar multiplication of `R` on a Type `M` with `0`, such that the equality `r • m = 0` holds if at least one among `r` or `m` equals `0`. -/ class smul_with_zero [has_zero R] [has_zero M] extends has_scalar R M := (smul_zero : ∀ r : R, r • (0 : M) = 0) (zero_smul : ∀ m : M, (0 : R) • m = 0) instance mul_zero_class.to_smul_with_zero [mul_zero_class R] : smul_with_zero R R := { smul := (*), smul_zero := mul_zero, zero_smul := zero_mul } instance add_monoid.to_smul_with_zero [add_monoid M] : smul_with_zero ℕ M := { smul_zero := nsmul_zero, zero_smul := zero_nsmul } variables (R) {M} [has_zero R] [has_zero M] [smul_with_zero R M] @[simp] lemma zero_smul (m : M) : (0 : R) • m = 0 := smul_with_zero.zero_smul m variables {R} (M) /-- Note that this lemma has different typeclass assumptions to `smul_zero`. -/ @[simp] lemma smul_zero' (r : R) : r • (0 : M) = 0 := smul_with_zero.smul_zero r variables {R M} [has_zero R'] [has_zero M'] [has_scalar R M'] /-- Pullback a `smul_with_zero` structure along an injective zero-preserving homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.smul_with_zero (f : zero_hom M' M) (hf : function.injective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : smul_with_zero R M' := { smul := (•), zero_smul := λ a, hf $ by simp [smul], smul_zero := λ a, hf $ by simp [smul]} /-- Pushforward a `smul_with_zero` structure along a surjective zero-preserving homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.smul_with_zero (f : zero_hom M M') (hf : function.surjective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : smul_with_zero R M' := { smul := (•), zero_smul := λ m, by { rcases hf m with ⟨x, rfl⟩, simp [←smul] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero'] } variables (M) /-- Compose a `smul_with_zero` with a `zero_hom`, with action `f r' • m` -/ def smul_with_zero.comp_hom (f : zero_hom R' R) : smul_with_zero R' M := { smul := (•) ∘ f, smul_zero := λ m, by simp, zero_smul := λ m, by simp } end has_zero section monoid_with_zero variables [monoid_with_zero R] [monoid_with_zero R'] [has_zero M] variables (R M) /-- An action of a monoid with zero `R` on a Type `M`, also with `0`, extends `mul_action` and is compatible with `0` (both in `R` and in `M`), with `1 ∈ R`, and with associativity of multiplication on the monoid `M`. -/ class mul_action_with_zero extends mul_action R M := -- these fields are copied from `smul_with_zero`, as `extends` behaves poorly (smul_zero : ∀ r : R, r • (0 : M) = 0) (zero_smul : ∀ m : M, (0 : R) • m = 0) @[priority 100] -- see Note [lower instance priority] instance mul_action_with_zero.to_smul_with_zero [m : mul_action_with_zero R M] : smul_with_zero R M := {..m} instance monoid_with_zero.to_mul_action_with_zero : mul_action_with_zero R R := { ..mul_zero_class.to_smul_with_zero R, ..monoid.to_mul_action R } variables {R M} [mul_action_with_zero R M] [has_zero M'] [has_scalar R M'] /-- Pullback a `mul_action_with_zero` structure along an injective zero-preserving homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.mul_action_with_zero (f : zero_hom M' M) (hf : function.injective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : mul_action_with_zero R M' := { ..hf.mul_action f smul, ..hf.smul_with_zero f smul } /-- Pushforward a `mul_action_with_zero` structure along a surjective zero-preserving homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.mul_action_with_zero (f : zero_hom M M') (hf : function.surjective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) : mul_action_with_zero R M' := { ..hf.mul_action f smul, ..hf.smul_with_zero f smul } variables (M) /-- Compose a `mul_action_with_zero` with a `monoid_with_zero_hom`, with action `f r' • m` -/ def mul_action_with_zero.comp_hom (f : monoid_with_zero_hom R' R) : mul_action_with_zero R' M := { smul := (•) ∘ f, mul_smul := λ r s m, by simp [mul_smul], one_smul := λ m, by simp, .. smul_with_zero.comp_hom M f.to_zero_hom} end monoid_with_zero
034d132711bf32c4937f66caa7440997687da64f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/integral/circle_transform.lean
7ca20fb8487a15321c3ae6c52690214313ded161
[ "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
7,869
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import data.complex.basic import measure_theory.integral.circle_integral /-! # Circle integral transform In this file we define the circle integral transform of a function `f` with complex domain. This is defined as $(2πi)^{-1}\frac{f(x)}{x-w}$ where `x` moves along a circle. We then prove some basic facts about these functions. These results are useful for proving that the uniform limit of a sequence of holomorphic functions is holomorphic. -/ open set measure_theory metric filter function open_locale interval real noncomputable theory variables {E : Type} [normed_add_comm_group E] [normed_space ℂ E] (R : ℝ) (z w : ℂ) namespace complex /-- Given a function `f : ℂ → E`, `circle_transform R z w f` is the functions mapping `θ` to `(2 * ↑π * I)⁻¹ • deriv (circle_map z R) θ • ((circle_map z R θ) - w)⁻¹ • f (circle_map z R θ)`. If `f` is differentiable and `w` is in the interior of the ball, then the integral from `0` to `2 * π` of this gives the value `f(w)`. -/ def circle_transform (f : ℂ → E) (θ : ℝ) : E := (2 * ↑π * I)⁻¹ • deriv (circle_map z R) θ • ((circle_map z R θ) - w)⁻¹ • f (circle_map z R θ) /-- The derivative of `circle_transform` w.r.t `w`.-/ def circle_transform_deriv (f : ℂ → E) (θ : ℝ) : E := (2 * ↑π * I)⁻¹ • deriv (circle_map z R) θ • ((circle_map z R θ - w) ^ 2)⁻¹ • f (circle_map z R θ) lemma circle_transform_deriv_periodic (f : ℂ → E) : periodic (circle_transform_deriv R z w f) (2 * π) := begin have := periodic_circle_map, simp_rw periodic at *, intro x, simp_rw [circle_transform_deriv, this], congr' 2, simp [this], end lemma circle_transform_deriv_eq (f : ℂ → E) : circle_transform_deriv R z w f = (λ θ, (circle_map z R θ - w)⁻¹ • (circle_transform R z w f θ)) := begin ext, simp_rw [circle_transform_deriv, circle_transform, ←mul_smul, ←mul_assoc], ring_nf, rw inv_pow, congr, ring, end lemma integral_circle_transform [complete_space E] (f : ℂ → E) : ∫ (θ : ℝ) in 0..2 * π, circle_transform R z w f θ = (2 * ↑π * I)⁻¹ • ∮ z in C(z, R), (z - w)⁻¹ • f z := begin simp_rw [circle_transform, circle_integral, deriv_circle_map, circle_map], simp, end lemma continuous_circle_transform {R : ℝ} (hR : 0 < R) {f : ℂ → E} {z w : ℂ} (hf : continuous_on f $ sphere z R) (hw : w ∈ ball z R) : continuous (circle_transform R z w f) := begin apply_rules [continuous.smul, continuous_const], simp_rw deriv_circle_map, apply_rules [continuous.mul, (continuous_circle_map 0 R), continuous_const], { apply continuous_circle_map_inv hw }, { apply continuous_on.comp_continuous hf (continuous_circle_map z R), exact (λ _, (circle_map_mem_sphere _ hR.le) _) }, end lemma continuous_circle_transform_deriv {R : ℝ} (hR : 0 < R) {f : ℂ → E} {z w : ℂ} (hf : continuous_on f (sphere z R)) (hw : w ∈ ball z R) : continuous (circle_transform_deriv R z w f) := begin rw circle_transform_deriv_eq, exact (continuous_circle_map_inv hw).smul (continuous_circle_transform hR hf hw), end /--A useful bound for circle integrals (with complex codomain)-/ def circle_transform_bounding_function (R : ℝ) (z : ℂ) (w : ℂ × ℝ) : ℂ := circle_transform_deriv R z w.1 (λ x, 1) w.2 lemma continuous_on_prod_circle_transform_function {R r : ℝ} (hr : r < R) {z : ℂ} : continuous_on (λ w : ℂ × ℝ, ((circle_map z R w.snd - w.fst)⁻¹) ^ 2) (closed_ball z r ×ˢ univ) := begin simp_rw ←one_div, apply_rules [continuous_on.pow, continuous_on.div, continuous_on_const], refine ((continuous_circle_map z R).continuous_on.comp continuous_on_snd (λ _, and.right)).sub (continuous_on_id.comp continuous_on_fst (λ _, and.left)), simp only [mem_prod, ne.def, and_imp, prod.forall], intros a b ha hb, have ha2 : a ∈ ball z R, by {simp at *, linarith,}, exact (sub_ne_zero.2 (circle_map_ne_mem_ball ha2 b)), end lemma continuous_on_abs_circle_transform_bounding_function {R r : ℝ} (hr : r < R) (z : ℂ) : continuous_on (abs ∘ (λ t, circle_transform_bounding_function R z t)) (closed_ball z r ×ˢ univ) := begin have : continuous_on (circle_transform_bounding_function R z) (closed_ball z r ×ˢ (⊤ : set ℝ)), { apply_rules [continuous_on.smul, continuous_on_const], simp only [deriv_circle_map], have c := (continuous_circle_map 0 R).continuous_on, apply_rules [continuous_on.mul, c.comp continuous_on_snd (λ _, and.right), continuous_on_const], simp_rw ←inv_pow, apply continuous_on_prod_circle_transform_function hr, }, refine continuous_abs.continuous_on.comp this _, show maps_to _ _ (⊤ : set ℂ), simp [maps_to], end lemma abs_circle_transform_bounding_function_le {R r : ℝ} (hr : r < R) (hr' : 0 ≤ r) (z : ℂ) : ∃ x : closed_ball z r ×ˢ [0, 2 * π], ∀ y : closed_ball z r ×ˢ [0, 2 * π], abs (circle_transform_bounding_function R z y) ≤ abs (circle_transform_bounding_function R z x) := begin have cts := continuous_on_abs_circle_transform_bounding_function hr z, have comp : is_compact (closed_ball z r ×ˢ [0, 2 * π]), { apply_rules [is_compact.prod, proper_space.is_compact_closed_ball z r, is_compact_interval], }, have none : (closed_ball z r ×ˢ [0, 2 * π]).nonempty := (nonempty_closed_ball.2 hr').prod nonempty_interval, have := is_compact.exists_forall_ge comp none (cts.mono (by { intro z, simp only [mem_prod, mem_closed_ball, mem_univ, and_true, and_imp], tauto })), simpa only [set_coe.forall, subtype.coe_mk, set_coe.exists], end /-- The derivative of a `circle_transform` is locally bounded. -/ lemma circle_transform_deriv_bound {R : ℝ} (hR : 0 < R) {z x : ℂ} {f : ℂ → ℂ} (hx : x ∈ ball z R) (hf : continuous_on f (sphere z R)) : ∃ (B ε : ℝ), 0 < ε ∧ ball x ε ⊆ ball z R ∧ (∀ (t : ℝ) (y ∈ ball x ε), ‖circle_transform_deriv R z y f t‖ ≤ B) := begin obtain ⟨r, hr, hrx⟩ := exists_lt_mem_ball_of_mem_ball hx, obtain ⟨ε', hε', H⟩ := exists_ball_subset_ball hrx, obtain ⟨⟨⟨a, b⟩, ⟨ha, hb⟩⟩, hab⟩ := abs_circle_transform_bounding_function_le hr (pos_of_mem_ball hrx).le z, let V : ℝ → (ℂ → ℂ) := λ θ w, circle_transform_deriv R z w (λ x, 1) θ, have funccomp : continuous_on (λ r , abs (f r)) (sphere z R), by { have cabs : continuous_on abs ⊤ := by apply continuous_abs.continuous_on, apply cabs.comp (hf), rw maps_to, tauto,}, have sbou := is_compact.exists_forall_ge (is_compact_sphere z R) (normed_space.sphere_nonempty.2 hR.le) funccomp, obtain ⟨X, HX, HX2⟩ := sbou, refine ⟨abs (V b a) * abs (f X), ε' , hε', subset.trans H (ball_subset_ball hr.le), _ ⟩, intros y v hv, obtain ⟨y1, hy1, hfun⟩ := periodic.exists_mem_Ico₀ (circle_transform_deriv_periodic R z v f) real.two_pi_pos y, have hy2: y1 ∈ [0, 2*π], by {convert (Ico_subset_Icc_self hy1), simp [interval_of_le real.two_pi_pos.le]}, have := mul_le_mul (hab ⟨⟨v, y1⟩, ⟨ball_subset_closed_ball (H hv), hy2⟩⟩) (HX2 (circle_map z R y1) (circle_map_mem_sphere z hR.le y1)) (complex.abs.nonneg _) (complex.abs.nonneg _), simp_rw hfun, simp only [circle_transform_bounding_function, circle_transform_deriv, V, norm_eq_abs, algebra.id.smul_eq_mul, deriv_circle_map, map_mul, abs_circle_map_zero, abs_I, mul_one, ←mul_assoc, mul_inv_rev, inv_I, abs_neg, abs_inv, abs_of_real, one_mul, abs_two, abs_pow, mem_ball, gt_iff_lt, subtype.coe_mk, set_coe.forall, mem_prod, mem_closed_ball, and_imp, prod.forall, normed_space.sphere_nonempty, mem_sphere_iff_norm] at *, exact this, end end complex
246cd3df7525afec9532f94dc6501ec91df0a3ea
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/511a.lean
6c39434fae4dd143f4a54ea6f0928aac024d4afe
[ "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
370
lean
import data.nat open nat example (a b : nat) (f : nat → nat) (h : f (succ a) = 0) : f (a+1) = 0 := by rewrite [add_one, h] example (a b : nat) (f : nat → nat) (h : f (succ a) = 0) : f (a+1) = 0 := by xrewrite h definition g (a : nat) := a + 1 definition h (a : nat) := a example (a b : nat) (f : nat → nat) (h : f (g (h a)) = 0) : f (a+1) = 0 := by krewrite h
a567c495ba0618e3da10eb49a8a0b9efbe84afd7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/matchPatternPartialApp.lean
f3b634dc6bfe5e88ee36a30c3fabd08eef2cf06a
[ "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
150
lean
def test2 : (Function.comp id id) = λ x : Nat => x := by conv in (Function.comp _) => trace_state simp [Function.comp, id] trace_state
84d9844d7f8dece6ec1a3df5199225d4686ce423
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.30.lean
8958819f97e524818c3e4553c1283674ec4214b9
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
81
lean
import standard import data.nat open [declarations] [notations] [coercions] nat
1d0615d47329d2f81fe18707f52a91071bca5b63
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/analysis/calculus/parametric_integral.lean
4346034a0ae444c55e874a6d818ed2704fbfff5c
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,576
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import measure_theory.integral.set_integral import analysis.calculus.mean_value /-! # Derivatives of integrals depending on parameters A parametric integral is a function with shape `f = λ x : H, ∫ a : α, F x a ∂μ` for some `F : H → α → E`, where `H` and `E` are normed spaces and `α` is a measured space with measure `μ`. We already know from `continuous_of_dominated` in `measure_theory.bochner_integral` how to guarantee that `f` is continuous using the dominated convergence theorem. In this file, we want to express the derivative of `f` as the integral of the derivative of `F` with respect to `x`. ## Main results As explained above, all results express the derivative of a parametric integral as the integral of a derivative. The variations come from the assumptions and from the different ways of expressing derivative, especially Fréchet derivatives vs elementary derivative of function of one real variable. * `has_fderiv_at_of_dominated_loc_of_lip`: this version assumes `F x` is ae-measurable for x near `x₀`, `F x₀` is integrable, `λ x, F x a` has derivative `F' a : H →L[ℝ] E` at `x₀` which is ae-measurable, `λ x, F x a` is locally Lipschitz near `x₀` for almost every `a`, with a Lipschitz bound which is integrable with respect to `a`. A subtle point is that the "near x₀" in the last condition has to be uniform in `a`. This is controlled by a positive number `ε`. * `has_fderiv_at_of_dominated_of_fderiv_le`: this version assume `λ x, F x a` has derivative `F' x a` for `x` near `x₀` and `F' x` is bounded by an integrable function independent from `x` near `x₀`. `has_deriv_at_of_dominated_loc_of_lip` and `has_deriv_at_of_dominated_loc_of_deriv_le ` are versions of the above two results that assume `H = ℝ` and use the high-school derivative `deriv` instead of Fréchet derivative `fderiv`. -/ noncomputable theory open topological_space measure_theory filter metric open_locale topological_space filter variables {α : Type*} [measurable_space α] {μ : measure α} {E : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [second_countable_topology E] [measurable_space E] [borel_space E] {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H →L[ℝ] E] /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` with integrable Lipschitz bound (with a ball radius independent of `a`), and `F x` is ae-measurable for `x` in the same ball. See `has_fderiv_at_of_dominated_loc_of_lip` for a slightly more general version. -/ lemma has_fderiv_at_of_dominated_loc_of_lip' {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ x ∈ ball x₀ ε, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have nneg : ∀ x, 0 ≤ ∥x - x₀∥⁻¹ := λ x, inv_nonneg.mpr (norm_nonneg _) , set b : α → ℝ := λ a, abs (bound a), have b_int : integrable b μ := bound_integrable.norm, have b_nonneg : ∀ a, 0 ≤ b a := λ a, abs_nonneg _, have hF_int' : ∀ x ∈ ball x₀ ε, integrable (F x) μ, { intros x x_in, have : ∀ᵐ a ∂μ, ∥F x₀ a - F x a∥ ≤ ε * ∥(bound a : ℝ)∥, { apply h_lipsch.mono, intros a ha, rw lipschitz_on_with_iff_norm_sub_le at ha, apply (ha x₀ x₀_in x x_in).trans, rw [mul_comm, nnreal.coe_nnabs, real.norm_eq_abs], rw [mem_ball, dist_eq_norm, norm_sub_rev] at x_in, exact mul_le_mul_of_nonneg_right (le_of_lt x_in) (abs_nonneg _) }, exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int (integrable.const_mul bound_integrable.norm ε) this }, have hF'_int : integrable F' μ, { have : ∀ᵐ a ∂μ, ∥F' a∥ ≤ b a, { apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_diff, ha_lip⟩, exact ha_diff.le_of_lip (ball_mem_nhds _ ε_pos) ha_lip }, exact b_int.mono' hF'_meas this }, refine ⟨hF'_int, _⟩, have h_ball: ball x₀ ε ∈ 𝓝 x₀ := ball_mem_nhds x₀ ε_pos, have : ∀ᶠ x in 𝓝 x₀, ∥x - x₀∥⁻¹ * ∥∫ a, F x a ∂μ - ∫ a, F x₀ a ∂μ - (∫ a, F' a ∂μ) (x - x₀)∥ = ∥∫ a, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀)) ∂μ∥, { apply mem_of_superset (ball_mem_nhds _ ε_pos), intros x x_in, rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul, integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int], exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int, hF'_int.apply_continuous_linear_map _] }, rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero, ← show ∫ (a : α), ∥x₀ - x₀∥⁻¹ • (F x₀ a - F x₀ a - (F' a) (x₀ - x₀)) ∂μ = 0, by simp], apply tendsto_integral_filter_of_dominated_convergence, { apply is_countably_generated_nhds }, { filter_upwards [h_ball], intros x x_in, apply ae_measurable.const_smul, exact ((hF_meas _ x_in).sub (hF_meas _ x₀_in)).sub (hF'_meas.apply_continuous_linear_map _) }, { simp [measurable_const] }, { apply mem_of_superset h_ball, intros x hx, apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_deriv, ha_bound⟩, show ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ ≤ b a + ∥F' a∥, replace ha_bound : ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥, { rw lipschitz_on_with_iff_norm_sub_le at ha_bound, exact ha_bound _ hx _ x₀_in }, calc ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ = ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a) - ∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : by rw smul_sub ... ≤ ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a)∥ + ∥∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : norm_sub_le _ _ ... = ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a∥ + ∥x - x₀∥⁻¹ * ∥F' a (x - x₀)∥ : by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _} ... ≤ ∥x - x₀∥⁻¹ * (b a * ∥x - x₀∥) + ∥x - x₀∥⁻¹ * (∥F' a∥ * ∥x - x₀∥) : add_le_add _ _ ... ≤ b a + ∥F' a∥ : _, exact mul_le_mul_of_nonneg_left ha_bound (nneg _), apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _), by_cases h : ∥x - x₀∥ = 0, { simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) }, { field_simp [h] } }, { exact b_int.add hF'_int.norm }, { apply h_diff.mono, intros a ha, suffices : tendsto (λ x, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))) (𝓝 x₀) (𝓝 0), by simpa, rw tendsto_zero_iff_norm_tendsto_zero, have : (λ x, ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a - F' a (x - x₀)∥) = λ x, ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥, { ext x, rw norm_smul_of_nonneg (nneg _) }, rwa [has_fderiv_at_iff_tendsto, this] at ha }, end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_loc_of_lip {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lip : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin obtain ⟨ε', ε'_pos, h'⟩ : ∃ ε' > 0, ∀ x ∈ ball x₀ ε', ae_measurable (F x) μ, by simpa using nhds_basis_ball.eventually_iff.mp hF_meas, set δ := min ε ε', have δ_pos : 0 < δ := lt_min ε_pos ε'_pos, replace h' : ∀ x, x ∈ ball x₀ δ → ae_measurable (F x) μ, { intros x x_in, exact h' _ (ball_subset_ball (min_le_right ε ε') x_in) }, replace h_lip : ∀ᵐ (a : α) ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ δ), { apply h_lip.mono, intros a lip, exact lip.mono (ball_subset_ball $ min_le_left ε ε') }, apply has_fderiv_at_of_dominated_loc_of_lip' δ_pos ; assumption end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_of_fderiv_le {F : H → α → E} {F' : H → α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x a) (F' x a) x) : has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ x, F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x x_in, (ha_deriv x x_in).has_fderiv_within_at) (λ x x_in, _), rw [← nnreal.coe_le_coe, coe_nnnorm, nnreal.coe_nnabs], exact (ha_bound x x_in).trans (le_abs_self _) }, exact (has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀).2 end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_lip {F : ℝ → α → E} {F' : α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) {bound : α → ℝ} (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' a) x₀) : (integrable F' μ) ∧ has_deriv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have hm := (continuous_linear_map.smul_rightL ℝ ℝ E 1).continuous.measurable.comp_ae_measurable hF'_meas, cases has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hm h_lipsch bound_integrable h_diff with hF'_int key, replace hF'_int : integrable F' μ, { rw [← integrable_norm_iff hm] at hF'_int, simpa only [integrable_norm_iff, hF'_meas, one_mul, norm_one, continuous_linear_map.norm_smul_rightL_apply] using hF'_int}, refine ⟨hF'_int, _⟩, simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊢, rwa continuous_linear_map.integral_comp_comm _ hF'_int at key, all_goals { apply_instance, }, end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_deriv_le {F : ℝ → α → E} {F' : ℝ → α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) {bound : α → ℝ} (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x a) (F' x a) x) : (integrable (F' x₀) μ) ∧ has_deriv_at (λn, ∫ a, F n a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ (x : ℝ), F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x x_in, (ha_deriv x x_in).has_deriv_within_at) (λ x x_in, _), rw [← nnreal.coe_le_coe, coe_nnnorm, nnreal.coe_nnabs], exact (ha_bound x x_in).trans (le_abs_self _) }, exact has_deriv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀ end
2cd786d314fb3308fb5e43f4cf78ce9cd5a7e302
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/set_theory/game/domineering.lean
7136e99fb010b3dfbcaf571dc2d25f4c61282130
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
7,937
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 set_theory.game.state /-! # Domineering as a combinatorial game. We define the game of Domineering, played on a chessboard of arbitrary shape (possibly even disconnected). Left moves by placing a domino vertically, while Right moves by placing a domino horizontally. This is only a fragment of a full development; in order to successfully analyse positions we would need some more theorems. Most importantly, we need a general statement that allows us to discard irrelevant moves. Specifically to domineering, we need the fact that disjoint parts of the chessboard give sums of games. -/ namespace pgame namespace domineering open function /-- The embedding `(x, y) ↦ (x, y+1)`. -/ def shift_up : ℤ × ℤ ↪ ℤ × ℤ := ⟨λ p : ℤ × ℤ, (p.1, p.2 + 1), have injective (λ (n : ℤ), n + 1) := λ _ _, (add_right_inj 1).mp, injective_id.prod this⟩ /-- The embedding `(x, y) ↦ (x+1, y)`. -/ def shift_right : ℤ × ℤ ↪ ℤ × ℤ := ⟨λ p : ℤ × ℤ, (p.1 + 1, p.2), have injective (λ (n : ℤ), n + 1) := λ _ _, (add_right_inj 1).mp, this.prod injective_id⟩ /-- A Domineering board is an arbitrary finite subset of `ℤ × ℤ`. -/ @[derive inhabited] def board := finset (ℤ × ℤ) local attribute [reducible] board /-- Left can play anywhere that a square and the square below it are open. -/ def left (b : board) : finset (ℤ × ℤ) := b ∩ b.map shift_up /-- Right can play anywhere that a square and the square to the left are open. -/ def right (b : board) : finset (ℤ × ℤ) := b ∩ b.map shift_right /-- After Left moves, two vertically adjacent squares are removed from the board. -/ def move_left (b : board) (m : ℤ × ℤ) : board := (b.erase m).erase (m.1, m.2 - 1) /-- After Left moves, two horizontally adjacent squares are removed from the board. -/ def move_right (b : board) (m : ℤ × ℤ) : board := (b.erase m).erase (m.1 - 1, m.2) lemma card_of_mem_left {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : 2 ≤ finset.card b := begin dsimp [left] at h, have w₁ : m ∈ b, { rw finset.mem_inter at h, exact h.1 }, have w₂ : (m.1, m.2 - 1) ∈ b.erase m, { simp only [finset.mem_erase], fsplit, { exact λ w, pred_ne_self m.2 (congr_arg prod.snd w) }, { rw finset.mem_inter at h, have h₂ := h.2, clear h, rw finset.mem_map at h₂, rcases h₂ with ⟨m', ⟨h₂, rfl⟩⟩, dsimp [shift_up], simpa, }, }, have i₁ := finset.card_erase_lt_of_mem w₁, have i₂ := nat.lt_of_le_of_lt (nat.zero_le _) (finset.card_erase_lt_of_mem w₂), exact nat.lt_of_le_of_lt i₂ i₁, end lemma card_of_mem_right {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : 2 ≤ finset.card b := begin dsimp [right] at h, have w₁ : m ∈ b, { rw finset.mem_inter at h, exact h.1 }, have w₂ : (m.1 - 1, m.2) ∈ b.erase m, { simp only [finset.mem_erase], fsplit, { exact λ w, pred_ne_self m.1 (congr_arg prod.fst w) }, { rw finset.mem_inter at h, have h₂ := h.2, clear h, rw finset.mem_map at h₂, rcases h₂ with ⟨m', ⟨h₂, rfl⟩⟩, dsimp [shift_right], simpa, }, }, have i₁ := finset.card_erase_lt_of_mem w₁, have i₂ := nat.lt_of_le_of_lt (nat.zero_le _) (finset.card_erase_lt_of_mem w₂), exact nat.lt_of_le_of_lt i₂ i₁, end lemma move_left_card {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : finset.card (move_left b m) + 2 = finset.card b := begin dsimp [move_left], rw finset.card_erase_of_mem, { rw finset.card_erase_of_mem, { exact nat.sub_add_cancel (card_of_mem_left h), }, { exact finset.mem_of_mem_inter_left h, } }, { apply finset.mem_erase_of_ne_of_mem, { exact λ w, pred_ne_self m.2 (congr_arg prod.snd w), }, { have t := finset.mem_of_mem_inter_right h, dsimp [shift_up] at t, simp only [finset.mem_map, prod.exists] at t, rcases t with ⟨x,y,w,h⟩, rw ←h, convert w, simp, } } end lemma move_right_card {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : finset.card (move_right b m) + 2 = finset.card b := begin dsimp [move_right], rw finset.card_erase_of_mem, { rw finset.card_erase_of_mem, { exact nat.sub_add_cancel (card_of_mem_right h), }, { exact finset.mem_of_mem_inter_left h, } }, { apply finset.mem_erase_of_ne_of_mem, { exact λ w, pred_ne_self m.1 (congr_arg prod.fst w), }, { have t := finset.mem_of_mem_inter_right h, dsimp [shift_right] at t, simp only [finset.mem_map, prod.exists] at t, rcases t with ⟨x,y,w,h⟩, rw ←h, convert w, simp, } } end lemma move_left_smaller {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : finset.card (move_left b m) / 2 < finset.card b / 2 := by simp [←move_left_card h, lt_add_one] lemma move_right_smaller {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : finset.card (move_right b m) / 2 < finset.card b / 2 := by simp [←move_right_card h, lt_add_one] /-- The instance describing allowed moves on a Domineering board. -/ instance state : state board := { turn_bound := λ s, s.card / 2, L := λ s, (left s).image (move_left s), R := λ s, (right s).image (move_right s), left_bound := λ s t m, begin simp only [finset.mem_image, prod.exists] at m, rcases m with ⟨_, _, ⟨h, rfl⟩⟩, exact move_left_smaller h end, right_bound := λ s t m, begin simp only [finset.mem_image, prod.exists] at m, rcases m with ⟨_, _, ⟨h, rfl⟩⟩, exact move_right_smaller h end, } end domineering /-- Construct a pre-game from a Domineering board. -/ def domineering (b : domineering.board) : pgame := pgame.of b /-- All games of Domineering are short, because each move removes two squares. -/ instance short_domineering (b : domineering.board) : short (domineering b) := by { dsimp [domineering], apply_instance } /-- The Domineering board with two squares arranged vertically, in which Left has the only move. -/ def domineering.one := domineering ([(0,0), (0,1)].to_finset) /-- The `L` shaped Domineering board, in which Left is exactly half a move ahead. -/ def domineering.L := domineering ([(0,2), (0,1), (0,0), (1,0)].to_finset) instance short_one : short domineering.one := by { dsimp [domineering.one], apply_instance } instance short_L : short domineering.L := by { dsimp [domineering.L], apply_instance } -- The VM can play small games successfully: -- #eval to_bool (domineering.one ≈ 1) -- #eval to_bool (domineering.L + domineering.L ≈ 1) -- We can check that `decidable` instances reduce as expected, -- and so our implementation of domineering is computable. -- run_cmd tactic.whnf `(by apply_instance : decidable (domineering.one ≤ 1)) >>= tactic.trace -- dec_trivial can handle most of the dictionary of small games described in [conway2001] example : domineering.one ≈ 1 := dec_trivial example : domineering.L + domineering.L ≈ 1 := dec_trivial example : domineering.L ≈ pgame.of_lists [0] [1] := dec_trivial example : (domineering ([(0,0), (0,1), (0,2), (0,3)].to_finset) ≈ 2) := dec_trivial example : (domineering ([(0,0), (0,1), (1,0), (1,1)].to_finset) ≈ pgame.of_lists [1] [-1]) := dec_trivial. -- The 3x3 grid is doable, but takes a minute... -- example : -- (domineering ([(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)].to_finset) ≈ -- pgame.of_lists [1] [-1]) := dec_trivial -- The 5x5 grid is actually 0, but brute-forcing this is too challenging even for the VM. -- #eval to_bool (domineering ([ -- (0,0), (0,1), (0,2), (0,3), (0,4), -- (1,0), (1,1), (1,2), (1,3), (1,4), -- (2,0), (2,1), (2,2), (2,3), (2,4), -- (3,0), (3,1), (3,2), (3,3), (3,4), -- (4,0), (4,1), (4,2), (4,3), (4,4) -- ].to_finset) ≈ 0) end pgame
9a48f68e3de1719afe899637fcc089babaa43138
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/archimedean.lean
eb52111ba783bf312e45f8ac579a856c2d4422ff
[ "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
13,682
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.field_power import data.rat /-! # Archimedean groups and fields. This file defines the archimedean property for ordered groups and proves several results connected to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural number `n` such that `x ≤ n • y`. ## Main definitions * `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean property. * `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making it into a `floor_ring`. * `round` defines a function rounding to the nearest integer for a linearly ordered field which is also a floor ring. ## Main statements * `ℕ`, `ℤ`, and `ℚ` are archimedean. -/ variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) namespace linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_int_smul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃ (k : ℤ), k • a ≤ g ∧ g < (k + 1) • a := begin let s : set ℤ := {n : ℤ | n • a ≤ g}, obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ), { assume n hn, apply (gsmul_le_gsmul_iff ha).mp, rw ← gsmul_coe_nat at hk, exact le_trans hn hk }, obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, refine ⟨m, hm, _⟩, by_contra H, linarith [hm' _ $ not_lt.mp H] end lemma exists_int_smul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃ (k : ℤ), 0 ≤ g - k • a ∧ g - k • a < a := begin obtain ⟨k, h1, h2⟩ := exists_int_smul_near_of_pos ha g, rw add_gsmul at h2, refine ⟨k, sub_nonneg.mpr h1, _⟩, simpa [sub_lt_iff_lt_add'] using h2 end end linear_ordered_add_comm_group theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := begin nontriviality α, exact (exists_nat_gt x).imp (λ n, le_of_lt) end lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le, let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n • y : h ... = n * y : nsmul_eq_mul _ _ ... < 1 + n * y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this) (add_nonneg zero_le_two hy.le) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_int_pow_near'`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by { rw [fpow_neg y (↑N), gpow_coe_nat], exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm (by rwa ← gpow_coe_nat at hM)))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_int_pow_near`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near' [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, le_inv hx (fpow_pos_of_pos hyp _)]⟩ /-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/ lemma exists_pow_lt_of_lt_one [archimedean α] {x y : α} (hx : 0 < x) (hy : y < 1) : ∃ n : ℕ, y ^ n < x := begin by_cases y_pos : y ≤ 0, { use 1, simp only [pow_one], linarith, }, rw [not_le] at y_pos, rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩, exact ⟨q, by rwa [inv_pow', inv_lt_inv hx (pow_pos y_pos _)] at hq⟩ end /-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`. This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/ lemma exists_nat_pow_near_of_lt_one [archimedean α] {x : α} {y : α} (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) : ∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n := begin rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩) with ⟨n, hn, h'n⟩, refine ⟨n, _, _⟩, { rwa [inv_pow', inv_lt_inv xpos (pow_pos ypos _)] at h'n }, { rwa [inv_pow', inv_le_inv (pow_pos ypos _) xpos] at hn } end variables [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh, have n0 := nat.cast_pos.1 n0', rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 end linear_ordered_field section variables [linear_ordered_field α] [floor_ring α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round (x : α) : ℤ := ⌊x + 1 / 2⌋ @[simp] lemma round_zero : round (0 : α) = 0 := floor_eq_iff.2 (by norm_num) @[simp] lemma round_one : round (1 : α) = 1 := floor_eq_iff.2 (by norm_num) lemma abs_sub_round (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end @[simp, norm_cast] theorem rat.cast_floor (x : ℚ) : ⌊(x:α)⌋ = ⌊x⌋ := floor_eq_iff.2 (by exact_mod_cast floor_eq_iff.1 (eq.refl ⌊x⌋)) @[simp, norm_cast] theorem rat.cast_ceil (x : ℚ) : ⌈(x:α)⌉ = ⌈x⌉ := by rw [ceil, ← rat.cast_neg, rat.cast_floor, ← ceil] @[simp, norm_cast] theorem rat.cast_round (x : ℚ) : round (x:α) = round x := have ((x + 1 / 2 : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end section variables [linear_ordered_field α] [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ end
d8bb2dc20af2d5f1680ca6679fa297ed7cc2c704
6c56e3fbe5d7711b66a3b46f1810b44cfa109768
/src/week3 day1.lean
28a59c000b145b07367a9eb098103ef9dcdefa07
[]
no_license
kodyvajjha/lean-mmc2021
015e7ba9d2f43397582d42ad282e88c8ce876dc3
cc774208f9dc041cad4def289357301b4a0a8173
refs/heads/master
1,689,416,888,246
1,630,161,054,000
1,630,161,054,000
384,140,257
1
0
null
null
null
null
UTF-8
Lean
false
false
24,584
lean
-- need the real numbers import data.real.basic -- need the tactics import tactic /- # Limits We develop a theory of limits of sequences a₀, a₁, a₂, … of reals, following the way is it traditionally done in a first year undergraduate mathematics course. ## Overview of the file This file contains the basic definition of the limit of a sequence, and proves basic properties about it. The `data.real.basic` import imports the definition and basic properties of the real numbers, including, for example, the absolute value function `abs : ℝ → ℝ`, and the proof that `ℝ` is a complete totally ordered archimedean field. To get `ℝ` in Lean, type `\R`. We define the predicate `is_limit (a : ℕ → ℝ) (l : ℝ)` to mean that `aₙ → l` in the usual way: `∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε` We then develop the basic theory of limits. ## Main theorems variables (a b c : ℕ → ℝ) (c l m : ℝ) * `is_limit_const : is_limit (λ n, c) c` * `is_limit_subsingleton (hl : is_limit a l) (hm : is_limit a m) : l = m` * `is_limit_add (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a + b) (l + m)` * `is_limit_mul (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a * b) (l * m)` * `is_limit_le_of_le (hl : is_limit a l) (hm : is_limit b m) (hle : ∀ n, a n ≤ b n) : l ≤ m` * `sandwich (ha : is_limit a l) (hc : is_limit c l) (hab : ∀ n, a n ≤ b n) (hbc : ∀ n, b n ≤ c n) : is_limit b l` -/ namespace xena -- the maths starts here. -- We introduce the usual mathematical notation for absolute value local notation `|` x `|` := abs x -- We model a sequence a₀, a₁, a₂,... of real numbers as a function -- from ℕ := {0,1,2,...} to ℝ, sending n to aₙ . So in the below -- definition of the limit of a sequence, a : ℕ → ℝ is the sequence. /-- `l` is the limit of the sequence `a` of reals -/ definition is_limit (a : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε /- Note that `is_limit` is not a *function* (ℕ → ℝ) → ℝ! It is a _binary relation_ on (ℕ → ℝ) and ℝ, i.e. it's a function which takes as input a sequence and a candidate limit, and returns the true-false statement saying that the sequence converges to the limit. The reason we can't use a "limit" function, which takes in a sequence and returns its limit, is twofold: (1) some sequences (like 0, 1, 0, 1, 0, 1,…) don't have a limit at all, and (2) at this point in the development, some sequences might in theory have more than one limit (and if we were working with a non-Hausdorff topological space rather than `ℝ` this could of course actually happen, although we will see below that it can't happen here). -/ /- Let's start with a warmup : the constant sequence with value c tends to c. Before we start though, I need to talk about this weird `λ` notation which functional programmers use. ### λ notation for functions This is a lot less scary than it looks. The notation `λ n, f n` in Lean just means what we mathematicians would call `f` or `f(x)`. Literally, it means "the function sending `n` to `f n`, with this added twist that we don't need to write the brackets (although `λ n, f(n)` would also work fine). Another way of rewriting it in a more familiar manner: `λ n, f n` is the function `n ↦ f n`. So, for example, `λ n, 2 * n` is just the function `f(x)=2*x`. It's sometimes called "anonymous function notation" because we do not need to introduce a name for the function if we use lambda notation. So you need to know a trick here. What happens if we have such a function defined by lambda notation, and then we actually try to evaluate it! You have to know how to change `(λ n, f n) (37)` into `f(37)` (or, as Lean would call it, `f 37`). Computer scientists call this transformation "beta reduction". In Lean, beta reduction is true definitionally, so if you are using `apply` or `intro` or other tactics which work up to definitional equality then you might not even have to change it at all. But if your goal contains an "evaluated λ" like `⊢ (λ n, f n) 37` and you have a hypothesis `h1 : f 37 = 100` then `rw h1` will fail, because `rw` is pickier and only worked up to syntactic equality. So you need to know the trick to change this goal to `f 37`, which is the tactic `dsimp only`. It works on hypotheses too -- `dsimp only at h` will remove an evaluated `λ` from hypothesis `h`. We will now prove that the limit of a constant sequence `aₙ = c` is `c`. The definition of the constant sequence is `λ n, c`, the function sending every `n` to `c`. I have given you the proof. Step through it by moving your cursor through it line by line and watch the tactic state changing. -/ example : ℕ → ℕ := λ n, n /-- The limit of a constant sequence is the constant. -/ lemma is_limit_const (c : ℝ) : is_limit (λ n, c) c := begin -- rw is_limit, -- not completely (but somewhat) redundant code intros ε hε, simp only [abs_zero, sub_self], refine ⟨1, λ n hn, hε⟩, end /- I am going to walk you through the next proof as well. It's a proof that if `aₙ → l` and `aₙ → m` then `l = m`. Here is how it is stated in Lean: ``` theorem is_limit_subsingleton {a : ℕ → ℝ} {l m : ℝ} (hl : is_limit a l) (hm : is_limit a m) : l = m := ... ``` Before we go through this proof, I think it's time I explained these squiggly brackets properly. How come I've written `{a : ℕ → ℝ}` and not `(a : ℕ → ℝ)`? ### Squiggly brackets {} in function inputs, and dependent functions. `is_limit_subsingleton` is a proof that a sequence can have at most one limit. It is also a function. Learning to think about proofs as functions is an important skill for proving the theorems in this workshop. So let's talk a bit about how a proof can be a function. In Lean's dependent type theory, there are types and terms, and every term has a unique type. Types and terms are used to unify two ideas which mathematicians usually regard as completely different: that of sets and elements, and that of theorems and proofs. Let's take a close look at what exactly this function `is_limit_subsingleton` does. Let's take a closer look at `is_limit_subsingleton` (the theorem is stated 20 lines above here). It is a function with five inputs. The first input is a sequence `a : ℕ → ℝ`. The second and third are real numbers `l` and `m`. The fourth input is a proof that `a(n)` tends to `l`, and the fifth is a proof that `a(n)` tends to `m`. The output of the function (after the colon) is a proof that `l = m`. This is how Lean thinks about proofs internally, and it's important that you internalise this point of view because you will be treating proofs as functions and evaluating them on inputs to get other proofs quite a bit today. If you still think it's a bit weird having proofs as inputs and outputs to functions, just think of a true-false statement (e.g. a theorem statement) as being a set, and the elements of that set are the proofs of the theorem. For example `2 + 2 = 5` is a set with no elements, because there are no proofs of this theorem (assuming that mathematics is consistent). Now if you think about these inputs carefully, and you think about your mental model of a function, you may realised that there is something else a bit fishy going on here. Usually you would think of a function with five inputs as a function from `A × B × C × D × E` to `X`, where `A`, `B`, `C`, `D` and `E` are all sets. The first three inputs `a` (of type `ℕ → ℝ`) and `l` and `m` (of type `ℝ`) are uncontroversial: we can just set `A = ℕ → ℝ` and `B = C = ℝ`. But the fourth input to `is_limit_singleton` is an element of the set of proofs of `is_limit a l`, the statement that `a(n)` tends to `l`, and in particular this set itself *depends on the first two inputs*. The set `D` itself is a function of `a` and `l` -- the actual inputs themselves, rather than the sets `A` and `B` that they belong to. The same is true for the set `E`, which is a function of `a` and `m`. This slightly bizarre set-up has the even more bizarre consequence that actually, if Lean knows the fourth and fifth inputs (in this case, proofs of `is_limit a l` and `is_limit a m`) then it *does not actually even need to know what the first three inputs are*, because Lean can work them out from the *type* of the fourth and fifth inputs. In summary then, the five inputs to this functions are: `a` of type `ℕ → ℝ`, `l` and `m` of type `ℝ`, `h1` of type `is_limit a l` `h2` of type `is_limit a m`. In particular, if we know the fourth and fifth inputs `h1` and `h2`, then by looking at the types of these terms, we can actually work out what the first three inputs *have to be* in order to make everything make sense. This is why we put the first three inputs in `{}` brackets. This means "these inputs are part of the function, but Lean's *unification system* (the part of the system which checks that everything has the right type) will work them out automatically, so we will not trouble the user by asking for them". In short, if we ever run this function of five inputs, we can just give `h1` and `h2` and let Lean figure out the first three inputs itself. In general if a function input has `{}` brackets then the user does not have to supply those inputs, the user can trust the system to fill them in automatically. That's quite enough about the statement! Let's get back to mathematics and I will talk you through the proof. Step through the proof line by line and watch the tactic state change. -/ theorem is_limit_subsingleton {a : ℕ → ℝ} {l m : ℝ} (hl : is_limit a l) (hm : is_limit a m) : l = m := begin by_contra h, -- For the naturals, l - m is NOT the same as l - m in the integers. -- For the naturals, l - m = l -m if m ≤ l, else 0 set ε := |m - l| with hε, have f : (ε/2) > 0, { apply half_pos, rw abs_pos, intro g, apply h, sorry,}, obtain ⟨n1, hl'⟩ := hl (ε/2) f, obtain ⟨n2, hm'⟩ := hm (ε/2) f, -- `obtain` combines `have` and `cases` set n := max n1 n2 with hn, have g1 : n ≥ n1, { apply le_max_left, }, specialize hl' n g1, have g2 : n ≥ n2, { apply le_max_right, }, specialize hm' n g2, have : | m - l | < ε, { have abs_sub' := abs_sub_le m (a n) l, -- a < b and c < d, then a + b < c + d, have f1 := add_lt_add hm' hl', rw abs_sub at f1, -- a ≤ b and b < c, get a < c convert (lt_of_le_of_lt abs_sub' f1), linarith, }, rw hε at this, apply lt_irrefl _ this, /- -- There are several ways to prove this, but let's prove it -- by contradiction. Let's assume `h : l ≠ m` and prove `false`. by_contra h, -- The idea is that if `ε = |l - m|` then the sequence `a` will -- eventually be within `ε/2` of `l` and `ε/2` of `m`, which -- will be a contradiction. To make life easier let's break -- the symmetry and assume WLOG that `l < m`, because then -- we can just let `ε` be `m - l`. wlog hlm : l < m, -- Lean checks that everything is symmetric in `l` and `m` so -- this tactic succeeds, but asks us to prove that either -- `l < m` or `m < l`. We now have two goals so let's -- put a `{` `}` pair to get back to one goal. { -- now we just have the one easy goal `l < m ∨ m < l`. -- First we note that the reals are totally ordered so -- we can add `l < m ∨ l = m ∨ m < l` to the list of -- hypotheses with the `have` tactic: have : l < m ∨ l = m ∨ m < l := lt_trichotomy l m, -- Now the result follows from pure logic. tauto }, -- Now let's define ε to be m - l. set ε := m - l with hε, -- Mathematically, the plan is to now find big natural numbers `L` and `M` -- such that `n ≥ L → |a n - l| < ε/2`, and `n ≥ M → |a n - m| < ε/2`, -- and then set `n = max L M` to get a contradiction. How do we do this -- in Lean? -- Well, let's think about `hl` as a function. Its type is -- `is_limit a l` which is definitionally `∀ ε, ε > 0 → ...`. -- So `hl` is a function which wants as an input a real number -- and a proof that it is positive. Let's first give `hl` the -- real number `ε/2` once and for all (it's the only time we'll -- be using `hl` in the proof so we can change its definition) specialize hl (ε/2), -- Now `hl` is a function which wants a proof by `ε/2>0` as its input. -- Mathematically, this is obvious: `ε/2=(m-l)/2` and `l < m`. -- Lean's `linarith` (linear arithmetic) tactic can solve this sort of goal: have hε2 : ε/2 > 0 := by linarith, -- Now we can specialize `hl` further: specialize hl hε2, -- Now `hl` isn't a function any more. In the lingo, it's an inductive -- type rather than a pi type. -- `hl : ∃ (N : ℕ), ∀ (n : ℕ), n ≥ N → |a n - l| < ε / 2` -- `hl` is now a made from a pair of pieces of information: first a natural -- number `N`, and second a proof of some fact about `N`. We can take -- `hl` apart into these two pieces with the `cases` tactic: cases hl with L hL, -- Now `L` is the natural and `hL` is a proof of a theorem about it: -- `hL : ∀ (n : ℕ), n ≥ L → |a n - l| < ε / 2` -- We now need to do the same thing with `hm`. Let's just do it all in one -- go. Check that you understand why this one line does the same sort of thing -- as the four lines above. cases hm (ε/2) (by linarith) with M hM, -- Now let's get back to the maths proof. Let N be the max of L and M. set N := max L M with hN, -- Let's record here the fact that `L ≤ N` and `M ≤ N`. I found -- these proofs by using `library_search` and then clicking on "Try this!". -- For example -- `have hLN : L ≤ N := by library_search`, have hLN : L ≤ N := le_max_left L M, have hMN : M ≤ N := le_max_right L M, -- We're going to set `n = N` in `hL` and `hM`. Again I'm thinking -- of these things as functions. specialize hL N hLN, specialize hM N hMN, -- It looks like we should be done now: everything should follow -- now from chasing inequalities. We need to give Lean one more hint -- though, because `linarith` doesn't know anything about the `abs` function; -- we need to know that |x|<ε/2 is the same as `-ε/2 < x ∧ x < ε/2`. -- This theorem is called `abs_lt` ("absolute value is less than"). rw abs_lt at hL hM, -- As a challenge, can you now look at the tactic state and finish the proof -- on paper? Lean's `linarith` tactic can see its way through the inequality -- maze. Let's finish this proof and talk about `linarith` and another -- high-powered tactic, `ring`. linarith, -/ end /- Two quick comments on some other new things in the above proof: 1) We will be using `max` a lot in this workshop. `max A B` is the max of `A` and `B`. `max` is a definition, not a theorem, so that means that there will be an API associated with it, i.e. a list of little theorems which make `max` possible to use. We just saw the two important theorems which we'll be using: `le_max_left A B : A ≤ max A B` and `le_max-right A B : B ≤ max A B`. There are other cool functions in the `max` API, for example `max_le : A ≤ C → B ≤ C → max A B ≤ C`. The easiest way to find your way around the `max` API is to *guess* what the names of the theorems are! For example what do you think `max A B < C ↔ A < C ∧ B < C` is called? If you can't work it out, then cheat by running ``` example (A B C : ℝ) : max A B < C ↔ A < C ∧ B < C := begin library_search end ``` 2) `specialize` is a tactic which changes a function by fixing once and for all the first inputs. For example, say `f : A → B → C → D` is a function. Because `→` is right associative in Lean, `f` is a function which wants an input from `A`, and then spits out a function which wants an input from `B`, and spits out a function which wants an input from `C` and spits out an element of `D`. So really it's just a function which takes three inputs, one from `A`, one from `B` and one from `C`, and spits out something in `D`. This is what computer scientists call "currying". Now say I have `a : A` and I want this to be my first input to `f`, and I never want to run `f` again with any other inputs from `A`. Then `specialize f a` will feed `a` into `f` and then rename `f` to be the resulting new function `B → C → D`. -/ -- Before we go on, I need to explain two more high-powered tactics. /- ## `linarith` and `ring` `linarith` and `ring` are two high-powered tactics. It's important to know their "scope". ### `ring` Let's start with `ring`. The `ring` tactic will prove any goal which can be deduced from the axioms of a commutative ring (or even a commutative semiring like `ℕ`). For example if `(x y : ℝ)` and the goal is `(x+y)^3=x^3+3*x^2*y+3*x*y^2+y^3` then `ring` will close this goal. In the proof of `is_limit_add` below in my solutions file, I use `ring` to prove `a n + b n - (l + m) = (a n - l) + (b n - m)` and to prove `ε/2 + ε/2 = ε`. Note that `ring` will get confused if it sees `λ` terms and so on, it works up to syntactic equality. `ring` wants to see a clean statement about elements of a ring involving only `+`, `-` and `*`. Note also that `ring` does not look at hypotheses -- it works on the goal only. So for example `ring` will not solve this goal directly: ``` a b c : ℝ ha : a = b + c ⊢ 2 * a = b + b + c + c ``` To solve this goal you need to do `rw ha` and then `ring`. ### `linarith` `linarith` solves linear inequalities. For example it will solve this goal: ``` a b c : ℝ hab : a ≤ b hbc : b < c ⊢ a ≤ c + 1 ``` Note that it will not do your logic for you though. For example it will not solve this goal: ``` a b c : ℝ hab : a ≤ b hbc : a ≤ b → b < c ⊢ a ≤ c + 1 ``` even though `b < c` is "obviously true because of `hab`", `linarith` can't see it. The *one* thing it can see through is `∧` in hypotheses: it will solve this goal. ``` a b c : ℝ h : a ≤ b ∧ b < c ⊢ a ≤ c + 1 ``` However it will not see through `∧` in goals; it will not solve this. ``` a b c : ℝ h : a ≤ b ∧ b < c ⊢ a ≤ c + 1 ∧ a ≤ c + 1 ``` To solve this goal, use `split; linarith`. The semicolon means "apply the next tactic to all goals created by the previous tactic". If you're unsure whether `linarith` can see an inequality, just isolate it as a hypothesis or goal all by itself. Then `linarith` can definitely see it. -/ /- ## convert While we're here, here is an explanation of one more high-powered tactic. If your goal is `⊢ P` and you have a hypothesis `h : P'` where `P` and `P'` only differ slightly, then `convert h'` will replace the goal with new goals asking for justification that all the places where `P` and `P'` differ are equal. Here's an example: -/ example (a b : ℝ) (h : a * 2 = b + 1) : a + a = b - (-1) := begin -- rw `h` won't work because we don't have a complete match on either -- side of the equality. convert h, -- now two goals: `a + a = a * 2` and `b - -1 = b + 1` { ring }, { ring } end /- An example where things can go a bit wrong is below. Uncomment the `convert h` line to see a failure, and then you'll understand the fix. -/ example (a b : ℝ) (h : a * 2 = b + 1) : a + a = 1 + b := begin -- uncomment this to see something unfortunate happen: -- convert h, convert h using 1, -- change to 2 or more to see the unfortunate thing again { ring }, { ring } end /- OK it's time to actually do some mathematics! Why don't we start by looking at what happens when we change a sequence or limit by adding a constant. -/ lemma is_limit_add_const {a : ℕ → ℝ} {l : ℝ} (c : ℝ) (ha : is_limit a l) : is_limit (λ i, a i + c) (l + c) := begin intros ε hε, specialize ha ε hε, cases ha with N ha, refine ⟨N, λ n hn, _⟩, -- want a + b - (c + b) = a - c rw add_sub_add_right_eq_sub, apply ha n hn, end lemma is_limit_add_const_iff {a : ℕ → ℝ} {l : ℝ} (c : ℝ) : is_limit a l ↔ is_limit (λ i, a i + c) (l + c) := iff.intro (is_limit_add_const c) (λ ha, begin have f2 : a = λ i : ℕ, a i + c + -c := by simp only [add_neg_cancel_right], rw [f2, ←add_neg_cancel_right l c], apply is_limit_add_const _ ha, end ) lemma is_limit_iff_is_limit_sub_eq_zero (a : ℕ → ℝ) (l : ℝ) : is_limit a l ↔ is_limit (λ i, a i - l) 0 := begin sorry, end /- We now prove that if aₙ → l and bₙ → m then aₙ + bₙ → l + m. Here is the proof that I recommend you formalise: choose L large enough so that n ≥ L implies |aₙ - l|<ε/2 choose M large enough so that n ≥ M implies |bₙ - m|<ε/2 Now N := max M₁ M₂ works. Some extra things you may need to know: `pi.add_apply a b : (a + b) n = a n + b n` `abs_add x y : |x + y| ≤ |x| + |y|` Good luck! -/ theorem is_limit_add {a b : ℕ → ℝ} {l m : ℝ} (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a + b) (l + m) := begin intros ε hε, cases h1 ε hε with n1 h1, cases h2 ε hε with n2 h2, sorry, end -- We have proved `is_limit` behaves well under `+`. If we also -- prove that it behaves well under scalar multiplication, we can -- deduce that it's linear. So let's do this next. -- Helpful things: -- `abs_pos : 0 < |a| ↔ a ≠ 0` -- `div_pos : 0 < a → 0 < b → 0 < a / b` -- `abs_mul x y : |x * y| = |x| * |y|` -- `lt_div_iff' : 0 < c → (a < b / c ↔ c * a < b)` -- I typically find these things myself with a combination of -- the "guess the name of the lemma" game (and ctrl-space), and `library_search` -- A hint for starting: -- It might be worth dealing with `c = 0` as a special case. You -- can start with -- `by_cases hc : c = 0` lemma is_limit_mul_const_left {a : ℕ → ℝ} {l c : ℝ} (h : is_limit a l) : is_limit (λ n, c * (a n)) (c * l) := begin sorry, end -- This should just be a couple of lines now. lemma is_limit_linear (a : ℕ → ℝ) (b : ℕ → ℝ) (α β c d : ℝ) (ha : is_limit a α) (hb : is_limit b β) : is_limit ( λ n, c * (a n) + d * (b n) ) (c * α + d * β) := begin sorry, end -- We need the below result to prove that product of limits is limit -- of products. -- Rather than using `√ε`, just choose `N` large enough such that `|a n| ≤ ε` -- and `|b n| ≤ 1` if `n ≥ N`; this will work. lemma is_limit_mul_eq_zero_of_is_limit_eq_zero {a : ℕ → ℝ} {b : ℕ → ℝ} (ha : is_limit a 0) (hb : is_limit b 0) : is_limit (a * b) 0 := begin sorry, end -- The limit of the product is the product of the limits. -- If aₙ → l and bₙ → m then aₙ * bₙ → l * m. -- Here's the proof I recommend. Start with -- `suffices : is_limit (λ i, (a i - l) * (b i - m) + (l * (b i - m)) + m * (a i - l)) 0,` -- (note: this multiplies out to `a i * b i - l * m`) -- and then prove that all three terms in the sum tend to zero. theorem is_limit_mul (a : ℕ → ℝ) (b : ℕ → ℝ) (l m : ℝ) (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a * b) (l * m) := begin sorry, end -- If aₙ → l and bₙ → m, and aₙ ≤ bₙ for all n, then l ≤ m theorem is_limit_le_of_le (a : ℕ → ℝ) (b : ℕ → ℝ) (l : ℝ) (m : ℝ) (hl : is_limit a l) (hm : is_limit b m) (hle : ∀ n, a n ≤ b n) : l ≤ m := begin sorry, end -- sandwich theorem sandwich (a b c : ℕ → ℝ) (l : ℝ) (ha : is_limit a l) (hc : is_limit c l) (hab : ∀ n, a n ≤ b n) (hbc : ∀ n, b n ≤ c n) : is_limit b l := begin sorry, end -- Let's make a new definition. definition is_bounded (a : ℕ → ℝ) := ∃ B, ∀ n, |a n| ≤ B -- Now try this: lemma tendsto_bounded_mul_zero {a : ℕ → ℝ} {b : ℕ → ℝ} (hA : is_bounded a) (hB : is_limit b 0) : is_limit (a*b) 0 := begin intros ε hε, cases hA with c hA, cases hB (ε/(c + 1)) _ with N hB, { refine ⟨N, λ n hn, _⟩, specialize hB n hn, specialize hA n, rw sub_zero at *, have : 0 ≤ c, sorry, -- why do you need this? -- use `mul_le_mul` sorry, }, sorry, end -- might be needing the bound to be non negative ahead, try to make a lemma saying the same -- we can make more definitions def is_cauchy (a : ℕ → ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ m ≥ N, ∀ n ≥ N, |a m - a n| < ε -- and of course one can go on and on and on end xena -- Take a look at `Part_A_limits_appendix.lean` to see some rather -- shorter proofs! We will talk about these proofs next week. Perhaps -- you can try and investigate what is going on, by hovering on things -- like `tendsto`. Hint: filters.
fc8aef04b58d5fe0087148bb79b310268b8d2f77
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/closed/cartesian.lean
179daffe19bb40167242204798d20555c96c08e2
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
14,748
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 := (exp.adjunction A).counit /-- The coevaluation natural transformation. -/ def coev : 𝟭 C ⟶ prod.functor.obj A ⋙ exp A := (exp.adjunction A).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) := (exp.adjunction A).hom_equiv _ _ /-- Uncurrying in a cartesian closed category. -/ def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) := ((exp.adjunction A).hom_equiv _ _).symm @[simp] lemma hom_equiv_apply_eq (f : A ⨯ Y ⟶ X) : (exp.adjunction A).hom_equiv _ _ f = curry f := rfl @[simp] lemma hom_equiv_symm_apply_eq (f : Y ⟶ A ⟹ X) : ((exp.adjunction A).hom_equiv _ _).symm f = uncurry f := rfl 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. -/ lemma 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 _, begin haveI := strict_initial t g, haveI := strict_initial t h, exact eq_of_inv_eq_inv (t.hom_ext _ _) end⟩ 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 } } end functor end category_theory
d478863f2cea0158d5af62b1896c114575488b37
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/ordinal/fixed_point.lean
f835a513fc28ec425f8fe57a5cd330061fd64461
[ "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
23,277
lean
/- Copyright (c) 2018 Violeta Hernández Palacios, Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios, Mario Carneiro -/ import set_theory.ordinal.arithmetic /-! # Fixed points of normal functions We prove various statements about the fixed points of normal ordinal functions. We state them in three forms: as statements about type-indexed families of normal functions, as statements about ordinal-indexed families of normal functions, and as statements about a single normal function. For the most part, the first case encompasses the others. Moreover, we prove some lemmas about the fixed points of specific normal functions. ## Main definitions and results * `nfp_family`, `nfp_bfamily`, `nfp`: the next fixed point of a (family of) normal function(s). * `fp_family_unbounded`, `fp_bfamily_unbounded`, `fp_unbounded`: the (common) fixed points of a (family of) normal function(s) are unbounded in the ordinals. * `deriv_add_eq_mul_omega_add`: a characterization of the derivative of addition. * `deriv_mul_eq_opow_omega_mul`: a characterization of the derivative of multiplication. -/ noncomputable theory universes u v open function order namespace ordinal /-! ### Fixed points of type-indexed families of ordinals -/ section variables {ι : Type u} {f : ι → ordinal.{max u v} → ordinal.{max u v}} /-- The next common fixed point, at least `a`, for a family of normal functions. `ordinal.nfp_family_fp` shows this is a fixed point, `ordinal.le_nfp_family` shows it's at least `a`, and `ordinal.nfp_family_le_fp` shows this is the least ordinal with these properties. -/ def nfp_family (f : ι → ordinal → ordinal) (a) : ordinal := sup (list.foldr f a) theorem nfp_family_eq_sup (f : ι → ordinal → ordinal) (a) : nfp_family f a = sup (list.foldr f a) := rfl theorem foldr_le_nfp_family (f : ι → ordinal → ordinal) (a l) : list.foldr f a l ≤ nfp_family f a := le_sup _ _ theorem le_nfp_family (f : ι → ordinal → ordinal) (a) : a ≤ nfp_family f a := le_sup _ [] theorem lt_nfp_family {a b} : a < nfp_family f b ↔ ∃ l, a < list.foldr f b l := lt_sup theorem nfp_family_le_iff {a b} : nfp_family f a ≤ b ↔ ∀ l, list.foldr f a l ≤ b := sup_le_iff theorem nfp_family_le {a b} : (∀ l, list.foldr f a l ≤ b) → nfp_family f a ≤ b := sup_le theorem nfp_family_monotone (hf : ∀ i, monotone (f i)) : monotone (nfp_family f) := λ a b h, sup_le $ λ l, (list.foldr_monotone hf l h).trans (le_sup _ l) theorem apply_lt_nfp_family (H : ∀ i, is_normal (f i)) {a b} (hb : b < nfp_family f a) (i) : f i b < nfp_family f a := let ⟨l, hl⟩ := lt_nfp_family.1 hb in lt_sup.2 ⟨i :: l, (H i).strict_mono hl⟩ theorem apply_lt_nfp_family_iff [nonempty ι] (H : ∀ i, is_normal (f i)) {a b} : (∀ i, f i b < nfp_family f a) ↔ b < nfp_family f a := ⟨λ h, lt_nfp_family.2 $ let ⟨l, hl⟩ := lt_sup.1 (h (classical.arbitrary ι)) in ⟨l, ((H _).self_le b).trans_lt hl⟩, apply_lt_nfp_family H⟩ theorem nfp_family_le_apply [nonempty ι] (H : ∀ i, is_normal (f i)) {a b} : (∃ i, nfp_family f a ≤ f i b) ↔ nfp_family f a ≤ b := by { rw ←not_iff_not, push_neg, exact apply_lt_nfp_family_iff H } theorem nfp_family_le_fp (H : ∀ i, monotone (f i)) {a b} (ab : a ≤ b) (h : ∀ i, f i b ≤ b) : nfp_family f a ≤ b := sup_le $ λ l, begin by_cases hι : is_empty ι, { rwa @unique.eq_default _ (@list.unique_of_is_empty ι hι) l }, { haveI := not_is_empty_iff.1 hι, induction l with i l IH generalizing a, {exact ab}, exact (H i (IH ab)).trans (h i) } end theorem nfp_family_fp {i} (H : is_normal (f i)) (a) : f i (nfp_family f a) = nfp_family f a := begin unfold nfp_family, rw @is_normal.sup _ H _ _ ⟨[]⟩, apply le_antisymm; refine ordinal.sup_le (λ l, _), { exact le_sup _ (i :: l) }, { exact (H.self_le _).trans (le_sup _ _) } end theorem apply_le_nfp_family [hι : nonempty ι] {f : ι → ordinal → ordinal} (H : ∀ i, is_normal (f i)) {a b} : (∀ i, f i b ≤ nfp_family f a) ↔ b ≤ nfp_family f a := begin refine ⟨λ h, _, λ h i, _⟩, { unfreezingI { cases hι with i }, exact ((H i).self_le b).trans (h i) }, rw ←nfp_family_fp (H i), exact (H i).monotone h end theorem nfp_family_eq_self {f : ι → ordinal → ordinal} {a} (h : ∀ i, f i a = a) : nfp_family f a = a := le_antisymm (sup_le (λ l, (by rw list.foldr_fixed' h l))) (le_nfp_family f a) /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem fp_family_unbounded (H : ∀ i, is_normal (f i)) : (⋂ i, function.fixed_points (f i)).unbounded (<) := λ a, ⟨_, λ s ⟨i, hi⟩, begin rw ←hi, exact nfp_family_fp (H i) a end, (le_nfp_family f a).not_lt⟩ /-- The derivative of a family of normal functions is the sequence of their common fixed points. -/ def deriv_family (f : ι → ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp_family f 0) (λ a IH, nfp_family f (succ IH)) (λ a l, bsup.{(max u v) u} a) @[simp] theorem deriv_family_zero (f : ι → ordinal → ordinal) : deriv_family f 0 = nfp_family f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_family_succ (f : ι → ordinal → ordinal) (o) : deriv_family f (succ o) = nfp_family f (succ (deriv_family f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_family_limit (f : ι → ordinal → ordinal) {o} : is_limit o → deriv_family f o = bsup.{(max u v) u} o (λ a _, deriv_family f a) := limit_rec_on_limit _ _ _ _ theorem deriv_family_is_normal (f : ι → ordinal → ordinal) : is_normal (deriv_family f) := ⟨λ o, by rw [deriv_family_succ, ← succ_le_iff]; apply le_nfp_family, λ o l a, by rw [deriv_family_limit _ l, bsup_le_iff]⟩ theorem deriv_family_fp {i} (H : is_normal (f i)) (o : ordinal.{max u v}) : f i (deriv_family f o) = deriv_family f o := begin refine limit_rec_on o _ (λ o IH, _) _, { rw [deriv_family_zero], exact nfp_family_fp H 0 }, { rw [deriv_family_succ], exact nfp_family_fp H _ }, { intros o l IH, rw [deriv_family_limit _ l, is_normal.bsup.{(max u v) u (max u v)} H (λ a _, deriv_family f a) l.1], refine eq_of_forall_ge_iff (λ c, _), simp only [bsup_le_iff, IH] {contextual:=tt} } end theorem le_iff_deriv_family (H : ∀ i, is_normal (f i)) {a} : (∀ i, f i a ≤ a) ↔ ∃ o, deriv_family f o = a := ⟨λ ha, begin suffices : ∀ o (_ : a ≤ deriv_family f o), ∃ o, deriv_family f o = a, from this a ((deriv_family_is_normal _).self_le _), refine λ o, limit_rec_on o (λ h₁, ⟨0, le_antisymm _ h₁⟩) (λ o IH h₁, _) (λ o l IH h₁, _), { rw deriv_family_zero, exact nfp_family_le_fp (λ i, (H i).monotone) (ordinal.zero_le _) ha }, { cases le_or_lt a (deriv_family f o), {exact IH h}, refine ⟨succ o, le_antisymm _ h₁⟩, rw deriv_family_succ, exact nfp_family_le_fp (λ i, (H i).monotone) (succ_le_of_lt h) ha }, { cases eq_or_lt_of_le h₁, {exact ⟨_, h.symm⟩}, rw [deriv_family_limit _ l, ← not_le, bsup_le_iff, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩ i, e ▸ le_of_eq (deriv_family_fp (H i) _)⟩ theorem fp_iff_deriv_family (H : ∀ i, is_normal (f i)) {a} : (∀ i, f i a = a) ↔ ∃ o, deriv_family f o = a := iff.trans ⟨λ h i, le_of_eq (h i), λ h i, (H i).le_iff_eq.1 (h i)⟩ (le_iff_deriv_family H) theorem deriv_family_eq_enum_ord (H : ∀ i, is_normal (f i)) : deriv_family f = enum_ord (⋂ i, function.fixed_points (f i)) := begin rw ←eq_enum_ord _ (fp_family_unbounded H), use (deriv_family_is_normal f).strict_mono, rw set.range_eq_iff, refine ⟨_, λ a ha, _⟩, { rintros a S ⟨i, hi⟩, rw ←hi, exact deriv_family_fp (H i) a }, rw set.mem_Inter at ha, rwa ←fp_iff_deriv_family H end end /-! ### Fixed points of ordinal-indexed families of ordinals -/ section variables {o : ordinal.{u}} {f : Π b < o, ordinal.{max u v} → ordinal.{max u v}} /-- The next common fixed point, at least `a`, for a family of normal functions indexed by ordinals. -/ def nfp_bfamily (o : ordinal) (f : Π b < o, ordinal → ordinal) : ordinal → ordinal := nfp_family (family_of_bfamily o f) theorem nfp_bfamily_eq_nfp_family {o : ordinal} (f : Π b < o, ordinal → ordinal) : nfp_bfamily o f = nfp_family (family_of_bfamily o f) := rfl theorem foldr_le_nfp_bfamily {o : ordinal} (f : Π b < o, ordinal → ordinal) (a l) : list.foldr (family_of_bfamily o f) a l ≤ nfp_bfamily o f a := le_sup _ _ theorem le_nfp_bfamily {o : ordinal} (f : Π b < o, ordinal → ordinal) (a) : a ≤ nfp_bfamily o f a := le_sup _ [] theorem lt_nfp_bfamily {a b} : a < nfp_bfamily o f b ↔ ∃ l, a < list.foldr (family_of_bfamily o f) b l := lt_sup theorem nfp_bfamily_le_iff {o : ordinal} {f : Π b < o, ordinal → ordinal} {a b} : nfp_bfamily o f a ≤ b ↔ ∀ l, list.foldr (family_of_bfamily o f) a l ≤ b := sup_le_iff theorem nfp_bfamily_le {o : ordinal} {f : Π b < o, ordinal → ordinal} {a b} : (∀ l, list.foldr (family_of_bfamily o f) a l ≤ b) → nfp_bfamily o f a ≤ b := sup_le theorem nfp_bfamily_monotone (hf : ∀ i hi, monotone (f i hi)) : monotone (nfp_bfamily o f) := nfp_family_monotone (λ i, hf _ _) theorem apply_lt_nfp_bfamily (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∀ i hi, f i hi b < nfp_bfamily o f a) ↔ b < nfp_bfamily o f a := begin unfold nfp_bfamily, rw ←@apply_lt_nfp_family_iff _ (family_of_bfamily o f) (out_nonempty_iff_ne_zero.2 ho) (λ i, H _ _), refine ⟨λ h i, h _ (typein_lt_self i), λ h i hio, _⟩, rw ←family_of_bfamily_enum o f, apply h end theorem nfp_bfamily_le_apply (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∃ i hi, nfp_bfamily o f a ≤ f i hi b) ↔ nfp_bfamily o f a ≤ b := by { rw ←not_iff_not, push_neg, convert apply_lt_nfp_bfamily ho H, simp only [not_le] } theorem nfp_bfamily_le_fp (H : ∀ i hi, monotone (f i hi)) {a b} (ab : a ≤ b) (h : ∀ i hi, f i hi b ≤ b) : nfp_bfamily o f a ≤ b := nfp_family_le_fp (λ _, H _ _) ab (λ i, h _ _) theorem nfp_bfamily_fp {i hi} (H : is_normal (f i hi)) (a) : f i hi (nfp_bfamily o f a) = nfp_bfamily o f a := by { rw ←family_of_bfamily_enum o f, apply nfp_family_fp, rw family_of_bfamily_enum, exact H } theorem apply_le_nfp_bfamily (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∀ i hi, f i hi b ≤ nfp_bfamily o f a) ↔ b ≤ nfp_bfamily o f a := begin refine ⟨λ h, _, λ h i hi, _⟩, { have ho' : 0 < o := ordinal.pos_iff_ne_zero.2 ho, exact ((H 0 ho').self_le b).trans (h 0 ho') }, rw ←nfp_bfamily_fp (H i hi), exact (H i hi).monotone h end theorem nfp_bfamily_eq_self {a} (h : ∀ i hi, f i hi a = a) : nfp_bfamily o f a = a := nfp_family_eq_self (λ _, h _ _) /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem fp_bfamily_unbounded (H : ∀ i hi, is_normal (f i hi)) : (⋂ i hi, function.fixed_points (f i hi)).unbounded (<) := λ a, ⟨_, by { rw set.mem_Inter₂, exact λ i hi, nfp_bfamily_fp (H i hi) _ }, (le_nfp_bfamily f a).not_lt⟩ /-- The derivative of a family of normal functions is the sequence of their common fixed points. -/ def deriv_bfamily (o : ordinal) (f : Π b < o, ordinal → ordinal) : ordinal → ordinal := deriv_family (family_of_bfamily o f) theorem deriv_bfamily_eq_deriv_family {o : ordinal} (f : Π b < o, ordinal → ordinal) : deriv_bfamily o f = deriv_family (family_of_bfamily o f) := rfl theorem deriv_bfamily_is_normal {o : ordinal} (f : Π b < o, ordinal → ordinal) : is_normal (deriv_bfamily o f) := deriv_family_is_normal _ theorem deriv_bfamily_fp {i hi} (H : is_normal (f i hi)) (a : ordinal) : f i hi (deriv_bfamily o f a) = deriv_bfamily o f a := by { rw ←family_of_bfamily_enum o f, apply deriv_family_fp, rw family_of_bfamily_enum, exact H } theorem le_iff_deriv_bfamily (H : ∀ i hi, is_normal (f i hi)) {a} : (∀ i hi, f i hi a ≤ a) ↔ ∃ b, deriv_bfamily o f b = a := begin unfold deriv_bfamily, rw ←le_iff_deriv_family, { refine ⟨λ h i, h _ _, λ h i hi, _⟩, rw ←family_of_bfamily_enum o f, apply h }, exact λ _, H _ _ end theorem fp_iff_deriv_bfamily (H : ∀ i hi, is_normal (f i hi)) {a} : (∀ i hi, f i hi a = a) ↔ ∃ b, deriv_bfamily o f b = a := begin rw ←le_iff_deriv_bfamily H, refine ⟨λ h i hi, le_of_eq (h i hi), λ h i hi, _⟩, rw ←(H i hi).le_iff_eq, exact h i hi end theorem deriv_bfamily_eq_enum_ord (H : ∀ i hi, is_normal (f i hi)) : deriv_bfamily o f = enum_ord (⋂ i hi, function.fixed_points (f i hi)) := begin rw ←eq_enum_ord _ (fp_bfamily_unbounded H), use (deriv_bfamily_is_normal f).strict_mono, rw set.range_eq_iff, refine ⟨λ a, set.mem_Inter₂.2 (λ i hi, deriv_bfamily_fp (H i hi) a), λ a ha, _⟩, rw set.mem_Inter₂ at ha, rwa ←fp_iff_deriv_bfamily H end end /-! ### Fixed points of a single function -/ section variable {f : ordinal.{u} → ordinal.{u}} /-- The next fixed point function, the least fixed point of the normal function `f`, at least `a`. -/ def nfp (f : ordinal → ordinal) : ordinal → ordinal := nfp_family (λ _ : unit, f) theorem nfp_eq_nfp_family (f : ordinal → ordinal) : nfp f = nfp_family (λ _ : unit, f) := rfl @[simp] theorem sup_iterate_eq_nfp (f : ordinal.{u} → ordinal.{u}) : (λ a, sup (λ n : ℕ, f^[n] a)) = nfp f := begin refine funext (λ a, le_antisymm _ (sup_le (λ l, _))), { rw sup_le_iff, intro n, rw [←list.length_repeat unit.star n, ←list.foldr_const f a], apply le_sup }, { rw list.foldr_const f a l, exact le_sup _ _ }, end theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := by { rw ←sup_iterate_eq_nfp, exact le_sup _ n } theorem le_nfp (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem lt_nfp {a b} : a < nfp f b ↔ ∃ n, a < (f^[n]) b := by { rw ←sup_iterate_eq_nfp, exact lt_sup } theorem nfp_le_iff {a b} : nfp f a ≤ b ↔ ∀ n, (f^[n]) a ≤ b := by { rw ←sup_iterate_eq_nfp, exact sup_le_iff } theorem nfp_le {a b} : (∀ n, (f^[n]) a ≤ b) → nfp f a ≤ b := nfp_le_iff.2 @[simp] theorem nfp_id : nfp id = id := funext (λ a, begin simp_rw [←sup_iterate_eq_nfp, iterate_id], exact sup_const a end) theorem nfp_monotone (hf : monotone f) : monotone (nfp f) := nfp_family_monotone (λ i, hf) theorem is_normal.apply_lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := begin unfold nfp, rw ←@apply_lt_nfp_family_iff unit (λ _, f) _ (λ _, H) a b, exact ⟨λ h _, h, λ h, h unit.star⟩ end theorem is_normal.nfp_le_apply {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.apply_lt_nfp theorem nfp_le_fp {f} (H : monotone f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := nfp_family_le_fp (λ _, H) ab (λ _, h) theorem is_normal.nfp_fp {f} (H : is_normal f) : ∀ a, f (nfp f a) = nfp f a := @nfp_family_fp unit (λ _, f) unit.star H theorem is_normal.apply_le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.self_le _), λ h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a := nfp_family_eq_self (λ _, h) /-- The fixed point lemma for normal functions: any normal function has an unbounded set of fixed points. -/ theorem fp_unbounded (H : is_normal f) : (function.fixed_points f).unbounded (<) := by { convert fp_family_unbounded (λ _ : unit, H), exact (set.Inter_const _).symm } /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) : ordinal → ordinal := deriv_family (λ _ : unit, f) theorem deriv_eq_deriv_family (f : ordinal → ordinal) : deriv f = deriv_family (λ _ : unit, f) := rfl @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := deriv_family_zero _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := deriv_family_succ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u 0} o (λ a _, deriv f a) := deriv_family_limit _ theorem deriv_is_normal (f) : is_normal (deriv f) := deriv_family_is_normal _ theorem deriv_id_of_nfp_id {f : ordinal → ordinal} (h : nfp f = id) : deriv f = id := ((deriv_is_normal _).eq_iff_zero_and_succ is_normal.refl).2 (by simp [h]) theorem is_normal.deriv_fp {f} (H : is_normal f) : ∀ o, f (deriv f o) = deriv f o := @deriv_family_fp unit (λ _, f) unit.star H theorem is_normal.le_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, deriv f o = a := begin unfold deriv, rw ←le_iff_deriv_family (λ _ : unit, H), exact ⟨λ h _, h, λ h, h unit.star⟩ end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a = a ↔ ∃ o, deriv f o = a := by rw [←H.le_iff_eq, H.le_iff_deriv] theorem deriv_eq_enum_ord (H : is_normal f) : deriv f = enum_ord (function.fixed_points f) := by { convert deriv_family_eq_enum_ord (λ _ : unit, H), exact (set.Inter_const _).symm } theorem deriv_eq_id_of_nfp_eq_id {f : ordinal → ordinal} (h : nfp f = id) : deriv f = id := (is_normal.eq_iff_zero_and_succ (deriv_is_normal _) is_normal.refl).2 (by simp [h]) end /-! ### Fixed points of addition -/ @[simp] theorem nfp_add_zero (a) : nfp ((+) a) 0 = a * omega := begin simp_rw [←sup_iterate_eq_nfp, ←sup_mul_nat], congr, funext, induction n with n hn, { rw [nat.cast_zero, mul_zero, iterate_zero_apply] }, { nth_rewrite 1 nat.succ_eq_one_add, rw [nat.cast_add, nat.cast_one, mul_one_add, iterate_succ_apply', hn] } end theorem nfp_add_eq_mul_omega {a b} (hba : b ≤ a * omega) : nfp ((+) a) b = a * omega := begin apply le_antisymm (nfp_le_fp (add_is_normal a).monotone hba _), { rw ←nfp_add_zero, exact nfp_monotone (add_is_normal a).monotone (ordinal.zero_le b) }, { rw [←mul_one_add, one_add_omega] } end theorem add_eq_right_iff_mul_omega_le {a b : ordinal} : a + b = b ↔ a * omega ≤ b := begin refine ⟨λ h, _, λ h, _⟩, { rw [←nfp_add_zero a, ←deriv_zero], cases (add_is_normal a).fp_iff_deriv.1 h with c hc, rw ←hc, exact (deriv_is_normal _).monotone (ordinal.zero_le _) }, { have := ordinal.add_sub_cancel_of_le h, nth_rewrite 0 ←this, rwa [←add_assoc, ←mul_one_add, one_add_omega] } end theorem add_le_right_iff_mul_omega_le {a b : ordinal} : a + b ≤ b ↔ a * omega ≤ b := by { rw ←add_eq_right_iff_mul_omega_le, exact (add_is_normal a).le_iff_eq } theorem deriv_add_eq_mul_omega_add (a b : ordinal.{u}) : deriv ((+) a) b = a * omega + b := begin revert b, rw [←funext_iff, is_normal.eq_iff_zero_and_succ (deriv_is_normal _) (add_is_normal _)], refine ⟨_, λ a h, _⟩, { rw [deriv_zero, add_zero], exact nfp_add_zero a }, { rw [deriv_succ, h, add_succ], exact nfp_eq_self (add_eq_right_iff_mul_omega_le.2 ((le_add_right _ _).trans (le_succ _))) } end /-! ### Fixed points of multiplication -/ local infixr ^ := @pow ordinal ordinal ordinal.has_pow @[simp] theorem nfp_mul_one {a : ordinal} (ha : 0 < a) : nfp ((*) a) 1 = a ^ omega := begin rw [←sup_iterate_eq_nfp, ←sup_opow_nat], { dsimp, congr, funext, induction n with n hn, { rw [nat.cast_zero, opow_zero, iterate_zero_apply] }, nth_rewrite 1 nat.succ_eq_one_add, rw [nat.cast_add, nat.cast_one, opow_add, opow_one, iterate_succ_apply', hn] }, { exact ha } end @[simp] theorem nfp_mul_zero (a : ordinal) : nfp ((*) a) 0 = 0 := begin rw [←ordinal.le_zero, nfp_le_iff], intro n, induction n with n hn, { refl }, rwa [iterate_succ_apply, mul_zero] end @[simp] theorem nfp_zero_mul : nfp ((*) 0) = id := begin rw ←sup_iterate_eq_nfp, refine funext (λ a, (sup_le (λ n, _)).antisymm (le_sup (λ n, ((*) 0)^[n] a) 0)), induction n with n hn, { refl }, rw function.iterate_succ', change 0 * _ ≤ a, rw zero_mul, exact ordinal.zero_le a end @[simp] theorem deriv_mul_zero : deriv ((*) 0) = id := deriv_eq_id_of_nfp_eq_id nfp_zero_mul theorem nfp_mul_eq_opow_omega {a b : ordinal} (hb : 0 < b) (hba : b ≤ a ^ omega) : nfp ((*) a) b = a ^ omega.{u} := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_opow omega_ne_zero] at *, rw [ordinal.le_zero.1 hba, nfp_zero_mul], refl }, apply le_antisymm, { apply nfp_le_fp (mul_is_normal ha).monotone hba, rw [←opow_one_add, one_add_omega] }, rw ←nfp_mul_one ha, exact nfp_monotone (mul_is_normal ha).monotone (one_le_iff_pos.2 hb) end theorem eq_zero_or_opow_omega_le_of_mul_eq_right {a b : ordinal} (hab : a * b = b) : b = 0 ∨ a ^ omega.{u} ≤ b := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_opow omega_ne_zero], exact or.inr (ordinal.zero_le b) }, rw or_iff_not_imp_left, intro hb, change b ≠ 0 at hb, rw ←nfp_mul_one ha, rw ←one_le_iff_ne_zero at hb, exact nfp_le_fp (mul_is_normal ha).monotone hb (le_of_eq hab) end theorem mul_eq_right_iff_opow_omega_dvd {a b : ordinal} : a * b = b ↔ a ^ omega ∣ b := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_mul, zero_opow omega_ne_zero, zero_dvd_iff], exact eq_comm }, refine ⟨λ hab, _, λ h, _⟩, { rw dvd_iff_mod_eq_zero, rw [←div_add_mod b (a ^ omega), mul_add, ←mul_assoc, ←opow_one_add, one_add_omega, add_left_cancel] at hab, cases eq_zero_or_opow_omega_le_of_mul_eq_right hab with hab hab, { exact hab }, refine (not_lt_of_le hab (mod_lt b (opow_ne_zero omega _))).elim, rwa ←ordinal.pos_iff_ne_zero }, cases h with c hc, rw [hc, ←mul_assoc, ←opow_one_add, one_add_omega] end theorem mul_le_right_iff_opow_omega_dvd {a b : ordinal} (ha : 0 < a) : a * b ≤ b ↔ a ^ omega ∣ b := by { rw ←mul_eq_right_iff_opow_omega_dvd, exact (mul_is_normal ha).le_iff_eq } theorem nfp_mul_opow_omega_add {a c : ordinal} (b) (ha : 0 < a) (hc : 0 < c) (hca : c ≤ a ^ omega) : nfp ((*) a) (a ^ omega * b + c) = a ^ omega.{u} * (succ b) := begin apply le_antisymm, { apply nfp_le_fp (mul_is_normal ha).monotone, { rw mul_succ, apply add_le_add_left hca }, { rw [←mul_assoc, ←opow_one_add, one_add_omega] } }, { cases mul_eq_right_iff_opow_omega_dvd.1 ((mul_is_normal ha).nfp_fp (a ^ omega * b + c)) with d hd, rw hd, apply mul_le_mul_left', have := le_nfp (has_mul.mul a) (a ^ omega * b + c), rw hd at this, have := (add_lt_add_left hc (a ^ omega * b)).trans_le this, rw [add_zero, mul_lt_mul_iff_left (opow_pos omega ha)] at this, rwa succ_le_iff } end theorem deriv_mul_eq_opow_omega_mul {a : ordinal.{u}} (ha : 0 < a) (b) : deriv ((*) a) b = a ^ omega * b := begin revert b, rw [←funext_iff, is_normal.eq_iff_zero_and_succ (deriv_is_normal _) (mul_is_normal (opow_pos omega ha))], refine ⟨_, λ c h, _⟩, { rw [deriv_zero, nfp_mul_zero, mul_zero] }, { rw [deriv_succ, h], exact nfp_mul_opow_omega_add c ha zero_lt_one (one_le_iff_pos.2 (opow_pos _ ha)) }, end end ordinal
5584767ee334dfa38fc504f3c4afc9d267b595a8
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Elab/Command.lean
98dab11bc9ad51e5c01dbf6fd3bc176334ba0c16
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,790
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.ResolveName import Lean.Meta.Reduce import Lean.Elab.Log import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.DeclModifiers namespace Lean.Elab.Command structure Scope where header : String opts : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] levelNames : List Name := [] varDecls : Array Syntax := #[] deriving Inhabited structure State where env : Environment messages : MessageLog := {} scopes : List Scope := [{ header := "" }] nextMacroScope : Nat := firstFrontendMacroScope + 1 maxRecDepth : Nat nextInstIdx : Nat := 1 -- for generating anonymous instance names ngen : NameGenerator := {} deriving Inhabited structure Context where fileName : String fileMap : FileMap currRecDepth : Nat := 0 cmdPos : String.Pos := 0 macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope ref : Syntax := Syntax.missing abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε abbrev CommandElabM := CommandElabCoreM Exception abbrev CommandElab := Syntax → CommandElabM Unit abbrev Linter := Syntax → CommandElabM Unit def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env messages := messages scopes := [{ header := "", opts := opts }] maxRecDepth := getMaxRecDepth opts } /- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the environment (which only contains `import`ed objects). -/ builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[] def addLinter (l : Linter) : IO Unit := do let ls ← lintersRef.get lintersRef.set (ls.push l) instance : MonadEnv CommandElabM where getEnv := do pure (← get).env modifyEnv f := modify fun s => { s with env := f s.env } instance : MonadOptions CommandElabM where getOptions := do pure (← get).scopes.head!.opts protected def getRef : CommandElabM Syntax := return (← read).ref instance : AddMessageContext CommandElabM where addMessageContext := addMessageContextPartial instance : MonadRef CommandElabM where getRef := Command.getRef withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : AddErrorMessageContext CommandElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack return (ref, msg) def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos) private def mkCoreContext (ctx : Context) (s : State) : Core.Context := let scope := s.scopes.head! { options := scope.opts currRecDepth := ctx.currRecDepth maxRecDepth := s.maxRecDepth ref := ctx.ref currNamespace := scope.currNamespace openDecls := scope.openDecls } def liftCoreM {α} (x : CoreM α) : CommandElabM α := do let s ← get let ctx ← read let Eα := Except Exception α let x : CoreM Eα := try let a ← x; pure $ Except.ok a catch ex => pure $ Except.error ex let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s)).run { env := s.env, ngen := s.ngen } let (ea, coreS) ← liftM x modify fun s => { s with env := coreS.env, ngen := coreS.ngen } match ea with | Except.ok a => pure a | Except.error e => throw e private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message := let ref := getBetterRef ref ctx.macroStack mkMessageAux ctx ref (toString err) MessageSeverity.error @[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x @[inline] def liftIO {α} (x : IO α) : CommandElabM α := do let ctx ← read IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x instance : MonadLiftT IO CommandElabM where monadLift := liftIO def getScope : CommandElabM Scope := do pure (← get).scopes.head! instance : MonadResolveName CommandElabM where getCurrNamespace := return (← getScope).currNamespace getOpenDecls := return (← getScope).openDecls instance : MonadLog CommandElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data } modify fun s => { s with messages := s.messages.add msg } def runLinters (stx : Syntax) : CommandElabM Unit := do let linters ← lintersRef.get unless linters.isEmpty do for linter in linters do let savedState ← get try linter stx catch ex => logException ex finally modify fun s => { savedState with messages := s.messages } protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule @[inline] protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation CommandElabM where getCurrMacroScope := Command.getCurrMacroScope getMainModule := Command.getMainModule withFreshMacroScope := Command.withFreshMacroScope unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) := mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" @[implementedBy mkCommandElabAttributeUnsafe] constant mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab) builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute private def elabCommandUsing (s : State) (stx : Syntax) : List CommandElab → CommandElabM Unit | [] => throwError! "unexpected syntax{indentD stx}" | (elabFn::elabFns) => catchInternalId unsupportedSyntaxExceptionId (elabFn stx) (fun _ => do set s; elabCommandUsing s stx elabFns) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α := withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x instance : MonadMacroAdapter CommandElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← get).nextMacroScope setNextMacroScope next := modify fun s => { s with nextMacroScope := next } instance : MonadRecDepth CommandElabM where withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x getRecDepth := return (← read).currRecDepth getMaxRecDepth := return (← get).maxRecDepth @[inline] def withLogging (x : CommandElabM Unit) : CommandElabM Unit := try x catch ex => match ex with | Exception.error _ _ => logException ex | Exception.internal id _ => if isAbortExceptionId id then pure () else let idName ← liftIO $ id.getName; logError m!"internal exception {idName}" builtin_initialize registerTraceClass `Elab.command partial def elabCommand (stx : Syntax) : CommandElabM Unit := withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do runLinters stx match stx with | Syntax.node k args => if k == nullKind then -- list of commands => elaborate in order -- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones args.forM elabCommand else do trace `Elab.command fun _ => stx; let s ← get let stxNew? ← catchInternalId unsupportedSyntaxExceptionId (do let newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx)) (fun ex => pure none) match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabCommand stxNew | _ => let table := (commandElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some elabFns => elabCommandUsing s stx elabFns | none => throwError! "elaboration function for '{k}' has not been implemented" | _ => throwError "unexpected command" /-- Adapt a syntax transformation to a regular, command-producing elaborator. -/ def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' $ elabCommand stx' private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls instance {α} : Inhabited (CommandElabM α) where default := throw arbitrary private def mkMetaContext : Meta.Context := { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true } } private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := let scope := s.scopes.head! { macroStack := ctx.macroStack fileName := ctx.fileName fileMap := ctx.fileMap currMacroScope := ctx.currMacroScope declName? := declName? } private def addTraceAsMessages (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog := traceState.traces.foldl (fun (log : MessageLog) traceElem => let ref := replaceRef traceElem.ref ctx.ref; let pos := ref.getPos.getD 0; log.add (mkMessageCore ctx.fileName ctx.fileMap traceElem.msg MessageSeverity.information pos)) log def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do let ctx ← read let s ← get let scope := s.scopes.head! -- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands. -- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog` let messages := s.messages let x : MetaM _ := (observing x).run (mkTermContext ctx s declName?) { messages := {}, levelNames := scope.levelNames } let x : CoreM _ := x.run mkMetaContext {} let x : EIO _ _ := x.run (mkCoreContext ctx s) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope } let (((ea, termS), _), coreS) ← liftEIO x modify fun s => { s with env := coreS.env messages := addTraceAsMessages ctx (messages ++ termS.messages) coreS.traceState nextMacroScope := coreS.nextMacroScope ngen := coreS.ngen } match ea with | Except.ok a => pure a | Except.error ex => throw ex @[inline] def runTermElabM {α} (declName? : Option Name) (elabFn : Array Expr → TermElabM α) : CommandElabM α := do let s ← get liftTermElabM declName? <| -- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command. -- So, we use `Term.resetMessageLog`. Term.withAutoBoundImplicitLocal <| Term.elabBinders (getVarDecls s) (catchAutoBoundImplicit := true) fun xs => do Term.resetMessageLog let xs ← Term.addAutoBoundImplicits xs Term.withAutoBoundImplicitLocal (flag := false) <| elabFn xs @[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref => EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ()) private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do liftCoreM x private def addScope (isNewNamespace : Bool) (header : String) (newNamespace : Name) : CommandElabM Unit := do modify fun s => { s with env := s.env.registerNamespace newNamespace, scopes := { s.scopes.head! with header := header, currNamespace := newNamespace } :: s.scopes } pushScope if isNewNamespace then activateScoped newNamespace private def addScopes (isNewNamespace : Bool) : Name → CommandElabM Unit | Name.anonymous => pure () | Name.str p header _ => do addScopes isNewNamespace p let currNamespace ← getCurrNamespace addScope isNewNamespace header (if isNewNamespace then Name.mkStr currNamespace header else currNamespace) | _ => throwError "invalid scope" private def addNamespace (header : Name) : CommandElabM Unit := addScopes (isNewNamespace := true) header @[builtinCommandElab «namespace»] def elabNamespace : CommandElab := fun stx => match stx with | `(namespace $n) => addNamespace n.getId | _ => throwUnsupportedSyntax @[builtinCommandElab «section»] def elabSection : CommandElab := fun stx => match stx with | `(section $header:ident) => addScopes (isNewNamespace := false) header.getId | `(section) => do let currNamespace ← getCurrNamespace; addScope (isNewNamespace := false) "" currNamespace | _ => throwUnsupportedSyntax def getScopes : CommandElabM (List Scope) := do pure (← get).scopes private def checkAnonymousScope : List Scope → Bool | { header := "", .. } :: _ => true | _ => false private def checkEndHeader : Name → List Scope → Bool | Name.anonymous, _ => true | Name.str p s _, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes | _, _ => false private def popScopes (numScopes : Nat) : CommandElabM Unit := for i in [0:numScopes] do popScope @[builtinCommandElab «end»] def elabEnd : CommandElab := fun stx => do let header? := (stx.getArg 1).getOptionalIdent?; let endSize := match header? with | none => 1 | some n => n.getNumParts let scopes ← getScopes if endSize < scopes.length then modify fun s => { s with scopes := s.scopes.drop endSize } popScopes endSize else -- we keep "root" scope let n := (← get).scopes.length - 1 modify fun s => { s with scopes := s.scopes.drop n } popScopes n throwError "invalid 'end', insufficient scopes" match header? with | none => unless checkAnonymousScope scopes do throwError "invalid 'end', name is missing" | some header => unless checkEndHeader header scopes do throwError "invalid 'end', name mismatch" @[inline] def withNamespace {α} (ns : Name) (elabFn : CommandElabM α) : CommandElabM α := do addNamespace ns let a ← elabFn modify fun s => { s with scopes := s.scopes.drop ns.getNumParts } pure a @[specialize] def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify fun s => { s with scopes := match s.scopes with | h::t => f h :: t | [] => unreachable! } def getLevelNames : CommandElabM (List Name) := return (← getScope).levelNames def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do let id := idStx.getId let levelNames ← getLevelNames if levelNames.elem id then throwAlreadyDeclaredUniverseLevel id else modifyScope fun scope => { scope with levelNames := id :: scope.levelNames } partial def elabChoiceAux (cmds : Array Syntax) (i : Nat) : CommandElabM Unit := if h : i < cmds.size then let cmd := cmds.get ⟨i, h⟩; catchInternalId unsupportedSyntaxExceptionId (elabCommand cmd) (fun ex => elabChoiceAux cmds (i+1)) else throwUnsupportedSyntax @[builtinCommandElab choice] def elbChoice : CommandElab := fun stx => elabChoiceAux stx.getArgs 0 @[builtinCommandElab «universe»] def elabUniverse : CommandElab := fun n => do addUnivLevel n[1] @[builtinCommandElab «universes»] def elabUniverses : CommandElab := fun n => do let idsStx := n[1] idsStx.forArgsM addUnivLevel @[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab := fun stx => do let env ← getEnv match env.addDecl Declaration.quotDecl with | Except.ok env => setEnv env | Except.error ex => do let opts ← getOptions throwError (ex.toMessageData opts) def logUnknownDecl (declName : Name) : CommandElabM Unit := logError m!"unknown declaration '{declName}'" @[builtinCommandElab «export»] def elabExport : CommandElab := fun stx => do -- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")") let id := stx[1].getId let ns ← resolveNamespace id let currNamespace ← getCurrNamespace if ns == currNamespace then throwError "invalid 'export', self export" let env ← getEnv let ids := stx[3].getArgs let aliases ← ids.foldlM (init := []) fun (aliases : List (Name × Name)) (idStx : Syntax) => do let id := idStx.getId let declName := ns ++ id if env.contains declName then pure $ (currNamespace ++ id, declName) :: aliases else withRef idStx $ logUnknownDecl declName pure aliases modify fun s => { s with env := aliases.foldl (init := s.env) fun env p => addAlias env p.1 p.2 } def addOpenDecl (d : OpenDecl) : CommandElabM Unit := modifyScope fun scope => { scope with openDecls := d :: scope.openDecls } def elabOpenSimple (n : SyntaxNode) : CommandElabM Unit := -- `open` id+ let nss := n.getArg 0 nss.forArgsM fun ns => do let ns ← resolveNamespace ns.getId addOpenDecl (OpenDecl.simple ns []) activateScoped ns -- `open` id `(` id+ `)` def elabOpenOnly (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0 let ns ← resolveNamespace ns let ids := n.getArg 2 ids.forArgsM fun idStx => do let id := idStx.getId let declName := ns ++ id let env ← getEnv if env.contains declName then addOpenDecl (OpenDecl.explicit id declName) else withRef idStx do logUnknownDecl declName -- `open` id `hiding` id+ def elabOpenHiding (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0 let ns ← resolveNamespace ns let idsStx := n.getArg 2 let env ← getEnv let ids ← idsStx.foldArgsM (fun idStx ids => do let id := idStx.getId let declName := ns ++ id if env.contains declName then pure (id::ids) else do withRef idStx do logUnknownDecl declName pure ids) [] addOpenDecl (OpenDecl.simple ns ids) -- `open` id `renaming` sepBy (id `->` id) `,` def elabOpenRenaming (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0 let ns ← resolveNamespace ns let rs := (n.getArg 2) rs.getSepArgs.forM fun stx => do let fromId := stx.getIdAt 0 let toId := stx.getIdAt 2 let declName := ns ++ fromId let env ← getEnv if env.contains declName then addOpenDecl (OpenDecl.explicit toId declName) else withRef stx do logUnknownDecl declName @[builtinCommandElab «open»] def elabOpen : CommandElab := fun n => do let body := (n.getArg 1).asNode let k := body.getKind; if k == ``Parser.Command.openSimple then elabOpenSimple body else if k == ``Parser.Command.openOnly then elabOpenOnly body else if k == ``Parser.Command.openHiding then elabOpenHiding body else elabOpenRenaming body @[builtinCommandElab «variable»] def elabVariable : CommandElab := fun n => do -- `variable` bracketedBinder let binder := n[1] -- Try to elaborate `binder` for sanity checking runTermElabM none fun _ => Term.withAutoBoundImplicitLocal <| Term.elabBinder binder (catchAutoBoundImplicit := true) fun _ => pure () modifyScope fun scope => { scope with varDecls := scope.varDecls.push binder } @[builtinCommandElab «variables»] def elabVariables : CommandElab := fun n => do -- `variables` bracketedBinder+ let binders := n[1].getArgs -- Try to elaborate `binders` for sanity checking runTermElabM none fun _ => Term.withAutoBoundImplicitLocal <| Term.elabBinders binders (catchAutoBoundImplicit := true) fun _ => pure () modifyScope fun scope => { scope with varDecls := scope.varDecls ++ binders } open Meta @[builtinCommandElab Lean.Parser.Command.check] def elabCheck : CommandElab | `(#check%$tk $term) => withoutModifyingEnv $ runTermElabM (some `_check) fun _ => do let e ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing let (e, _) ← Term.levelMVarToParam (← instantiateMVars e) let type ← inferType e unless e.isSyntheticSorry do logInfoAt tk m!"{e} : {type}" | _ => throwUnsupportedSyntax @[builtinCommandElab Lean.Parser.Command.reduce] def elabReduce : CommandElab | `(#reduce%$tk $term) => withoutModifyingEnv $ runTermElabM (some `_check) fun _ => do let e ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing let (e, _) ← Term.levelMVarToParam (← instantiateMVars e) -- TODO: add options or notation for setting the following parameters withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding false }) do let e ← withTransparency (mode := TransparencyMode.all) <| reduce e (skipProofs := false) (skipTypes := false) logInfoAt tk e | _ => throwUnsupportedSyntax def hasNoErrorMessages : CommandElabM Bool := do return !(← get).messages.hasErrors def failIfSucceeds (x : CommandElabM Unit) : CommandElabM Unit := do let resetMessages : CommandElabM MessageLog := do let s ← get let messages := s.messages; modify fun s => { s with messages := {} }; pure messages let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do modify fun s => { s with messages := prevMessages ++ s.messages.errorsToWarnings } let prevMessages ← resetMessages let succeeded ← try x hasNoErrorMessages catch | ex@(Exception.error _ _) => do logException ex; pure false | Exception.internal id _ => do logError "internal"; pure false -- TODO: improve `logError "internal"` finally restoreMessages prevMessages if succeeded then throwError "unexpected success" @[builtinCommandElab «check_failure»] def elabCheckFailure : CommandElab := fun stx => failIfSucceeds <| elabCheck stx unsafe def elabEvalUnsafe : CommandElab | `(#eval%$tk $term) => do let n := `_eval let ctx ← read let addAndCompile (value : Expr) : TermElabM Unit := do let type ← inferType value let decl := Declaration.defnDecl { name := n, lparams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } Term.ensureNoUnassignedMVars decl addAndCompile decl let elabMetaEval : CommandElabM Unit := runTermElabM (some n) fun _ => do let e ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing let e ← withLocalDeclD `env (mkConst ``Lean.Environment) fun env => withLocalDeclD `opts (mkConst ``Lean.Options) fun opts => do let e ← mkAppM ``Lean.runMetaEval #[env, opts, e]; mkLambdaFVars #[env, opts] e let env ← getEnv let opts ← getOptions let act ← try addAndCompile e; evalConst (Environment → Options → IO (String × Except IO.Error Environment)) n finally setEnv env let (out, res) ← act env opts -- we execute `act` using the environment logInfoAt tk out match res with | Except.error e => throwError e.toString | Except.ok env => do setEnv env; pure () let elabEval : CommandElabM Unit := runTermElabM (some n) fun _ => do -- fall back to non-meta eval if MetaEval hasn't been defined yet -- modify e to `runEval e` let e ← Term.elabTerm term none let e := mkSimpleThunk e Term.synthesizeSyntheticMVarsNoPostponing let e ← mkAppM ``Lean.runEval #[e] let env ← getEnv let act ← try addAndCompile e; evalConst (IO (String × Except IO.Error Unit)) n finally setEnv env let (out, res) ← liftM (m := IO) act logInfoAt tk out match res with | Except.error e => throwError e.toString | Except.ok _ => pure () if (← getEnv).contains ``Lean.MetaEval then do elabMetaEval else elabEval | _ => throwUnsupportedSyntax @[builtinCommandElab «eval», implementedBy elabEvalUnsafe] constant elabEval : CommandElab @[builtinCommandElab «synth»] def elabSynth : CommandElab := fun stx => do let term := stx[1] withoutModifyingEnv $ runTermElabM `_synth_cmd fun _ => do let inst ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing let inst ← instantiateMVars inst let val ← synthInstance inst logInfo val pure () def setOption (optionName : Name) (val : DataValue) : CommandElabM Unit := do let decl ← liftIO <| getOptionDecl optionName unless decl.defValue.sameCtor val do throwError "type mismatch at set_option" modifyScope fun scope => { scope with opts := scope.opts.insert optionName val } match optionName, val with | `maxRecDepth, DataValue.ofNat max => modify fun s => { s with maxRecDepth := max } | _, _ => pure () @[builtinCommandElab «set_option»] def elabSetOption : CommandElab := fun stx => do let optionName := stx[1].getId.eraseMacroScopes let val := stx[2] match val.isStrLit? with | some str => setOption optionName (DataValue.ofString str) | none => match val.isNatLit? with | some num => setOption optionName (DataValue.ofNat num) | none => match val with | Syntax.atom _ "true" => setOption optionName (DataValue.ofBool true) | Syntax.atom _ "false" => setOption optionName (DataValue.ofBool false) | _ => logErrorAt val m!"unexpected set_option value {val}" @[builtinMacro Lean.Parser.Command.«in»] def expandInCmd : Macro := fun stx => do let cmd₁ := stx[0] let cmd₂ := stx[2] `(section $cmd₁:command $cmd₂:command end) def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do let currNamespace ← getCurrNamespace let currLevelNames ← getLevelNames Lean.Elab.expandDeclId currNamespace currLevelNames declId modifiers end Elab.Command export Elab.Command (Linter addLinter) end Lean
4076ec8652c67f8073a44a165b25b4a064e2b9d0
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/list/nat_antidiagonal.lean
bbabc67b33744a3bb05a30765fc7e39f69798bf3
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
1,483
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.list.range open list function nat namespace list namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := rfl /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@left_inverse.injective ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) end nat end list
83ab1d0b292b0ee900fb93ac5aa43a154ef00dca
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Assumption.lean
83f275a3007202504d9910cfa34518ed44b5e221
[ "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,420
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Util namespace Lean.Meta /-- Return a local declaration whose type is definitionally equal to `type`. -/ def findLocalDeclWithType? (type : Expr) : MetaM (Option FVarId) := do (← getLCtx).findDeclRevM? fun localDecl => do if localDecl.isImplementationDetail then return none else if (← isDefEq type localDecl.type) then return some localDecl.fvarId else return none /-- Return `true` if managed to close goal `mvarId` using an assumption. -/ def _root_.Lean.MVarId.assumptionCore (mvarId : MVarId) : MetaM Bool := mvarId.withContext do mvarId.checkNotAssigned `assumption match (← findLocalDeclWithType? (← mvarId.getType)) with | none => return false | some fvarId => mvarId.assign (mkFVar fvarId); return true @[deprecated MVarId.assumptionCore] def assumptionCore (mvarId : MVarId) : MetaM Bool := mvarId.assumptionCore /-- Close goal `mvarId` using an assumption. Throw error message if failed. -/ def _root_.Lean.MVarId.assumption (mvarId : MVarId) : MetaM Unit := unless (← mvarId.assumptionCore) do throwTacticEx `assumption mvarId "" @[deprecated MVarId.assumption] def assumption (mvarId : MVarId) : MetaM Unit := mvarId.assumption end Lean.Meta
d477f310abc6a43eaa5f3a452ad001440b2c537f
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/Group/zero.lean
a0576616fdc1086de5d0e8fc05d9ee8465304a51
[ "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
791
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.basic import category_theory.limits.shapes.zero /-! # The category of commutative additive groups has a zero object. It also has zero morphisms. For definitional reasons, we infer this from preadditivity rather than from the existence of a zero object. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup instance : has_zero_object AddCommGroup := { zero := 0, unique_to := λ X, ⟨⟨0⟩, λ f, begin ext, cases x, erw add_monoid_hom.map_zero, refl end⟩, unique_from := λ X, ⟨⟨0⟩, λ f, begin ext, apply subsingleton.elim, end⟩, } end AddCommGroup
624b474e6ed8df8db44859a9dfbcb7a573e326e5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/control/random.lean
0b6581b91df800765e5436f10b660b55799675bd
[ "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
9,692
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.uliftable import data.bitvec.basic import data.stream.defs import tactic.norm_num /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) := (random [] : Π (g : Type) [random_gen g], rand_g g α) /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 /-- Run `cmd` using the provided seed. -/ def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α := return $ (cmd.run ⟨mk_std_gen seed⟩).1 section random variables [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [ne_zero n] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← le_tsub_iff_right hxy; apply le_of_succ_le_succ z.is_lt⟩ } /-- This `bounded_random` interval generates integers between `x` and `y` by first generating a natural number between `0` and `y - x` and shifting the result appropriately. -/ instance int_bounded_random : bounded_random ℤ := { random_r := λ g inst x y hxy, do ⟨z,h₀,h₁⟩ ← @bounded_random.random_r ℕ _ _ g inst 0 (int.nat_abs $ y - x) dec_trivial, pure ⟨z + x, int.le_add_of_nonneg_left (int.coe_nat_nonneg _), int.add_le_of_le_sub_right $ le_trans (int.coe_nat_le_coe_nat_of_le h₁) (le_of_eq $ int.of_nat_nat_abs_eq_of_nonneg (int.sub_nonneg_of_le hxy)) ⟩ } instance fin_random (n : ℕ) [ne_zero n] : random (fin n) := { random := λ g inst, @fin.random g inst _ _ } instance fin_bounded_random (n : ℕ) : bounded_random (fin n) := { random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (nat.not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _) } instance : bounded_random bool := { random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n } instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) := { random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
08f8d62071d4d60842cceb5fa1844980bdb98270
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/real/pi/leibniz.lean
4a803ae34bf6f8b51844560c8c143de301e96043
[ "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
7,642
lean
/- Copyright (c) 2020 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import analysis.special_functions.trigonometric.arctan_deriv /-! ### Leibniz's Series for Pi -/ namespace real open filter set open_locale classical big_operators topological_space real local notation `|`x`|` := abs x /-- This theorem establishes **Leibniz's series for `π`**: The alternating sum of the reciprocals of the odd numbers is `π/4`. Note that this is a conditionally rather than absolutely convergent series. The main tool that this proof uses is the Mean Value Theorem (specifically avoiding the Fundamental Theorem of Calculus). Intuitively, the theorem holds because Leibniz's series is the Taylor series of `arctan x` centered about `0` and evaluated at the value `x = 1`. Therefore, much of this proof consists of reasoning about a function `f := arctan x - ∑ i in finset.range k, (-(1:ℝ))^i * x^(2*i+1) / (2*i+1)`, the difference between `arctan` and the `k`-th partial sum of its Taylor series. Some ingenuity is required due to the fact that the Taylor series is not absolutely convergent at `x = 1`. This proof requires a bound on `f 1`, the key idea being that `f 1` can be split as the sum of `f 1 - f u` and `f u`, where `u` is a sequence of values in [0,1], carefully chosen such that each of these two terms can be controlled (in different ways). We begin the proof by (1) introducing that sequence `u` and then proving that another sequence constructed from `u` tends to `0` at `+∞`. After (2) converting the limit in our goal to an inequality, we (3) introduce the auxiliary function `f` defined above. Next, we (4) compute the derivative of `f`, denoted by `f'`, first generally and then on each of two subintervals of [0,1]. We then (5) prove a bound for `f'`, again both generally as well as on each of the two subintervals. Finally, we (6) apply the Mean Value Theorem twice, obtaining bounds on `f 1 - f u` and `f u - f 0` from the bounds on `f'` (note that `f 0 = 0`). -/ theorem tendsto_sum_pi_div_four : tendsto (λ k, ∑ i in finset.range k, ((-(1:ℝ))^i / (2*i+1))) at_top (𝓝 (π/4)) := begin rw [tendsto_iff_norm_tendsto_zero, ← tendsto_zero_iff_norm_tendsto_zero], -- (1) We introduce a useful sequence `u` of values in [0,1], then prove that another sequence -- constructed from `u` tends to `0` at `+∞` let u := λ k : ℕ, (k:nnreal) ^ (-1 / (2 * (k:ℝ) + 1)), have H : tendsto (λ k : ℕ, (1:ℝ) - (u k) + (u k) ^ (2 * (k:ℝ) + 1)) at_top (𝓝 0), { convert (((tendsto_rpow_div_mul_add (-1) 2 1 two_ne_zero.symm).neg.const_add 1).add tendsto_inv_at_top_zero).comp tendsto_coe_nat_at_top_at_top, { ext k, simp only [nnreal.coe_nat_cast, function.comp_app, nnreal.coe_rpow], rw [← rpow_mul (nat.cast_nonneg k) ((-1)/(2*(k:ℝ)+1)) (2*(k:ℝ)+1), @div_mul_cancel _ _ (2*(k:ℝ)+1) _ (by { norm_cast, simp only [nat.succ_ne_zero, not_false_iff] }), rpow_neg_one k, sub_eq_add_neg] }, { simp only [add_zero, add_right_neg] } }, -- (2) We convert the limit in our goal to an inequality refine squeeze_zero_norm _ H, intro k, -- Since `k` is now fixed, we henceforth denote `u k` as `U` let U := u k, -- (3) We introduce an auxiliary function `f` let b := λ (i:ℕ) x, (-(1:ℝ))^i * x^(2*i+1) / (2*i+1), let f := λ x, arctan x - (∑ i in finset.range k, b i x), suffices f_bound : |f 1 - f 0| ≤ (1:ℝ) - U + U ^ (2 * (k:ℝ) + 1), { rw ← norm_neg, convert f_bound, simp only [f], simp [b] }, -- We show that `U` is indeed in [0,1] have hU1 : (U:ℝ) ≤ 1, { by_cases hk : k = 0, { simp [u, U, hk] }, { exact rpow_le_one_of_one_le_of_nonpos (by { norm_cast, exact nat.succ_le_iff.mpr (nat.pos_of_ne_zero hk) }) (le_of_lt (@div_neg_of_neg_of_pos _ _ (-(1:ℝ)) (2*k+1) (neg_neg_iff_pos.mpr zero_lt_one) (by { norm_cast, exact nat.succ_pos' }))) } }, have hU2 := nnreal.coe_nonneg U, -- (4) We compute the derivative of `f`, denoted by `f'` let f' := λ x : ℝ, (-x^2) ^ k / (1 + x^2), have has_deriv_at_f : ∀ x, has_deriv_at f (f' x) x, { intro x, have has_deriv_at_b : ∀ i ∈ finset.range k, (has_deriv_at (b i) ((-x^2)^i) x), { intros i hi, convert has_deriv_at.const_mul ((-1:ℝ)^i / (2*i+1)) (@has_deriv_at.pow _ _ _ _ _ (2*i+1) (has_deriv_at_id x)), { ext y, simp only [b, id.def], ring }, { simp only [nat.add_succ_sub_one, add_zero, mul_one, id.def, nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul], rw [← mul_assoc, @div_mul_cancel _ _ (2*(i:ℝ)+1) _ (by { norm_cast, linarith }), pow_mul x 2 i, ← mul_pow (-1) (x^2) i], ring_nf } }, convert (has_deriv_at_arctan x).sub (has_deriv_at.sum has_deriv_at_b), have g_sum := @geom_sum_eq _ _ (-x^2) ((neg_nonpos.mpr (sq_nonneg x)).trans_lt zero_lt_one).ne k, simp only [f'] at g_sum ⊢, rw [g_sum, ← neg_add' (x^2) 1, add_comm (x^2) 1, sub_eq_add_neg, neg_div', neg_div_neg_eq], ring }, have hderiv1 : ∀ x ∈ Icc (U:ℝ) 1, has_deriv_within_at f (f' x) (Icc (U:ℝ) 1) x := λ x hx, (has_deriv_at_f x).has_deriv_within_at, have hderiv2 : ∀ x ∈ Icc 0 (U:ℝ), has_deriv_within_at f (f' x) (Icc 0 (U:ℝ)) x := λ x hx, (has_deriv_at_f x).has_deriv_within_at, -- (5) We prove a general bound for `f'` and then more precise bounds on each of two subintervals have f'_bound : ∀ x ∈ Icc (-1:ℝ) 1, |f' x| ≤ |x|^(2*k), { intros x hx, rw [abs_div, is_absolute_value.abv_pow abs (-x^2) k, abs_neg, is_absolute_value.abv_pow abs x 2, ← pow_mul], refine div_le_of_nonneg_of_le_mul (abs_nonneg _) (pow_nonneg (abs_nonneg _) _) _, refine le_mul_of_one_le_right (pow_nonneg (abs_nonneg _) _) _, rw abs_of_nonneg ((add_nonneg zero_le_one (sq_nonneg x)) : (0 : ℝ) ≤ _), exact (le_add_of_nonneg_right (sq_nonneg x) : (1 : ℝ) ≤ _) }, have hbound1 : ∀ x ∈ Ico (U:ℝ) 1, |f' x| ≤ 1, { rintros x ⟨hx_left, hx_right⟩, have hincr := pow_le_pow_of_le_left (le_trans hU2 hx_left) (le_of_lt hx_right) (2*k), rw [one_pow (2*k), ← abs_of_nonneg (le_trans hU2 hx_left)] at hincr, rw ← abs_of_nonneg (le_trans hU2 hx_left) at hx_right, linarith [f'_bound x (mem_Icc.mpr (abs_le.mp (le_of_lt hx_right)))] }, have hbound2 : ∀ x ∈ Ico 0 (U:ℝ), |f' x| ≤ U ^ (2*k), { rintros x ⟨hx_left, hx_right⟩, have hincr := pow_le_pow_of_le_left hx_left (le_of_lt hx_right) (2*k), rw ← abs_of_nonneg hx_left at hincr hx_right, rw ← abs_of_nonneg hU2 at hU1 hx_right, linarith [f'_bound x (mem_Icc.mpr (abs_le.mp (le_trans (le_of_lt hx_right) hU1)))] }, -- (6) We twice apply the Mean Value Theorem to obtain bounds on `f` from the bounds on `f'` have mvt1 := norm_image_sub_le_of_norm_deriv_le_segment' hderiv1 hbound1 _ (right_mem_Icc.mpr hU1), have mvt2 := norm_image_sub_le_of_norm_deriv_le_segment' hderiv2 hbound2 _ (right_mem_Icc.mpr hU2), -- The following algebra is enough to complete the proof calc |f 1 - f 0| = |(f 1 - f U) + (f U - f 0)| : by ring_nf ... ≤ 1 * (1-U) + U^(2*k) * (U - 0) : le_trans (abs_add (f 1 - f U) (f U - f 0)) (add_le_add mvt1 mvt2) ... = 1 - U + U^(2*k) * U : by ring ... = 1 - (u k) + (u k)^(2*(k:ℝ)+1) : by { rw [← pow_succ' (U:ℝ) (2*k)], norm_cast }, end end real