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
ac354bf3fe58fe1dcf4ba95240c6cfcdc4352894
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/cubic_discriminant.lean
edd52127e26637e29920f15f436674f2c2a45090
[ "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
13,825
lean
/- Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import data.polynomial.splits /-! # Cubics and discriminants This file defines cubic polynomials over a semiring and their discriminants over a splitting field. ## Main definitions * `cubic`: the structure representing a cubic polynomial. * `cubic.disc`: the discriminant of a cubic polynomial. ## Main statements * `cubic.disc_ne_zero_iff_roots_nodup`: the cubic discriminant is not equal to zero if and only if the cubic has no duplicate roots. ## References * https://en.wikipedia.org/wiki/Cubic_equation * https://en.wikipedia.org/wiki/Discriminant ## Tags cubic, discriminant, polynomial, root -/ noncomputable theory /-- The structure representing a cubic polynomial. -/ @[ext] structure cubic (R : Type*) := (a b c d : R) namespace cubic open cubic polynomial open_locale polynomial variables {R S F K : Type*} instance [inhabited R] : inhabited (cubic R) := ⟨⟨default, default, default, default⟩⟩ instance [has_zero R] : has_zero (cubic R) := ⟨⟨0, 0, 0, 0⟩⟩ section basic variables {P Q : cubic R} {a b c d a' b' c' d' : R} [semiring R] /-- Convert a cubic polynomial to a polynomial. -/ def to_poly (P : cubic R) : R[X] := C P.a * X ^ 3 + C P.b * X ^ 2 + C P.c * X + C P.d /-! ### Coefficients -/ section coeff private lemma coeffs : (βˆ€ n > 3, P.to_poly.coeff n = 0) ∧ P.to_poly.coeff 3 = P.a ∧ P.to_poly.coeff 2 = P.b ∧ P.to_poly.coeff 1 = P.c ∧ P.to_poly.coeff 0 = P.d := begin simp only [to_poly, coeff_add, coeff_C, coeff_C_mul_X, coeff_C_mul_X_pow], norm_num, intros n hn, repeat { rw [if_neg] }, any_goals { linarith only [hn] }, repeat { rw [zero_add] } end @[simp] lemma coeff_eq_zero {n : β„•} (hn : 3 < n) : P.to_poly.coeff n = 0 := coeffs.1 n hn @[simp] lemma coeff_eq_a : P.to_poly.coeff 3 = P.a := coeffs.2.1 @[simp] lemma coeff_eq_b : P.to_poly.coeff 2 = P.b := coeffs.2.2.1 @[simp] lemma coeff_eq_c : P.to_poly.coeff 1 = P.c := coeffs.2.2.2.1 @[simp] lemma coeff_eq_d : P.to_poly.coeff 0 = P.d := coeffs.2.2.2.2 lemma a_of_eq (h : P.to_poly = Q.to_poly) : P.a = Q.a := by rw [← coeff_eq_a, h, coeff_eq_a] lemma b_of_eq (h : P.to_poly = Q.to_poly) : P.b = Q.b := by rw [← coeff_eq_b, h, coeff_eq_b] lemma c_of_eq (h : P.to_poly = Q.to_poly) : P.c = Q.c := by rw [← coeff_eq_c, h, coeff_eq_c] lemma d_of_eq (h : P.to_poly = Q.to_poly) : P.d = Q.d := by rw [← coeff_eq_d, h, coeff_eq_d] lemma to_poly_injective (P Q : cubic R) : P.to_poly = Q.to_poly ↔ P = Q := ⟨λ h, ext P Q (a_of_eq h) (b_of_eq h) (c_of_eq h) (d_of_eq h), congr_arg to_poly⟩ lemma of_a_eq_zero (ha : P.a = 0) : P.to_poly = C P.b * X ^ 2 + C P.c * X + C P.d := by rw [to_poly, ha, C_0, zero_mul, zero_add] lemma of_a_eq_zero' : to_poly ⟨0, b, c, d⟩ = C b * X ^ 2 + C c * X + C d := of_a_eq_zero rfl lemma of_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) : P.to_poly = C P.c * X + C P.d := by rw [of_a_eq_zero ha, hb, C_0, zero_mul, zero_add] lemma of_b_eq_zero' : to_poly ⟨0, 0, c, d⟩ = C c * X + C d := of_b_eq_zero rfl rfl lemma of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.to_poly = C P.d := by rw [of_b_eq_zero ha hb, hc, C_0, zero_mul, zero_add] lemma of_c_eq_zero' : to_poly ⟨0, 0, 0, d⟩ = C d := of_c_eq_zero rfl rfl rfl lemma of_d_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 0) : P.to_poly = 0 := by rw [of_c_eq_zero ha hb hc, hd, C_0] lemma of_d_eq_zero' : (⟨0, 0, 0, 0⟩ : cubic R).to_poly = 0 := of_d_eq_zero rfl rfl rfl rfl lemma zero : (0 : cubic R).to_poly = 0 := of_d_eq_zero' lemma to_poly_eq_zero_iff (P : cubic R) : P.to_poly = 0 ↔ P = 0 := by rw [← zero, to_poly_injective] private lemma ne_zero (h0 : P.a β‰  0 ∨ P.b β‰  0 ∨ P.c β‰  0 ∨ P.d β‰  0) : P.to_poly β‰  0 := by { contrapose! h0, rw [(to_poly_eq_zero_iff P).mp h0], exact ⟨rfl, rfl, rfl, rfl⟩ } lemma ne_zero_of_a_ne_zero (ha : P.a β‰  0) : P.to_poly β‰  0 := (or_imp_distrib.mp ne_zero).1 ha lemma ne_zero_of_b_ne_zero (hb : P.b β‰  0) : P.to_poly β‰  0 := (or_imp_distrib.mp (or_imp_distrib.mp ne_zero).2).1 hb lemma ne_zero_of_c_ne_zero (hc : P.c β‰  0) : P.to_poly β‰  0 := (or_imp_distrib.mp (or_imp_distrib.mp (or_imp_distrib.mp ne_zero).2).2).1 hc lemma ne_zero_of_d_ne_zero (hd : P.d β‰  0) : P.to_poly β‰  0 := (or_imp_distrib.mp (or_imp_distrib.mp (or_imp_distrib.mp ne_zero).2).2).2 hd end coeff /-! ### Degrees -/ section degree /-- The equivalence between cubic polynomials and polynomials of degree at most three. -/ @[simps] def equiv : cubic R ≃ {p : R[X] // p.degree ≀ 3} := { to_fun := Ξ» P, ⟨P.to_poly, degree_cubic_le⟩, inv_fun := Ξ» f, ⟨coeff f 3, coeff f 2, coeff f 1, coeff f 0⟩, left_inv := Ξ» P, by ext; simp only [subtype.coe_mk, coeffs], right_inv := Ξ» f, begin ext (_ | _ | _ | _ | n); simp only [subtype.coe_mk, coeffs], have h3 : 3 < n + 4 := by linarith only, rw [coeff_eq_zero h3, (degree_le_iff_coeff_zero (f : R[X]) 3).mp f.2 _ $ with_bot.coe_lt_coe.mpr h3] end } @[simp] lemma degree_of_a_ne_zero (ha : P.a β‰  0) : P.to_poly.degree = 3 := degree_cubic ha @[simp] lemma degree_of_a_ne_zero' (ha : a β‰  0) : (to_poly ⟨a, b, c, d⟩).degree = 3 := degree_of_a_ne_zero ha lemma degree_of_a_eq_zero (ha : P.a = 0) : P.to_poly.degree ≀ 2 := by simpa only [of_a_eq_zero ha] using degree_quadratic_le lemma degree_of_a_eq_zero' : (to_poly ⟨0, b, c, d⟩).degree ≀ 2 := degree_of_a_eq_zero rfl @[simp] lemma degree_of_b_ne_zero (ha : P.a = 0) (hb : P.b β‰  0) : P.to_poly.degree = 2 := by rw [of_a_eq_zero ha, degree_quadratic hb] @[simp] lemma degree_of_b_ne_zero' (hb : b β‰  0) : (to_poly ⟨0, b, c, d⟩).degree = 2 := degree_of_b_ne_zero rfl hb lemma degree_of_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) : P.to_poly.degree ≀ 1 := by simpa only [of_b_eq_zero ha hb] using degree_linear_le lemma degree_of_b_eq_zero' : (to_poly ⟨0, 0, c, d⟩).degree ≀ 1 := degree_of_b_eq_zero rfl rfl @[simp] lemma degree_of_c_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c β‰  0) : P.to_poly.degree = 1 := by rw [of_b_eq_zero ha hb, degree_linear hc] @[simp] lemma degree_of_c_ne_zero' (hc : c β‰  0) : (to_poly ⟨0, 0, c, d⟩).degree = 1 := degree_of_c_ne_zero rfl rfl hc lemma degree_of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.to_poly.degree ≀ 0 := by simpa only [of_c_eq_zero ha hb hc] using degree_C_le lemma degree_of_c_eq_zero' : (to_poly ⟨0, 0, 0, d⟩).degree ≀ 0 := degree_of_c_eq_zero rfl rfl rfl @[simp] lemma degree_of_d_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d β‰  0) : P.to_poly.degree = 0 := by rw [of_c_eq_zero ha hb hc, degree_C hd] @[simp] lemma degree_of_d_ne_zero' (hd : d β‰  0) : (to_poly ⟨0, 0, 0, d⟩).degree = 0 := degree_of_d_ne_zero rfl rfl rfl hd @[simp] lemma degree_of_d_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 0) : P.to_poly.degree = βŠ₯ := by rw [of_d_eq_zero ha hb hc hd, degree_zero] @[simp] lemma degree_of_d_eq_zero' : (⟨0, 0, 0, 0⟩ : cubic R).to_poly.degree = βŠ₯ := degree_of_d_eq_zero rfl rfl rfl rfl @[simp] lemma degree_of_zero : (0 : cubic R).to_poly.degree = βŠ₯ := degree_of_d_eq_zero' @[simp] lemma leading_coeff_of_a_ne_zero (ha : P.a β‰  0) : P.to_poly.leading_coeff = P.a := leading_coeff_cubic ha @[simp] lemma leading_coeff_of_a_ne_zero' (ha : a β‰  0) : (to_poly ⟨a, b, c, d⟩).leading_coeff = a := leading_coeff_of_a_ne_zero ha @[simp] lemma leading_coeff_of_b_ne_zero (ha : P.a = 0) (hb : P.b β‰  0) : P.to_poly.leading_coeff = P.b := by rw [of_a_eq_zero ha, leading_coeff_quadratic hb] @[simp] lemma leading_coeff_of_b_ne_zero' (hb : b β‰  0) : (to_poly ⟨0, b, c, d⟩).leading_coeff = b := leading_coeff_of_b_ne_zero rfl hb @[simp] lemma leading_coeff_of_c_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c β‰  0) : P.to_poly.leading_coeff = P.c := by rw [of_b_eq_zero ha hb, leading_coeff_linear hc] @[simp] lemma leading_coeff_of_c_ne_zero' (hc : c β‰  0) : (to_poly ⟨0, 0, c, d⟩).leading_coeff = c := leading_coeff_of_c_ne_zero rfl rfl hc @[simp] lemma leading_coeff_of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.to_poly.leading_coeff = P.d := by rw [of_c_eq_zero ha hb hc, leading_coeff_C] @[simp] lemma leading_coeff_of_c_eq_zero' : (to_poly ⟨0, 0, 0, d⟩).leading_coeff = d := leading_coeff_of_c_eq_zero rfl rfl rfl end degree /-! ### Map across a homomorphism -/ section map variables [semiring S] {Ο† : R β†’+* S} /-- Map a cubic polynomial across a semiring homomorphism. -/ def map (Ο† : R β†’+* S) (P : cubic R) : cubic S := βŸ¨Ο† P.a, Ο† P.b, Ο† P.c, Ο† P.d⟩ lemma map_to_poly : (map Ο† P).to_poly = polynomial.map Ο† P.to_poly := by simp only [map, to_poly, map_C, map_X, polynomial.map_add, polynomial.map_mul, polynomial.map_pow] end map end basic section roots open multiset /-! ### Roots over an extension -/ section extension variables {P : cubic R} [comm_ring R] [comm_ring S] {Ο† : R β†’+* S} /-- The roots of a cubic polynomial. -/ def roots [is_domain R] (P : cubic R) : multiset R := P.to_poly.roots lemma map_roots [is_domain S] : (map Ο† P).roots = (polynomial.map Ο† P.to_poly).roots := by rw [roots, map_to_poly] theorem mem_roots_iff [is_domain R] (h0 : P.to_poly β‰  0) (x : R) : x ∈ P.roots ↔ P.a * x ^ 3 + P.b * x ^ 2 + P.c * x + P.d = 0 := begin rw [roots, mem_roots h0, is_root, to_poly], simp only [eval_C, eval_X, eval_add, eval_mul, eval_pow] end theorem card_roots_le [is_domain R] [decidable_eq R] : P.roots.to_finset.card ≀ 3 := begin apply (to_finset_card_le P.to_poly.roots).trans, by_cases hP : P.to_poly = 0, { exact (card_roots' P.to_poly).trans (by { rw [hP, nat_degree_zero], exact zero_le 3 }) }, { exact with_bot.coe_le_coe.1 ((card_roots hP).trans degree_cubic_le) } end end extension variables {P : cubic F} [field F] [field K] {Ο† : F β†’+* K} {x y z : K} /-! ### Roots over a splitting field -/ section split theorem splits_iff_card_roots (ha : P.a β‰  0) : splits Ο† P.to_poly ↔ (map Ο† P).roots.card = 3 := begin replace ha : (map Ο† P).a β‰  0 := (_root_.map_ne_zero Ο†).mpr ha, nth_rewrite_lhs 0 [← ring_hom.id_comp Ο†], rw [roots, ← splits_map_iff, ← map_to_poly, splits_iff_card_roots, ← ((degree_eq_iff_nat_degree_eq $ ne_zero_of_a_ne_zero ha).mp $ degree_of_a_ne_zero ha : _ = 3)] end theorem splits_iff_roots_eq_three (ha : P.a β‰  0) : splits Ο† P.to_poly ↔ βˆƒ x y z : K, (map Ο† P).roots = {x, y, z} := by rw [splits_iff_card_roots ha, card_eq_three] theorem eq_prod_three_roots (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : (map Ο† P).to_poly = C (Ο† P.a) * (X - C x) * (X - C y) * (X - C z) := begin rw [map_to_poly, eq_prod_roots_of_splits $ (splits_iff_roots_eq_three ha).mpr $ exists.intro x $ exists.intro y $ exists.intro z h3, leading_coeff_of_a_ne_zero ha, ← map_roots, h3], change C (Ο† P.a) * ((X - C x) ::β‚˜ (X - C y) ::β‚˜ {X - C z}).prod = _, rw [prod_cons, prod_cons, prod_singleton, mul_assoc, mul_assoc] end theorem eq_sum_three_roots (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : map Ο† P = βŸ¨Ο† P.a, Ο† P.a * -(x + y + z), Ο† P.a * (x * y + x * z + y * z), Ο† P.a * -(x * y * z)⟩ := begin apply_fun to_poly, any_goals { exact Ξ» P Q, (to_poly_injective P Q).mp }, rw [eq_prod_three_roots ha h3, to_poly], simp only [C_neg, C_add, C_mul], ring1 end theorem b_eq_three_roots (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : Ο† P.b = Ο† P.a * -(x + y + z) := by injection eq_sum_three_roots ha h3 theorem c_eq_three_roots (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : Ο† P.c = Ο† P.a * (x * y + x * z + y * z) := by injection eq_sum_three_roots ha h3 theorem d_eq_three_roots (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : Ο† P.d = Ο† P.a * -(x * y * z) := by injection eq_sum_three_roots ha h3 end split /-! ### Discriminant over a splitting field -/ section discriminant /-- The discriminant of a cubic polynomial. -/ def disc {R : Type*} [ring R] (P : cubic R) : R := P.b ^ 2 * P.c ^ 2 - 4 * P.a * P.c ^ 3 - 4 * P.b ^ 3 * P.d - 27 * P.a ^ 2 * P.d ^ 2 + 18 * P.a * P.b * P.c * P.d theorem disc_eq_prod_three_roots (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : Ο† P.disc = (Ο† P.a * Ο† P.a * (x - y) * (x - z) * (y - z)) ^ 2 := begin simp only [disc, ring_hom.map_add, ring_hom.map_sub, ring_hom.map_mul, map_pow], simp only [ring_hom.map_one, map_bit0, map_bit1], rw [b_eq_three_roots ha h3, c_eq_three_roots ha h3, d_eq_three_roots ha h3], ring1 end theorem disc_ne_zero_iff_roots_ne (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : P.disc β‰  0 ↔ x β‰  y ∧ x β‰  z ∧ y β‰  z := begin rw [←_root_.map_ne_zero Ο†, disc_eq_prod_three_roots ha h3, pow_two], simp_rw [mul_ne_zero_iff, sub_ne_zero, _root_.map_ne_zero, and_self, and_iff_right ha, and_assoc], end theorem disc_ne_zero_iff_roots_nodup (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) : P.disc β‰  0 ↔ (map Ο† P).roots.nodup := begin rw [disc_ne_zero_iff_roots_ne ha h3, h3], change _ ↔ (x ::β‚˜ y ::β‚˜ {z}).nodup, rw [nodup_cons, nodup_cons, mem_cons, mem_singleton, mem_singleton], simp only [nodup_singleton], tautology end theorem card_roots_of_disc_ne_zero [decidable_eq K] (ha : P.a β‰  0) (h3 : (map Ο† P).roots = {x, y, z}) (hd : P.disc β‰  0) : (map Ο† P).roots.to_finset.card = 3 := begin rw [to_finset_card_of_nodup $ (disc_ne_zero_iff_roots_nodup ha h3).mp hd, ← splits_iff_card_roots ha, splits_iff_roots_eq_three ha], exact ⟨x, ⟨y, ⟨z, h3⟩⟩⟩ end end discriminant end roots end cubic
579a25bbd240652e0aec947a4a24a3744fbce719
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/examples/lean/primes.lean
167800157f20d826ae5630a4c16f6df9d9318d82
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
18,055
lean
---------------------------------------------------------------------------------------------------- -- -- theory primes.lean -- author: Jeremy Avigad -- -- Experimenting with Lean. -- ---------------------------------------------------------------------------------------------------- import macros import tactic using Nat -- -- fundamental properties of Nat -- theorem cases_on {P : Nat β†’ Bool} (a : Nat) (H1 : P 0) (H2 : βˆ€ (n : Nat), P (n + 1)) : P a := induction_on a H1 (take n : Nat, assume ih : P n, H2 n) theorem strong_induction_on {P : Nat β†’ Bool} (a : Nat) (H : βˆ€ n, (βˆ€ m, m < n β†’ P m) β†’ P n) : P a := @strong_induction P H a -- in hindsight, now I know I don't need these theorem one_ne_zero : 1 β‰  0 := succ_nz 0 theorem two_ne_zero : 2 β‰  0 := succ_nz 1 -- -- observation: the proof of lt_le_trans in Nat is not needed -- theorem lt_le_trans2 {a b c : Nat} (H1 : a < b) (H2 : b ≀ c) : a < c := le_trans H1 H2 -- -- also, contrapos and mt are the same theorem -- theorem contrapos2 {a b : Bool} (H : a β†’ b) : Β¬ b β†’ Β¬ a := mt H -- -- properties of lt and le -- theorem succ_le_succ {a b : Nat} (H : a + 1 ≀ b + 1) : a ≀ b := obtain (x : Nat) (Hx : a + 1 + x = b + 1), from lt_elim H, have H2 : a + x + 1 = b + 1, from (calc a + x + 1 = a + (x + 1) : add_assoc _ _ _ ... = a + (1 + x) : { add_comm x 1 } ... = a + 1 + x : symm (add_assoc _ _ _) ... = b + 1 : Hx), have H3 : a + x = b, from (succ_inj H2), show a ≀ b, from (le_intro H3) -- should we keep this duplication or < and <=? theorem lt_succ {a b : Nat} (H : a < b + 1) : a ≀ b := succ_le_succ H theorem succ_le_succ_eq (a b : Nat) : a + 1 ≀ b + 1 ↔ a ≀ b := iff_intro succ_le_succ (assume H : a ≀ b, le_add H 1) theorem lt_succ_eq (a b : Nat) : a < b + 1 ↔ a ≀ b := succ_le_succ_eq a b theorem le_or_lt (a : Nat) : βˆ€ b : Nat, a ≀ b ∨ b < a := induction_on a ( show βˆ€b, 0 ≀ b ∨ b < 0, from take b, or_introl (le_zero b) _ ) ( take a, assume ih : βˆ€b, a ≀ b ∨ b < a, show βˆ€b, a + 1 ≀ b ∨ b < a + 1, from take b, cases_on b ( show a + 1 ≀ 0 ∨ 0 < a + 1, from or_intror _ (le_add (le_zero a) 1) ) ( take b, have H : a ≀ b ∨ b < a, from ih b, show a + 1 ≀ b + 1 ∨ b + 1 < a + 1, from or_elim H ( assume H1 : a ≀ b, or_introl (le_add H1 1) (b + 1 < a + 1) ) ( assume H2 : b < a, or_intror (a + 1 ≀ b + 1) (le_add H2 1) ) ) ) theorem not_le_lt {a b : Nat} : Β¬ a ≀ b β†’ b < a := (or_imp _ _) β—‚ le_or_lt a b theorem not_lt_le {a b : Nat} : Β¬ a < b β†’ b ≀ a := (or_imp _ _) β—‚ (or_comm _ _ β—‚ le_or_lt b a) theorem lt_not_le {a b : Nat} (H : a < b) : Β¬ b ≀ a := not_intro (take H1 : b ≀ a, absurd (lt_le_trans H H1) (lt_nrefl a)) theorem le_not_lt {a b : Nat} (H : a ≀ b) : Β¬ b < a := not_intro (take H1 : b < a, absurd H (lt_not_le H1)) theorem not_le_iff {a b : Nat} : Β¬ a ≀ b ↔ b < a := iff_intro (@not_le_lt a b) (@lt_not_le b a) theorem not_lt_iff {a b : Nat} : Β¬ a < b ↔ b ≀ a := iff_intro (@not_lt_le a b) (@le_not_lt b a) theorem le_iff {a b : Nat} : a ≀ b ↔ a < b ∨ a = b := iff_intro ( assume H : a ≀ b, show a < b ∨ a = b, from or_elim (em (a = b)) ( take H1 : a = b, show a < b ∨ a = b, from or_intror _ H1 ) ( take H2 : a β‰  b, have H3 : Β¬ b ≀ a, from not_intro (take H4: b ≀ a, absurd (le_antisym H H4) H2), have H4 : a < b, from resolve1 (le_or_lt b a) H3, show a < b ∨ a = b, from or_introl H4 _ ) )( assume H : a < b ∨ a = b, show a ≀ b, from or_elim H ( take H1 : a < b, lt_le H1 ) ( take H1 : a = b, subst (le_refl a) H1 ) ) theorem ne_symm_iff {A : (Type U)} (a b : A) : a β‰  b ↔ b β‰  a := iff_intro ne_symm ne_symm theorem lt_iff (a b : Nat) : a < b ↔ a ≀ b ∧ a β‰  b := calc a < b = Β¬ b ≀ a : symm (not_le_iff) ... = Β¬ (b < a ∨ b = a) : { le_iff } ... = Β¬ b < a ∧ b β‰  a : not_or _ _ ... = a ≀ b ∧ b β‰  a : { not_lt_iff } ... = a ≀ b ∧ a β‰  b : { ne_symm_iff _ _ } theorem ne_zero_ge_one {x : Nat} (H : x β‰  0) : x β‰₯ 1 := resolve2 (le_iff β—‚ (le_zero x)) (ne_symm H) theorem ne_zero_one_ge_two {x : Nat} (H0 : x β‰  0) (H1 : x β‰  1) : x β‰₯ 2 := resolve2 (le_iff β—‚ (ne_zero_ge_one H0)) (ne_symm H1) -- the forward direction can be replaced by ne_zero_ge_one, but -- note the comments below theorem ne_zero_iff (n : Nat) : n β‰  0 ↔ n > 0 := iff_intro ( assume H : n β‰  0, by_contradiction ( assume H1 : Β¬ n > 0, -- curious: if you make the arguments implicit in the next line, -- it fails (the evaluator is getting in the way, I think) have H2 : n = 0, from le_antisym (@not_lt_le 0 n H1) (le_zero n), absurd H2 H ) ) ( -- here too assume H : n > 0, ne_symm (@lt_ne 0 n H) ) -- Note: this differs from Leo's naming conventions theorem mul_right_mono {x y : Nat} (H : x ≀ y) (z : Nat) : x * z ≀ y * z := obtain (w : Nat) (Hw : x + w = y), from le_elim H, le_intro ( show x * z + w * z = y * z, from calc x * z + w * z = (x + w) * z : symm (distributel x w z) ... = y * z : { Hw } ) theorem mul_left_mono (x : Nat) {y z : Nat} (H : y ≀ z) : x * y ≀ x * z := subst (subst (mul_right_mono H x) (mul_comm y x)) (mul_comm z x) theorem le_addr (a b : Nat) : a ≀ a + b := le_intro (refl (a + b)) theorem le_addl (a b : Nat) : a ≀ b + a := subst (le_addr a b) (add_comm a b) theorem add_left_mono {a b : Nat} (c : Nat) (H : a ≀ b) : c + a ≀ c + b := subst (subst (le_add H c) (add_comm a c)) (add_comm b c) theorem mul_right_strict_mono {x y z : Nat} (H : x < y) (znez : z β‰  0) : x * z < y * z := obtain (w : Nat) (Hw : x + 1 + w = y), from le_elim H, have H1 : y * z = x * z + w * z + z, from calc y * z = (x + 1 + w) * z : { symm Hw } ... = (x + (1 + w)) * z : { add_assoc _ _ _ } ... = (x + (w + 1)) * z : { add_comm _ _ } ... = (x + w + 1) * z : { symm (add_assoc _ _ _) } ... = (x + w) * z + 1 * z : distributel _ _ _ ... = (x + w) * z + z : { mul_onel _ } ... = x * z + w * z + z : { distributel _ _ _ }, have H2 : x * z ≀ x * z + w * z, from le_addr _ _, have H3 : x * z + w * z < x * z + w * z + z, from add_left_mono _ (ne_zero_ge_one znez), show x * z < y * z, from subst (le_lt_trans H2 H3) (symm H1) theorem mul_left_strict_mono {x y z : Nat} (H : x < y) (znez : z β‰  0) : z * x < z * y := subst (subst (mul_right_strict_mono H znez) (mul_comm x z)) (mul_comm y z) theorem mul_left_le_cancel {a b c : Nat} (H : a * b ≀ a * c) (anez : a β‰  0) : b ≀ c := by_contradiction ( assume H1 : Β¬ b ≀ c, have H2 : a * c < a * b, from mul_left_strict_mono (not_le_lt H1) anez, show false, from absurd H (lt_not_le H2) ) theorem mul_right_le_cancel {a b c : Nat} (H : b * a ≀ c * a) (anez : a β‰  0) : b ≀ c := mul_left_le_cancel (subst (subst H (mul_comm b a)) (mul_comm c a)) anez theorem mul_left_lt_cancel {a b c : Nat} (H : a * b < a * c) : b < c := by_contradiction ( assume H1 : Β¬ b < c, have H2 : a * c ≀ a * b, from mul_left_mono a (not_lt_le H1), show false, from absurd H (le_not_lt H2) ) theorem mul_right_lt_cancel {a b c : Nat} (H : b * a < c * a) : b < c := mul_left_lt_cancel (subst (subst H (mul_comm b a)) (mul_comm c a)) theorem add_right_comm (a b c : Nat) : a + b + c = a + c + b := calc a + b + c = a + (b + c) : add_assoc _ _ _ ... = a + (c + b) : { add_comm b c } ... = a + c + b : symm (add_assoc _ _ _) theorem add_left_le_cancel {a b c : Nat} (H : a + c ≀ b + c) : a ≀ b := obtain (d : Nat) (Hd : a + c + d = b + c), from le_elim H, le_intro (add_injl (subst Hd (add_right_comm a c d))) theorem add_right_le_cancel {a b c : Nat} (H : c + a ≀ c + b) : a ≀ b := add_left_le_cancel (subst (subst H (add_comm c a)) (add_comm c b)) -- -- more properties of multiplication -- theorem mul_left_cancel {a b c : Nat} (H : a * b = a * c) (anez : a β‰  0) : b = c := have H1 : a * b ≀ a * c, from subst (le_refl _) H, have H2 : a * c ≀ a * b, from subst (le_refl _) H, le_antisym (mul_left_le_cancel H1 anez) (mul_left_le_cancel H2 anez) theorem mul_right_cancel {a b c : Nat} (H : b * a = c * a) (anez : a β‰  0) : b = c := mul_left_cancel (subst (subst H (mul_comm b a)) (mul_comm c a)) anez -- -- divisibility -- definition dvd (a b : Nat) : Bool := βˆƒ c, a * c = b infix 50 | : dvd theorem dvd_intro {a b c : Nat} (H : a * c = b) : a | b := exists_intro c H theorem dvd_elim {a b : Nat} (H : a | b) : βˆƒ c, a * c = b := H theorem dvd_self (n : Nat) : n | n := dvd_intro (mul_oner n) theorem one_dvd (a : Nat) : 1 | a := dvd_intro (mul_onel a) theorem zero_dvd {a : Nat} (H: 0 | a) : a = 0 := obtain (w : Nat) (H1 : 0 * w = a), from H, subst (symm H1) (mul_zerol _) theorem dvd_zero (a : Nat) : a | 0 := exists_intro 0 (mul_zeror _) theorem dvd_trans {a b c} (H1 : a | b) (H2 : b | c) : a | c := obtain (w1 : Nat) (Hw1 : a * w1 = b), from H1, obtain (w2 : Nat) (Hw2 : b * w2 = c), from H2, exists_intro (w1 * w2) calc a * (w1 * w2) = a * w1 * w2 : symm (mul_assoc a w1 w2) ... = b * w2 : { Hw1 } ... = c : Hw2 theorem dvd_le {x y : Nat} (H : x | y) (ynez : y β‰  0) : x ≀ y := obtain (w : Nat) (Hw : x * w = y), from H, have wnez : w β‰  0, from not_intro (take H1 : w = 0, absurd ( calc y = x * w : symm Hw ... = x * 0 : { H1 } ... = 0 : mul_zeror x ) ynez), have H2 : x * 1 ≀ x * w, from mul_left_mono x (ne_zero_ge_one wnez), show x ≀ y, from subst (subst H2 (mul_oner x)) Hw theorem dvd_mul_right {a b : Nat} (H : a | b) (c : Nat) : a | b * c := obtain (d : Nat) (Hd : a * d = b), from dvd_elim H, dvd_intro ( calc a * (d * c) = (a * d) * c : symm (mul_assoc _ _ _) ... = b * c : { Hd } ) theorem dvd_mul_left {a b : Nat} (H : a | b) (c : Nat) : a | c * b := subst (dvd_mul_right H c) (mul_comm b c) theorem dvd_add {a b c : Nat} (H1 : a | b) (H2 : a | c) : a | b + c := obtain (w1 : Nat) (Hw1 : a * w1 = b), from H1, obtain (w2 : Nat) (Hw2 : a * w2 = c), from H2, exists_intro (w1 + w2) calc a * (w1 + w2) = a * w1 + a * w2 : distributer _ _ _ ... = b + a * w2 : { Hw1 } ... = b + c : { Hw2 } theorem dvd_add_cancel {a b c : Nat} (H1 : a | b + c) (H2 : a | b) : a | c := or_elim (em (a = 0)) ( assume az : a = 0, have H3 : c = 0, from calc c = 0 + c : symm (add_zerol _) ... = b + c : { symm (zero_dvd (subst H2 az)) } ... = 0 : zero_dvd (subst H1 az), show a | c, from subst (dvd_zero a) (symm H3) ) ( assume anz : a β‰  0, obtain (w1 : Nat) (Hw1 : a * w1 = b + c), from H1, obtain (w2 : Nat) (Hw2 : a * w2 = b), from H2, have H3 : a * w1 = a * w2 + c, from subst Hw1 (symm Hw2), have H4 : a * w2 ≀ a * w1, from le_intro (symm H3), have H5 : w2 ≀ w1, from mul_left_le_cancel H4 anz, obtain (w3 : Nat) (Hw3 : w2 + w3 = w1), from le_elim H5, have H6 : b + a * w3 = b + c, from calc b + a * w3 = a * w2 + a * w3 : { symm Hw2 } ... = a * (w2 + w3) : symm (distributer _ _ _) ... = a * w1 : { Hw3 } ... = b + c : Hw1, have H7 : a * w3 = c, from add_injr H6, show a | c, from dvd_intro H7 ) -- -- primes -- definition prime p := p β‰₯ 2 ∧ forall m, m | p β†’ m = 1 ∨ m = p theorem not_prime_has_divisor {n : Nat} (H1 : n β‰₯ 2) (H2 : Β¬ prime n) : βˆƒ m, m | n ∧ m β‰  1 ∧ m β‰  n := have H3 : Β¬ n β‰₯ 2 ∨ Β¬ (βˆ€ m : Nat, m | n β†’ m = 1 ∨ m = n), from not_and _ _ β—‚ H2, have H4 : Β¬ Β¬ n β‰₯ 2, from (symm (not_not_eq _)) β—‚ H1, obtain (m : Nat) (H5 : Β¬ (m | n β†’ m = 1 ∨ m = n)), from not_forall_elim (resolve1 H3 H4), have H6 : m | n ∧ Β¬ (m = 1 ∨ m = n), from (not_implies _ _) β—‚ H5, have H7 : Β¬ (m = 1 ∨ m = n) ↔ (m β‰  1 ∧ m β‰  n), from not_or (m = 1) (m = n), have H8 : m | n ∧ m β‰  1 ∧ m β‰  n, from subst H6 H7, show βˆƒ m, m | n ∧ m β‰  1 ∧ m β‰  n, from exists_intro m H8 theorem not_prime_has_divisor2 {n : Nat} (H1 : n β‰₯ 2) (H2 : Β¬ prime n) : βˆƒ m, m | n ∧ m β‰₯ 2 ∧ m < n := have n_ne_0 : n β‰  0, from not_intro (take n0 : n = 0, substp (fun n, n β‰₯ 2) H1 n0), obtain (m : Nat) (Hm : m | n ∧ m β‰  1 ∧ m β‰  n), from not_prime_has_divisor H1 H2, let m_dvd_n := and_eliml Hm in let m_ne_1 := and_eliml (and_elimr Hm) in let m_ne_n := and_elimr (and_elimr Hm) in have m_ne_0 : m β‰  0, from not_intro ( take m0 : m = 0, have n0 : n = 0, from zero_dvd (subst m_dvd_n m0), absurd n0 n_ne_0 ), exists_intro m ( and_intro m_dvd_n ( and_intro ( show m β‰₯ 2, from ne_zero_one_ge_two m_ne_0 m_ne_1 ) ( have m_le_n : m ≀ n, from dvd_le m_dvd_n n_ne_0, show m < n, from resolve2 (le_iff β—‚ m_le_n) m_ne_n ) ) ) theorem has_prime_divisor {n : Nat} : n β‰₯ 2 β†’ βˆƒ p, prime p ∧ p | n := strong_induction_on n ( take n, assume ih : βˆ€ m, m < n β†’ m β‰₯ 2 β†’ βˆƒ p, prime p ∧ p | m, assume n_ge_2 : n β‰₯ 2, show βˆƒ p, prime p ∧ p | n, from or_elim (em (prime n)) ( assume H : prime n, exists_intro n (and_intro H (dvd_self n)) ) ( assume H : Β¬ prime n, obtain (m : Nat) (Hm : m | n ∧ m β‰₯ 2 ∧ m < n), from not_prime_has_divisor2 n_ge_2 H, obtain (p : Nat) (Hp : prime p ∧ p | m), from ih m (and_elimr (and_elimr Hm)) (and_eliml (and_elimr Hm)), have p_dvd_n : p | n, from dvd_trans (and_elimr Hp) (and_eliml Hm), exists_intro p (and_intro (and_eliml Hp) p_dvd_n) ) ) -- -- factorial -- variable fact : Nat β†’ Nat axiom fact_0 : fact 0 = 1 axiom fact_succ : βˆ€ n, fact (n + 1) = (n + 1) * fact n -- can the simplifier do this? theorem fact_1 : fact 1 = 1 := calc fact 1 = fact (0 + 1) : { symm (add_zerol 1) } ... = (0 + 1) * fact 0 : fact_succ _ ... = 1 * fact 0 : { add_zerol 1 } ... = 1 * 1 : { fact_0 } ... = 1 : mul_oner _ theorem fact_ne_0 (n : Nat) : fact n β‰  0 := induction_on n ( not_intro ( assume H : fact 0 = 0, have H1 : 1 = 0, from (subst H fact_0), absurd H1 one_ne_zero ) ) ( take n, assume ih : fact n β‰  0, not_intro ( assume H : fact (n + 1) = 0, have H1 : n + 1 = 0, from mul_right_cancel ( calc (n + 1) * fact n = fact (n + 1) : symm (fact_succ n) ... = 0 : H ... = 0 * fact n : symm (mul_zerol _) ) ih, absurd H1 (succ_nz _) ) ) theorem dvd_fact {m n : Nat} (m_gt_0 : m > 0) (m_le_n : m ≀ n) : m | fact n := obtain (m' : Nat) (Hm' : 1 + m' = m), from le_elim m_gt_0, obtain (n' : Nat) (Hn' : 1 + n' = n), from le_elim (le_trans m_gt_0 m_le_n), have m'_le_n' : m' ≀ n', from add_right_le_cancel (subst (subst m_le_n (symm Hm')) (symm Hn')), have H : βˆ€ n' m', m' ≀ n' β†’ m' + 1 | fact (n' + 1), from induction ( take m' , assume m'_le_0 : m' ≀ 0, have Hm' : m' + 1 = 1, from calc m' + 1 = 0 + 1 : { le_antisym m'_le_0 (le_zero m') } ... = 1 : add_zerol _, show m' + 1 | fact (0 + 1), from subst (one_dvd _) (symm Hm') ) ( take n', assume ih : βˆ€m', m' ≀ n' β†’ m' + 1 | fact (n' + 1), take m', assume Hm' : m' ≀ n' + 1, have H1 : m' < n' + 1 ∨ m' = n' + 1, from le_iff β—‚ Hm', or_elim H1 ( assume H2 : m' < n' + 1, have H3 : m' ≀ n', from lt_succ H2, have H4 : m' + 1 | fact (n' + 1), from ih _ H3, have H5 : m' + 1 | (n' + 1 + 1) * fact (n' + 1), from dvd_mul_left H4 _, show m' + 1 | fact (n' + 1 + 1), from subst H5 (symm (fact_succ _)) ) ( assume H2 : m' = n' + 1, have H3 : m' + 1 | n' + 1 + 1, from subst (dvd_self _) H2, have H4 : m' + 1 | (n' + 1 + 1) * fact (n' + 1), from dvd_mul_right H3 _, show m' + 1 | fact (n' + 1 + 1), from subst H4 (symm (fact_succ _)) ) ), have H1 : m' + 1 | fact (n' + 1), from H _ _ m'_le_n', show m | fact n, from (subst (subst (subst (subst H1 (add_comm m' 1)) Hm') (add_comm n' 1)) Hn') theorem primes_infinite (n : Nat) : βˆƒ p, p β‰₯ n ∧ prime p := let m := fact (n + 1) in have Hn1 : n + 1 β‰₯ 1, from le_addl _ _, have m_ge_1 : m β‰₯ 1, from ne_zero_ge_one (fact_ne_0 _), have m1_ge_2 : m + 1 β‰₯ 2, from le_add m_ge_1 1, obtain (p : Nat) (Hp : prime p ∧ p | m + 1), from has_prime_divisor m1_ge_2, let prime_p := and_eliml Hp in let p_dvd_m1 := and_elimr Hp in have p_ge_2 : p β‰₯ 2, from and_eliml prime_p, have two_gt_0 : 2 > 0, from (ne_zero_iff 2) β—‚ (succ_nz 1), -- fails if arguments are left implicit have p_gt_0 : p > 0, from @lt_le_trans 0 2 p two_gt_0 p_ge_2, have p_ge_n : p β‰₯ n, from by_contradiction ( assume H1 : Β¬ p β‰₯ n, have H2 : p < n, from not_le_lt H1, have H3 : p ≀ n + 1, from lt_le (lt_le_trans H2 (le_addr n 1)), have H4 : p | m, from dvd_fact p_gt_0 H3, have H5 : p | 1, from dvd_add_cancel p_dvd_m1 H4, have H6 : p ≀ 1, from dvd_le H5 (succ_nz 0), have H7 : 2 ≀ 1, from le_trans p_ge_2 H6, absurd H7 (lt_nrefl 1) ), exists_intro p (and_intro p_ge_n prime_p)
11022e7e6ca5dfd88202e98f0b991a26da1680a7
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/Algebra/basic.lean
9369539b293f7eec2818678ecebfddc9ac0f32e6
[ "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
3,395
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.CommRing.basic import algebra.category.Module.basic import ring_theory.algebra open category_theory open category_theory.limits universe u variables (R : Type u) [comm_ring R] /-- The category of R-modules and their morphisms. -/ structure Algebra := (carrier : Type u) [is_ring : ring carrier] [is_algebra : algebra R carrier] attribute [instance] Algebra.is_ring Algebra.is_algebra namespace Algebra instance : has_coe_to_sort (Algebra R) := { S := Type u, coe := Algebra.carrier } instance : category (Algebra R) := { hom := Ξ» A B, A →ₐ[R] B, id := Ξ» A, alg_hom.id R A, comp := Ξ» A B C f g, g.comp f } instance : concrete_category (Algebra R) := { forget := { obj := Ξ» R, R, map := Ξ» R S f, (f : R β†’ S) }, forget_faithful := { } } instance has_forget_to_Ring : has_forgetβ‚‚ (Algebra R) Ring := { forgetβ‚‚ := { obj := Ξ» A, Ring.of A, map := Ξ» A₁ Aβ‚‚ f, alg_hom.to_ring_hom f, } } instance has_forget_to_Module : has_forgetβ‚‚ (Algebra R) (Module R) := { forgetβ‚‚ := { obj := Ξ» M, Module.of R M, map := Ξ» M₁ Mβ‚‚ f, alg_hom.to_linear_map f, } } /-- The object in the category of R-algebras associated to a type equipped with the appropriate typeclasses. -/ def of (X : Type u) [ring X] [algebra R X] : Algebra R := ⟨X⟩ instance : inhabited (Algebra R) := ⟨of R R⟩ @[simp] lemma of_apply (X : Type u) [ring X] [algebra R X] : (of R X : Type u) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original algebra. -/ @[simps] def of_self_iso (M : Algebra R) : Algebra.of R M β‰… M := { hom := πŸ™ M, inv := πŸ™ M } variables {R} {M N U : Module R} @[simp] lemma id_apply (m : M) : (πŸ™ M : M β†’ M) m = m := rfl @[simp] lemma coe_comp (f : M ⟢ N) (g : N ⟢ U) : ((f ≫ g) : M β†’ U) = g ∘ f := rfl end Algebra variables {R} variables {X₁ Xβ‚‚ : Type u} /-- Build an isomorphism in the category `Algebra R` from a `alg_equiv` between `algebra`s. -/ @[simps] def alg_equiv.to_Algebra_iso {g₁ : ring X₁} {gβ‚‚ : ring Xβ‚‚} {m₁ : algebra R X₁} {mβ‚‚ : algebra R Xβ‚‚} (e : X₁ ≃ₐ[R] Xβ‚‚) : Algebra.of R X₁ β‰… Algebra.of R Xβ‚‚ := { hom := (e : X₁ →ₐ[R] Xβ‚‚), inv := (e.symm : Xβ‚‚ →ₐ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } namespace category_theory.iso /-- Build a `alg_equiv` from an isomorphism in the category `Algebra R`. -/ @[simps] def to_alg_equiv {X Y : Algebra R} (i : X β‰… Y) : X ≃ₐ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy, commutes' := by tidy, }. end category_theory.iso /-- algebra equivalences between `algebras`s are the same as (isomorphic to) isomorphisms in `Algebra` -/ @[simps] def alg_equiv_iso_Algebra_iso {X Y : Type u} [ring X] [ring Y] [algebra R X] [algebra R Y] : (X ≃ₐ[R] Y) β‰… (Algebra.of R X β‰… Algebra.of R Y) := { hom := Ξ» e, e.to_Algebra_iso, inv := Ξ» i, i.to_alg_equiv, } instance (X : Type u) [ring X] [algebra R X] : has_coe (subalgebra R X) (Algebra R) := ⟨ Ξ» N, Algebra.of R N ⟩
38166e8e118f196acebd63ad08996c65eeb51ff7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/geom_sum_auto.lean
c47e168e1a62b48472213b68df02ffae2b4edec9
[]
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
5,562
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Sums of finite geometric series -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group_with_zero.power import Mathlib.algebra.big_operators.order import Mathlib.algebra.big_operators.ring import Mathlib.algebra.big_operators.intervals import Mathlib.PostPort universes u u_1 namespace Mathlib /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/ def geom_series {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (n : β„•) : Ξ± := finset.sum (finset.range n) fun (i : β„•) => x ^ i theorem geom_series_def {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (n : β„•) : geom_series x n = finset.sum (finset.range n) fun (i : β„•) => x ^ i := rfl @[simp] theorem geom_series_zero {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) : geom_series x 0 = 0 := rfl @[simp] theorem geom_series_one {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) : geom_series x 1 = 1 := sorry @[simp] theorem op_geom_series {Ξ± : Type u} [ring Ξ±] (x : Ξ±) (n : β„•) : opposite.op (geom_series x n) = geom_series (opposite.op x) n := sorry /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_seriesβ‚‚ {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (y : Ξ±) (n : β„•) : Ξ± := finset.sum (finset.range n) fun (i : β„•) => x ^ i * y ^ (n - 1 - i) theorem geom_seriesβ‚‚_def {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (y : Ξ±) (n : β„•) : geom_seriesβ‚‚ x y n = finset.sum (finset.range n) fun (i : β„•) => x ^ i * y ^ (n - 1 - i) := rfl @[simp] theorem geom_seriesβ‚‚_zero {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (y : Ξ±) : geom_seriesβ‚‚ x y 0 = 0 := rfl @[simp] theorem geom_seriesβ‚‚_one {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (y : Ξ±) : geom_seriesβ‚‚ x y 1 = 1 := sorry @[simp] theorem geom_seriesβ‚‚_with_one {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (n : β„•) : geom_seriesβ‚‚ x 1 n = geom_series x n := sorry /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sumβ‚‚_mul_add {Ξ± : Type u} [semiring Ξ±] {x : Ξ±} {y : Ξ±} (h : commute x y) (n : β„•) : geom_seriesβ‚‚ (x + y) y n * x + y ^ n = (x + y) ^ n := sorry theorem geom_seriesβ‚‚_self {Ξ± : Type u_1} [comm_ring Ξ±] (x : Ξ±) (n : β„•) : geom_seriesβ‚‚ x x n = ↑n * x ^ (n - 1) := sorry /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sumβ‚‚_mul_add {Ξ± : Type u} [comm_semiring Ξ±] (x : Ξ±) (y : Ξ±) (n : β„•) : geom_seriesβ‚‚ (x + y) y n * x + y ^ n = (x + y) ^ n := commute.geom_sumβ‚‚_mul_add (commute.all x y) n theorem geom_sum_mul_add {Ξ± : Type u} [semiring Ξ±] (x : Ξ±) (n : β„•) : geom_series (x + 1) n * x + 1 = (x + 1) ^ n := eq.mp (Eq._oldrec (Eq.refl (geom_seriesβ‚‚ (x + 1) 1 n * x + 1 = (x + 1) ^ n)) (geom_seriesβ‚‚_with_one (x + 1) n)) (eq.mp (Eq._oldrec (Eq.refl (geom_seriesβ‚‚ (x + 1) 1 n * x + 1 ^ n = (x + 1) ^ n)) (one_pow n)) (commute.geom_sumβ‚‚_mul_add (commute.one_right x) n)) theorem geom_sumβ‚‚_mul_comm {Ξ± : Type u} [ring Ξ±] {x : Ξ±} {y : Ξ±} (h : commute x y) (n : β„•) : geom_seriesβ‚‚ x y n * (x - y) = x ^ n - y ^ n := sorry theorem geom_sumβ‚‚_mul {Ξ± : Type u} [comm_ring Ξ±] (x : Ξ±) (y : Ξ±) (n : β„•) : geom_seriesβ‚‚ x y n * (x - y) = x ^ n - y ^ n := geom_sumβ‚‚_mul_comm (commute.all x y) n theorem geom_sum_mul {Ξ± : Type u} [ring Ξ±] (x : Ξ±) (n : β„•) : geom_series x n * (x - 1) = x ^ n - 1 := eq.mp (Eq._oldrec (Eq.refl (geom_seriesβ‚‚ x 1 n * (x - 1) = x ^ n - 1)) (geom_seriesβ‚‚_with_one x n)) (eq.mp (Eq._oldrec (Eq.refl (geom_seriesβ‚‚ x 1 n * (x - 1) = x ^ n - 1 ^ n)) (one_pow n)) (geom_sumβ‚‚_mul_comm (commute.one_right x) n)) theorem mul_geom_sum {Ξ± : Type u} [ring Ξ±] (x : Ξ±) (n : β„•) : (x - 1) * geom_series x n = x ^ n - 1 := sorry theorem geom_sum_mul_neg {Ξ± : Type u} [ring Ξ±] (x : Ξ±) (n : β„•) : geom_series x n * (1 - x) = 1 - x ^ n := sorry theorem mul_neg_geom_sum {Ξ± : Type u} [ring Ξ±] (x : Ξ±) (n : β„•) : (1 - x) * geom_series x n = 1 - x ^ n := sorry theorem geom_sum {Ξ± : Type u} [division_ring Ξ±] {x : Ξ±} (h : x β‰  1) (n : β„•) : geom_series x n = (x ^ n - 1) / (x - 1) := sorry theorem geom_sum_Ico_mul {Ξ± : Type u} [ring Ξ±] (x : Ξ±) {m : β„•} {n : β„•} (hmn : m ≀ n) : (finset.sum (finset.Ico m n) fun (i : β„•) => x ^ i) * (x - 1) = x ^ n - x ^ m := sorry theorem geom_sum_Ico_mul_neg {Ξ± : Type u} [ring Ξ±] (x : Ξ±) {m : β„•} {n : β„•} (hmn : m ≀ n) : (finset.sum (finset.Ico m n) fun (i : β„•) => x ^ i) * (1 - x) = x ^ m - x ^ n := sorry theorem geom_sum_Ico {Ξ± : Type u} [division_ring Ξ±] {x : Ξ±} (hx : x β‰  1) {m : β„•} {n : β„•} (hmn : m ≀ n) : (finset.sum (finset.Ico m n) fun (i : β„•) => x ^ i) = (x ^ n - x ^ m) / (x - 1) := sorry theorem geom_sum_inv {Ξ± : Type u} [division_ring Ξ±] {x : Ξ±} (hx1 : x β‰  1) (hx0 : x β‰  0) (n : β„•) : geom_series (x⁻¹) n = x - 1⁻¹ * (x - x⁻¹ ^ n * x) := sorry theorem ring_hom.map_geom_series {Ξ± : Type u} {Ξ² : Type u_1} [semiring Ξ±] [semiring Ξ²] (x : Ξ±) (n : β„•) (f : Ξ± β†’+* Ξ²) : coe_fn f (geom_series x n) = geom_series (coe_fn f x) n := sorry theorem ring_hom.map_geom_seriesβ‚‚ {Ξ± : Type u} {Ξ² : Type u_1} [semiring Ξ±] [semiring Ξ²] (x : Ξ±) (y : Ξ±) (n : β„•) (f : Ξ± β†’+* Ξ²) : coe_fn f (geom_seriesβ‚‚ x y n) = geom_seriesβ‚‚ (coe_fn f x) (coe_fn f y) n := sorry end Mathlib
671786e37e7a02a7c83824f1aca8b8865ae5d4e5
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/category_theory/limits/shapes/regular_mono.lean
e8606a61d217ff62d8f7aee7257f752997381ff3
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
14,858
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.preserves.basic import category_theory.limits.shapes.kernels import category_theory.limits.shapes.strong_epi import category_theory.limits.shapes.pullbacks /-! # Definitions and basic properties of regular and normal monomorphisms and epimorphisms. A regular monomorphism is a morphism that is the equalizer of some parallel pair. A normal monomorphism is a morphism that is the kernel of some other morphism. We give the constructions * `split_mono β†’ regular_mono` * `normal_mono β†’ regular_mono`, and * `regular_mono β†’ mono` as well as the dual constructions for regular and normal epimorphisms. Additionally, we give the construction * `regular_epi ⟢ strong_epi`. -/ noncomputable theory namespace category_theory open category_theory.limits universes v₁ u₁ uβ‚‚ variables {C : Type u₁} [category.{v₁} C] variables {X Y : C} /-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/ class regular_mono (f : X ⟢ Y) := (Z : C) (left right : Y ⟢ Z) (w : f ≫ left = f ≫ right) (is_limit : is_limit (fork.of_ΞΉ f w)) attribute [reassoc] regular_mono.w /-- Every regular monomorphism is a monomorphism. -/ @[priority 100] instance regular_mono.mono (f : X ⟢ Y) [regular_mono f] : mono f := mono_of_is_limit_parallel_pair regular_mono.is_limit instance equalizer_regular (g h : X ⟢ Y) [has_limit (parallel_pair g h)] : regular_mono (equalizer.ΞΉ g h) := { Z := Y, left := g, right := h, w := equalizer.condition g h, is_limit := fork.is_limit.mk _ (Ξ» s, limit.lift _ s) (by simp) (Ξ» s m w, by { ext1, simp [←w] }) } /-- Every split monomorphism is a regular monomorphism. -/ @[priority 100] instance regular_mono.of_split_mono (f : X ⟢ Y) [split_mono f] : regular_mono f := { Z := Y, left := πŸ™ Y, right := retraction f ≫ f, w := by tidy, is_limit := split_mono_equalizes f } /-- If `f` is a regular mono, then any map `k : W ⟢ Y` equalizing `regular_mono.left` and `regular_mono.right` induces a morphism `l : W ⟢ X` such that `l ≫ f = k`. -/ def regular_mono.lift' {W : C} (f : X ⟢ Y) [regular_mono f] (k : W ⟢ Y) (h : k ≫ (regular_mono.left : Y ⟢ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) : {l : W ⟢ X // l ≫ f = k} := fork.is_limit.lift' regular_mono.is_limit _ h /-- The second leg of a pullback cone is a regular monomorphism if the right component is too. See also `pullback.snd_of_mono` for the basic monomorphism version, and `regular_of_is_pullback_fst_of_regular` for the flipped version. -/ def regular_of_is_pullback_snd_of_regular {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : regular_mono g := { Z := hr.Z, left := k ≫ hr.left, right := k ≫ hr.right, w := by rw [← reassoc_of comm, ← reassoc_of comm, hr.w], is_limit := begin apply fork.is_limit.mk' _ _, intro s, have l₁ : (fork.ΞΉ s ≫ k) ≫ regular_mono.left = (fork.ΞΉ s ≫ k) ≫ regular_mono.right, rw [category.assoc, s.condition, category.assoc], obtain ⟨l, hl⟩ := fork.is_limit.lift' hr.is_limit _ l₁, obtain ⟨p, hp₁, hpβ‚‚βŸ© := pullback_cone.is_limit.lift' t _ _ hl, refine ⟨p, hpβ‚‚, _⟩, intros m w, have z : m ≫ g = p ≫ g := w.trans hpβ‚‚.symm, apply t.hom_ext, apply (pullback_cone.mk f g comm).equalizer_ext, { erw [← cancel_mono h, category.assoc, category.assoc, comm, reassoc_of z] }, { exact z }, end } /-- The first leg of a pullback cone is a regular monomorphism if the left component is too. See also `pullback.fst_of_mono` for the basic monomorphism version, and `regular_of_is_pullback_snd_of_regular` for the flipped version. -/ def regular_of_is_pullback_fst_of_regular {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : regular_mono f := regular_of_is_pullback_snd_of_regular comm.symm (pullback_cone.flip_is_limit t) /-- A regular monomorphism is an isomorphism if it is an epimorphism. -/ def is_iso_of_regular_mono_of_epi (f : X ⟢ Y) [regular_mono f] [e : epi f] : is_iso f := @is_iso_limit_cone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_mono.is_limit e section variables [has_zero_morphisms C] /-- A normal monomorphism is a morphism which is the kernel of some morphism. -/ class normal_mono (f : X ⟢ Y) := (Z : C) (g : Y ⟢ Z) (w : f ≫ g = 0) (is_limit : is_limit (kernel_fork.of_ΞΉ f w)) section local attribute [instance] fully_faithful_reflects_limits local attribute [instance] equivalence.ess_surj_of_equivalence /-- If `F` is an equivalence and `F.map f` is a normal mono, then `f` is a normal mono. -/ def equivalence_reflects_normal_mono {D : Type uβ‚‚} [category.{v₁} D] [has_zero_morphisms D] (F : C β₯€ D) [is_equivalence F] {X Y : C} {f : X ⟢ Y} (hf : normal_mono (F.map f)) : normal_mono f := { Z := F.obj_preimage hf.Z, g := full.preimage (hf.g ≫ (F.fun_obj_preimage_iso hf.Z).inv), w := faithful.map_injective F $ by simp [reassoc_of hf.w], is_limit := reflects_limit.reflects $ is_limit.of_cone_equiv (cones.postcompose_equivalence (comp_nat_iso F)) $ is_limit.of_iso_limit (by exact is_limit.of_iso_limit (is_kernel.of_comp_iso _ _ (F.fun_obj_preimage_iso hf.Z) (by simp) hf.is_limit) (of_ΞΉ_congr (category.comp_id _).symm)) (iso_of_ΞΉ _).symm } end /-- Every normal monomorphism is a regular monomorphism. -/ @[priority 100] instance normal_mono.regular_mono (f : X ⟢ Y) [I : normal_mono f] : regular_mono f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal mono, then any map `k : W ⟢ Y` such that `k ≫ normal_mono.g = 0` induces a morphism `l : W ⟢ X` such that `l ≫ f = k`. -/ def normal_mono.lift' {W : C} (f : X ⟢ Y) [normal_mono f] (k : W ⟢ Y) (h : k ≫ normal_mono.g = 0) : {l : W ⟢ X // l ≫ f = k} := kernel_fork.is_limit.lift' normal_mono.is_limit _ h /-- The second leg of a pullback cone is a normal monomorphism if the right component is too. See also `pullback.snd_of_mono` for the basic monomorphism version, and `normal_of_is_pullback_fst_of_normal` for the flipped version. -/ def normal_of_is_pullback_snd_of_normal {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [hn : normal_mono h] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : normal_mono g := { Z := hn.Z, g := k ≫ hn.g, w := by rw [← reassoc_of comm, hn.w, has_zero_morphisms.comp_zero], is_limit := begin letI gr := regular_of_is_pullback_snd_of_regular comm t, have q := (has_zero_morphisms.comp_zero k hn.Z).symm, convert gr.is_limit, dunfold kernel_fork.of_ΞΉ fork.of_ΞΉ, congr, exact q, exact q, exact q, apply proof_irrel_heq, end } /-- The first leg of a pullback cone is a normal monomorphism if the left component is too. See also `pullback.fst_of_mono` for the basic monomorphism version, and `normal_of_is_pullback_snd_of_normal` for the flipped version. -/ def normal_of_is_pullback_fst_of_normal {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [hn : normal_mono k] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : normal_mono f := normal_of_is_pullback_snd_of_normal comm.symm (pullback_cone.flip_is_limit t) end /-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/ class regular_epi (f : X ⟢ Y) := (W : C) (left right : W ⟢ X) (w : left ≫ f = right ≫ f) (is_colimit : is_colimit (cofork.of_Ο€ f w)) attribute [reassoc] regular_epi.w /-- Every regular epimorphism is an epimorphism. -/ @[priority 100] instance regular_epi.epi (f : X ⟢ Y) [regular_epi f] : epi f := epi_of_is_colimit_parallel_pair regular_epi.is_colimit instance coequalizer_regular (g h : X ⟢ Y) [has_colimit (parallel_pair g h)] : regular_epi (coequalizer.Ο€ g h) := { W := X, left := g, right := h, w := coequalizer.condition g h, is_colimit := cofork.is_colimit.mk _ (Ξ» s, colimit.desc _ s) (by simp) (Ξ» s m w, by { ext1, simp [←w] }) } /-- Every split epimorphism is a regular epimorphism. -/ @[priority 100] instance regular_epi.of_split_epi (f : X ⟢ Y) [split_epi f] : regular_epi f := { W := X, left := πŸ™ X, right := f ≫ section_ f, w := by tidy, is_colimit := split_epi_coequalizes f } /-- If `f` is a regular epi, then every morphism `k : X ⟢ W` coequalizing `regular_epi.left` and `regular_epi.right` induces `l : Y ⟢ W` such that `f ≫ l = k`. -/ def regular_epi.desc' {W : C} (f : X ⟢ Y) [regular_epi f] (k : X ⟢ W) (h : (regular_epi.left : regular_epi.W f ⟢ X) ≫ k = regular_epi.right ≫ k) : {l : Y ⟢ W // f ≫ l = k} := cofork.is_colimit.desc' (regular_epi.is_colimit) _ h /-- The second leg of a pushout cocone is a regular epimorphism if the right component is too. See also `pushout.snd_of_epi` for the basic epimorphism version, and `regular_of_is_pushout_fst_of_regular` for the flipped version. -/ def regular_of_is_pushout_snd_of_regular {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : regular_epi h := { W := gr.W, left := gr.left ≫ f, right := gr.right ≫ f, w := by rw [category.assoc, category.assoc, comm, reassoc_of gr.w], is_colimit := begin apply cofork.is_colimit.mk' _ _, intro s, have l₁ : gr.left ≫ f ≫ s.Ο€ = gr.right ≫ f ≫ s.Ο€, rw [← category.assoc, ← category.assoc, s.condition], obtain ⟨l, hl⟩ := cofork.is_colimit.desc' gr.is_colimit (f ≫ cofork.Ο€ s) l₁, obtain ⟨p, hp₁, hpβ‚‚βŸ© := pushout_cocone.is_colimit.desc' t _ _ hl.symm, refine ⟨p, hp₁, _⟩, intros m w, have z := w.trans hp₁.symm, apply t.hom_ext, apply (pushout_cocone.mk _ _ comm).coequalizer_ext, { exact z }, { erw [← cancel_epi g, ← reassoc_of comm, ← reassoc_of comm, z], refl }, end } /-- The first leg of a pushout cocone is a regular epimorphism if the left component is too. See also `pushout.fst_of_epi` for the basic epimorphism version, and `regular_of_is_pushout_snd_of_regular` for the flipped version. -/ def regular_of_is_pushout_fst_of_regular {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : regular_epi k := regular_of_is_pushout_snd_of_regular comm.symm (pushout_cocone.flip_is_colimit t) /-- A regular epimorphism is an isomorphism if it is a monomorphism. -/ def is_iso_of_regular_epi_of_mono (f : X ⟢ Y) [regular_epi f] [m : mono f] : is_iso f := @is_iso_limit_cocone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_epi.is_colimit m @[priority 100] instance strong_epi_of_regular_epi (f : X ⟢ Y) [regular_epi f] : strong_epi f := { epi := by apply_instance, has_lift := begin introsI, have : (regular_epi.left : regular_epi.W f ⟢ X) ≫ u = regular_epi.right ≫ u, { apply (cancel_mono z).1, simp only [category.assoc, h, regular_epi.w_assoc] }, obtain ⟨t, ht⟩ := regular_epi.desc' f u this, exact ⟨t, ht, (cancel_epi f).1 (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩, end } section variables [has_zero_morphisms C] /-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/ class normal_epi (f : X ⟢ Y) := (W : C) (g : W ⟢ X) (w : g ≫ f = 0) (is_colimit : is_colimit (cokernel_cofork.of_Ο€ f w)) section local attribute [instance] fully_faithful_reflects_colimits local attribute [instance] equivalence.ess_surj_of_equivalence /-- If `F` is an equivalence and `F.map f` is a normal epi, then `f` is a normal epi. -/ def equivalence_reflects_normal_epi {D : Type uβ‚‚} [category.{v₁} D] [has_zero_morphisms D] (F : C β₯€ D) [is_equivalence F] {X Y : C} {f : X ⟢ Y} (hf : normal_epi (F.map f)) : normal_epi f := { W := F.obj_preimage hf.W, g := full.preimage ((F.fun_obj_preimage_iso hf.W).hom ≫ hf.g), w := faithful.map_injective F $ by simp [hf.w], is_colimit := reflects_colimit.reflects $ is_colimit.of_cocone_equiv (cocones.precompose_equivalence (comp_nat_iso F).symm) $ is_colimit.of_iso_colimit (by exact is_colimit.of_iso_colimit (is_cokernel.of_iso_comp _ _ (F.fun_obj_preimage_iso hf.W).symm (by simp) hf.is_colimit) (of_Ο€_congr (category.id_comp _).symm)) (iso_of_Ο€ _).symm } end /-- Every normal epimorphism is a regular epimorphism. -/ @[priority 100] instance normal_epi.regular_epi (f : X ⟢ Y) [I : normal_epi f] : regular_epi f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal epi, then every morphism `k : X ⟢ W` satisfying `normal_epi.g ≫ k = 0` induces `l : Y ⟢ W` such that `f ≫ l = k`. -/ def normal_epi.desc' {W : C} (f : X ⟢ Y) [normal_epi f] (k : X ⟢ W) (h : normal_epi.g ≫ k = 0) : {l : Y ⟢ W // f ≫ l = k} := cokernel_cofork.is_colimit.desc' (normal_epi.is_colimit) _ h /-- The second leg of a pushout cocone is a normal epimorphism if the right component is too. See also `pushout.snd_of_epi` for the basic epimorphism version, and `normal_of_is_pushout_fst_of_normal` for the flipped version. -/ def normal_of_is_pushout_snd_of_normal {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [gn : normal_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : normal_epi h := { W := gn.W, g := gn.g ≫ f, w := by rw [category.assoc, comm, reassoc_of gn.w, zero_comp], is_colimit := begin letI hn := regular_of_is_pushout_snd_of_regular comm t, have q := (@zero_comp _ _ _ gn.W _ _ f).symm, convert hn.is_colimit, dunfold cokernel_cofork.of_Ο€ cofork.of_Ο€, congr, exact q, exact q, exact q, apply proof_irrel_heq, end } /-- The first leg of a pushout cocone is a normal epimorphism if the left component is too. See also `pushout.fst_of_epi` for the basic epimorphism version, and `normal_of_is_pushout_snd_of_normal` for the flipped version. -/ def normal_of_is_pushout_fst_of_normal {P Q R S : C} {f : P ⟢ Q} {g : P ⟢ R} {h : Q ⟢ S} {k : R ⟢ S} [hn : normal_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : normal_epi k := normal_of_is_pushout_snd_of_normal comm.symm (pushout_cocone.flip_is_colimit t) end end category_theory
74da03b678b2035b66623ba0f817503e9ce0b2e4
e0b0b1648286e442507eb62344760d5cd8d13f2d
/src/Lean/Meta/Match/Basic.lean
ba46ab6e43e724620d1ae6bb1fa8f85d7b291966
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,603
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.Check import Lean.Meta.Match.MatcherInfo import Lean.Meta.Match.CaseArraySizes namespace Lean.Meta.Match /-- Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and `_` in patterns. -/ def mkInaccessible (e : Expr) : Expr := mkAnnotation `_inaccessible e def inaccessible? (e : Expr) : Option Expr := annotation? `_inaccessible e inductive Pattern : Type where | inaccessible (e : Expr) : Pattern | var (fvarId : FVarId) : Pattern | ctor (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern | val (e : Expr) : Pattern | arrayLit (type : Expr) (xs : List Pattern) : Pattern | as (varId : FVarId) (p : Pattern) : Pattern deriving Inhabited namespace Pattern partial def toMessageData : Pattern β†’ MessageData | inaccessible e => m!".({e})" | var varId => mkFVar varId | ctor ctorName _ _ [] => ctorName | ctor ctorName _ _ pats => m!"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil})" | val e => e | arrayLit _ pats => m!"#[{MessageData.joinSep (pats.map toMessageData) ", "}]" | as varId p => m!"{mkFVar varId}@{toMessageData p}" partial def toExpr (p : Pattern) (annotate := false) : MetaM Expr := visit p where visit (p : Pattern) := do match p with | inaccessible e => if annotate then pure (mkInaccessible e) else pure e | var fvarId => pure $ mkFVar fvarId | val e => pure e | as fvarId p => if annotate then mkAppM `namedPattern #[mkFVar fvarId, (← visit p)] else visit p | arrayLit type xs => let xs ← xs.mapM visit mkArrayLit type xs | ctor ctorName us params fields => let fields ← fields.mapM visit pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray /- Apply the free variable substitution `s` to the given pattern -/ partial def applyFVarSubst (s : FVarSubst) : Pattern β†’ Pattern | inaccessible e => inaccessible $ s.apply e | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s) | val e => val $ s.apply e | arrayLit t xs => arrayLit (s.apply t) $ xs.map (applyFVarSubst s) | var fvarId => match s.find? fvarId with | some e => inaccessible e | none => var fvarId | as fvarId p => match s.find? fvarId with | none => as fvarId $ applyFVarSubst s p | some _ => applyFVarSubst s p def replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern := let s : FVarSubst := {} p.applyFVarSubst (s.insert fvarId v) partial def hasExprMVar : Pattern β†’ Bool | inaccessible e => e.hasExprMVar | ctor _ _ ps fs => ps.any (Β·.hasExprMVar) || fs.any hasExprMVar | val e => e.hasExprMVar | as _ p => hasExprMVar p | arrayLit t xs => t.hasExprMVar || xs.any hasExprMVar | _ => false end Pattern partial def instantiatePatternMVars : Pattern β†’ MetaM Pattern | Pattern.inaccessible e => return Pattern.inaccessible (← instantiateMVars e) | Pattern.val e => return Pattern.val (← instantiateMVars e) | Pattern.ctor n us ps fields => return Pattern.ctor n us (← ps.mapM instantiateMVars) (← fields.mapM instantiatePatternMVars) | Pattern.as x p => return Pattern.as x (← instantiatePatternMVars p) | Pattern.arrayLit t xs => return Pattern.arrayLit (← instantiateMVars t) (← xs.mapM instantiatePatternMVars) | p => return p structure AltLHS where ref : Syntax fvarDecls : List LocalDecl -- Free variables used in the patterns. patterns : List Pattern -- We use `List Pattern` since we have nary match-expressions. def instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS := return { altLHS with fvarDecls := (← altLHS.fvarDecls.mapM instantiateLocalDeclMVars), patterns := (← altLHS.patterns.mapM instantiatePatternMVars) } structure Alt where ref : Syntax idx : Nat -- for generating error messages rhs : Expr fvarDecls : List LocalDecl patterns : List Pattern deriving Inhabited namespace Alt partial def toMessageData (alt : Alt) : MetaM MessageData := do withExistingLocalDecls alt.fvarDecls do let msg : List MessageData := alt.fvarDecls.map fun d => m!"{d.toExpr}:({d.type})" let msg : MessageData := m!"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}" addMessageContext msg def applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.applyFVarSubst s, fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s, rhs := alt.rhs.applyFVarSubst s } def replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.replaceFVarId fvarId v, fvarDecls := let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId decls.map $ replaceFVarIdAtLocalDecl fvarId v, rhs := alt.rhs.replaceFVarId fvarId v } /- Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`. This extra check is necessary when performing dependent elimination and inaccessible terms have been used. For example, consider the following code fragment: ``` inductive Vec (Ξ± : Type u) : Nat β†’ Type u where | nil : Vec Ξ± 0 | cons {n} (head : Ξ±) (tail : Vec Ξ± n) : Vec Ξ± (n+1) inductive VecPred {Ξ± : Type u} (P : Ξ± β†’ Prop) : {n : Nat} β†’ Vec Ξ± n β†’ Prop where | nil : VecPred P Vec.nil | cons {n : Nat} {head : Ξ±} {tail : Vec Ξ± n} : P head β†’ VecPred P tail β†’ VecPred P (Vec.cons head tail) theorem ex {Ξ± : Type u} (P : Ξ± β†’ Prop) : {n : Nat} β†’ (v : Vec Ξ± (n+1)) β†’ VecPred P v β†’ Exists P | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` Recall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term. The elaborator uses an inaccessible term when typing constraints restrict its value. Thus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)` because the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`. After elaboration the alternative becomes: ``` | .(0), @Vec.cons .(Ξ±) .(0) head .(Vec.nil), @VecPred.cons .(Ξ±) .(P) .(0) .(head) .(Vec.nil) h w => ⟨head, h⟩ ``` where ``` (head : Ξ±), (h: P head), (w : VecPred P Vec.nil) ``` Then, when we process this alternative in this module, the following check will detect that `w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`. Note that if we had written ``` theorem ex {Ξ± : Type u} (P : Ξ± β†’ Prop) : {n : Nat} β†’ (v : Vec Ξ± (n+1)) β†’ VecPred P v β†’ Exists P | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` we would get the easier to digest error message ``` missing cases: _, (Vec.cons _ _ (Vec.cons _ _ _)), _ ``` -/ def checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with | none => throwErrorAt alt.ref "unknown free pattern variable" | some fvarDecl => do let vType ← inferType v unless (← isDefEqGuarded fvarDecl.type vType) do withExistingLocalDecls alt.fvarDecls do let (expectedType, givenType) ← addPPExplicitToExposeDiff vType fvarDecl.type throwErrorAt alt.ref "type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\nexpected type{indentExpr expectedType}" pure $ replaceFVarId fvarId v alt end Alt inductive Example where | var : FVarId β†’ Example | underscore : Example | ctor : Name β†’ List Example β†’ Example | val : Expr β†’ Example | arrayLit : List Example β†’ Example namespace Example partial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example β†’ Example | var x => if x == fvarId then ex else var x | ctor n exs => ctor n $ exs.map (replaceFVarId fvarId ex) | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex) | ex => ex partial def applyFVarSubst (s : FVarSubst) : Example β†’ Example | var fvarId => match s.get fvarId with | Expr.fvar fvarId' _ => var fvarId' | _ => underscore | ctor n exs => ctor n $ exs.map (applyFVarSubst s) | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s) | ex => ex partial def varsToUnderscore : Example β†’ Example | var x => underscore | ctor n exs => ctor n $ exs.map varsToUnderscore | arrayLit exs => arrayLit $ exs.map varsToUnderscore | ex => ex partial def toMessageData : Example β†’ MessageData | var fvarId => mkFVar fvarId | ctor ctorName [] => mkConst ctorName | ctor ctorName exs => m!"({mkConst ctorName}{exs.foldl (fun msg pat => m!"{msg} {toMessageData pat}") Format.nil})" | arrayLit exs => "#" ++ MessageData.ofList (exs.map toMessageData) | val e => e | underscore => "_" end Example def examplesToMessageData (cex : List Example) : MessageData := MessageData.joinSep (cex.map (Example.toMessageData ∘ Example.varsToUnderscore)) ", " structure Problem where mvarId : MVarId vars : List Expr alts : List Alt examples : List Example deriving Inhabited def withGoalOf {Ξ±} (p : Problem) (x : MetaM Ξ±) : MetaM Ξ± := withMVarContext p.mvarId x def Problem.toMessageData (p : Problem) : MetaM MessageData := withGoalOf p do let alts ← p.alts.mapM Alt.toMessageData let vars ← p.vars.mapM fun x => do let xType ← inferType x; pure m!"{x}:({xType})" return m!"remaining variables: {vars}\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\nexamples:{examplesToMessageData p.examples}\n" abbrev CounterExample := List Example def counterExampleToMessageData (cex : CounterExample) : MessageData := examplesToMessageData cex def counterExamplesToMessageData (cexs : List CounterExample) : MessageData := MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line structure MatcherResult where matcher : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables. counterExamples : List CounterExample unusedAltIdxs : List Nat /-- Convert a expression occurring as the argument of a `match` motive application back into a `Pattern` For example, we can use this method to convert `x::y::xs` at ``` ... (motive : List Nat β†’ Sort u_1) (xs : List Nat) (h_1 : (x y : Nat) β†’ (xs : List Nat) β†’ motive (x :: y :: xs)) ... ``` into a pattern object -/ partial def toPattern (e : Expr) : MetaM Pattern := do match inaccessible? e with | some t => return Pattern.inaccessible t | none => match e.arrayLit? with | some (Ξ±, lits) => return Pattern.arrayLit Ξ± (← lits.mapM toPattern) | none => if e.isAppOfArity `namedPattern 3 then let p ← toPattern <| e.getArg! 2 match e.getArg! 1 with | Expr.fvar fvarId _ => return Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then return Pattern.val e else if e.isFVar then return Pattern.var e.fvarId! else let newE ← whnf e if newE != e then toPattern newE else matchConstCtor e.getAppFn (fun _ => throwError "unexpected pattern{indentExpr e}") fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwError "unexpected pattern{indentExpr e}" let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM toPattern return Pattern.ctor v.name us params.toList fields.toList end Lean.Meta.Match
56ce57a9cfdc971f28b4abf113f6db74250c186c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/sets/compacts.lean
8dc271235107ee3d88961980e2d791def5172648
[ "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
16,969
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, YaΓ«l Dillies -/ import topology.sets.closeds import topology.quasi_separated /-! # Compact sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define a few types of compact sets in a topological space. ## Main Definitions For a topological space `Ξ±`, * `compacts Ξ±`: The type of compact sets. * `nonempty_compacts Ξ±`: The type of non-empty compact sets. * `positive_compacts Ξ±`: The type of compact sets with non-empty interior. * `compact_opens Ξ±`: The type of compact open sets. This is a central object in the study of spectral spaces. -/ open set variables {Ξ± Ξ² Ξ³ : Type*} [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] namespace topological_space /-! ### Compact sets -/ /-- The type of compact sets of a topological space. -/ structure compacts (Ξ± : Type*) [topological_space Ξ±] := (carrier : set Ξ±) (is_compact' : is_compact carrier) namespace compacts variables {Ξ±} instance : set_like (compacts Ξ±) Ξ± := { coe := compacts.carrier, coe_injective' := Ξ» s t h, by { cases s, cases t, congr' } } protected lemma is_compact (s : compacts Ξ±) : is_compact (s : set Ξ±) := s.is_compact' instance (K : compacts Ξ±) : compact_space K := is_compact_iff_compact_space.1 K.is_compact instance : can_lift (set Ξ±) (compacts Ξ±) coe is_compact := { prf := Ξ» K hK, ⟨⟨K, hK⟩, rfl⟩ } @[ext] protected lemma ext {s t : compacts Ξ±} (h : (s : set Ξ±) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : set Ξ±) (h) : (mk s h : set Ξ±) = s := rfl @[simp] lemma carrier_eq_coe (s : compacts Ξ±) : s.carrier = s := rfl instance : has_sup (compacts Ξ±) := ⟨λ s t, ⟨s βˆͺ t, s.is_compact.union t.is_compact⟩⟩ instance [t2_space Ξ±] : has_inf (compacts Ξ±) := ⟨λ s t, ⟨s ∩ t, s.is_compact.inter t.is_compact⟩⟩ instance [compact_space Ξ±] : has_top (compacts Ξ±) := ⟨⟨univ, is_compact_univ⟩⟩ instance : has_bot (compacts Ξ±) := βŸ¨βŸ¨βˆ…, is_compact_empty⟩⟩ instance : semilattice_sup (compacts Ξ±) := set_like.coe_injective.semilattice_sup _ (Ξ» _ _, rfl) instance [t2_space Ξ±] : distrib_lattice (compacts Ξ±) := set_like.coe_injective.distrib_lattice _ (Ξ» _ _, rfl) (Ξ» _ _, rfl) instance : order_bot (compacts Ξ±) := order_bot.lift (coe : _ β†’ set Ξ±) (Ξ» _ _, id) rfl instance [compact_space Ξ±] : bounded_order (compacts Ξ±) := bounded_order.lift (coe : _ β†’ set Ξ±) (Ξ» _ _, id) rfl rfl /-- The type of compact sets is inhabited, with default element the empty set. -/ instance : inhabited (compacts Ξ±) := ⟨βŠ₯⟩ @[simp] lemma coe_sup (s t : compacts Ξ±) : (↑(s βŠ” t) : set Ξ±) = s βˆͺ t := rfl @[simp] lemma coe_inf [t2_space Ξ±] (s t : compacts Ξ±) : (↑(s βŠ“ t) : set Ξ±) = s ∩ t := rfl @[simp] lemma coe_top [compact_space Ξ±] : (↑(⊀ : compacts Ξ±) : set Ξ±) = univ := rfl @[simp] lemma coe_bot : (↑(βŠ₯ : compacts Ξ±) : set Ξ±) = βˆ… := rfl @[simp] lemma coe_finset_sup {ΞΉ : Type*} {s : finset ΞΉ} {f : ΞΉ β†’ compacts Ξ±} : (↑(s.sup f) : set Ξ±) = s.sup (Ξ» i, f i) := begin classical, refine finset.induction_on s rfl (Ξ» a s _ h, _), simp_rw [finset.sup_insert, coe_sup, sup_eq_union], congr', end /-- The image of a compact set under a continuous function. -/ protected def map (f : Ξ± β†’ Ξ²) (hf : continuous f) (K : compacts Ξ±) : compacts Ξ² := ⟨f '' K.1, K.2.image hf⟩ @[simp, norm_cast] lemma coe_map {f : Ξ± β†’ Ξ²} (hf : continuous f) (s : compacts Ξ±) : (s.map f hf : set Ξ²) = f '' s := rfl @[simp] lemma map_id (K : compacts Ξ±) : K.map id continuous_id = K := compacts.ext $ set.image_id _ lemma map_comp (f : Ξ² β†’ Ξ³) (g : Ξ± β†’ Ξ²) (hf : continuous f) (hg : continuous g) (K : compacts Ξ±) : K.map (f ∘ g) (hf.comp hg) = (K.map g hg).map f hf := compacts.ext $ set.image_comp _ _ _ /-- A homeomorphism induces an equivalence on compact sets, by taking the image. -/ @[simps] protected def equiv (f : Ξ± β‰ƒβ‚œ Ξ²) : compacts Ξ± ≃ compacts Ξ² := { to_fun := compacts.map f f.continuous, inv_fun := compacts.map _ f.symm.continuous, left_inv := Ξ» s, by { ext1, simp only [coe_map, ← image_comp, f.symm_comp_self, image_id] }, right_inv := Ξ» s, by { ext1, simp only [coe_map, ← image_comp, f.self_comp_symm, image_id] } } @[simp] lemma equiv_refl : compacts.equiv (homeomorph.refl Ξ±) = equiv.refl _ := equiv.ext map_id @[simp] lemma equiv_trans (f : Ξ± β‰ƒβ‚œ Ξ²) (g : Ξ² β‰ƒβ‚œ Ξ³) : compacts.equiv (f.trans g) = (compacts.equiv f).trans (compacts.equiv g) := equiv.ext $ map_comp _ _ _ _ @[simp] lemma equiv_symm (f : Ξ± β‰ƒβ‚œ Ξ²) : compacts.equiv f.symm = (compacts.equiv f).symm := rfl /-- The image of a compact set under a homeomorphism can also be expressed as a preimage. -/ lemma coe_equiv_apply_eq_preimage (f : Ξ± β‰ƒβ‚œ Ξ²) (K : compacts Ξ±) : (compacts.equiv f K : set Ξ²) = f.symm ⁻¹' (K : set Ξ±) := f.to_equiv.image_eq_preimage K /-- The product of two `compacts`, as a `compacts` in the product space. -/ protected def prod (K : compacts Ξ±) (L : compacts Ξ²) : compacts (Ξ± Γ— Ξ²) := { carrier := K Γ—Λ’ L, is_compact' := is_compact.prod K.2 L.2 } @[simp] lemma coe_prod (K : compacts Ξ±) (L : compacts Ξ²) : (K.prod L : set (Ξ± Γ— Ξ²)) = K Γ—Λ’ L := rfl end compacts /-! ### Nonempty compact sets -/ /-- The type of nonempty compact sets of a topological space. -/ structure nonempty_compacts (Ξ± : Type*) [topological_space Ξ±] extends compacts Ξ± := (nonempty' : carrier.nonempty) namespace nonempty_compacts instance : set_like (nonempty_compacts Ξ±) Ξ± := { coe := Ξ» s, s.carrier, coe_injective' := Ξ» s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } } protected lemma is_compact (s : nonempty_compacts Ξ±) : is_compact (s : set Ξ±) := s.is_compact' protected lemma nonempty (s : nonempty_compacts Ξ±) : (s : set Ξ±).nonempty := s.nonempty' /-- Reinterpret a nonempty compact as a closed set. -/ def to_closeds [t2_space Ξ±] (s : nonempty_compacts Ξ±) : closeds Ξ± := ⟨s, s.is_compact.is_closed⟩ @[ext] protected lemma ext {s t : nonempty_compacts Ξ±} (h : (s : set Ξ±) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : compacts Ξ±) (h) : (mk s h : set Ξ±) = s := rfl @[simp] lemma carrier_eq_coe (s : nonempty_compacts Ξ±) : s.carrier = s := rfl instance : has_sup (nonempty_compacts Ξ±) := ⟨λ s t, ⟨s.to_compacts βŠ” t.to_compacts, s.nonempty.mono $ subset_union_left _ _⟩⟩ instance [compact_space Ξ±] [nonempty Ξ±] : has_top (nonempty_compacts Ξ±) := ⟨⟨⊀, univ_nonempty⟩⟩ instance : semilattice_sup (nonempty_compacts Ξ±) := set_like.coe_injective.semilattice_sup _ (Ξ» _ _, rfl) instance [compact_space Ξ±] [nonempty Ξ±] : order_top (nonempty_compacts Ξ±) := order_top.lift (coe : _ β†’ set Ξ±) (Ξ» _ _, id) rfl @[simp] lemma coe_sup (s t : nonempty_compacts Ξ±) : (↑(s βŠ” t) : set Ξ±) = s βˆͺ t := rfl @[simp] lemma coe_top [compact_space Ξ±] [nonempty Ξ±] : (↑(⊀ : nonempty_compacts Ξ±) : set Ξ±) = univ := rfl /-- In an inhabited space, the type of nonempty compact subsets is also inhabited, with default element the singleton set containing the default element. -/ instance [inhabited Ξ±] : inhabited (nonempty_compacts Ξ±) := ⟨{ carrier := {default}, is_compact' := is_compact_singleton, nonempty' := singleton_nonempty _ }⟩ instance to_compact_space {s : nonempty_compacts Ξ±} : compact_space s := is_compact_iff_compact_space.1 s.is_compact instance to_nonempty {s : nonempty_compacts Ξ±} : nonempty s := s.nonempty.to_subtype /-- The product of two `nonempty_compacts`, as a `nonempty_compacts` in the product space. -/ protected def prod (K : nonempty_compacts Ξ±) (L : nonempty_compacts Ξ²) : nonempty_compacts (Ξ± Γ— Ξ²) := { nonempty' := K.nonempty.prod L.nonempty, .. K.to_compacts.prod L.to_compacts } @[simp] lemma coe_prod (K : nonempty_compacts Ξ±) (L : nonempty_compacts Ξ²) : (K.prod L : set (Ξ± Γ— Ξ²)) = K Γ—Λ’ L := rfl end nonempty_compacts /-! ### Positive compact sets -/ /-- The type of compact sets with nonempty interior of a topological space. See also `compacts` and `nonempty_compacts`. -/ structure positive_compacts (Ξ± : Type*) [topological_space Ξ±] extends compacts Ξ± := (interior_nonempty' : (interior carrier).nonempty) namespace positive_compacts instance : set_like (positive_compacts Ξ±) Ξ± := { coe := Ξ» s, s.carrier, coe_injective' := Ξ» s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } } protected lemma is_compact (s : positive_compacts Ξ±) : is_compact (s : set Ξ±) := s.is_compact' lemma interior_nonempty (s : positive_compacts Ξ±) : (interior (s : set Ξ±)).nonempty := s.interior_nonempty' protected lemma nonempty (s : positive_compacts Ξ±) : (s : set Ξ±).nonempty := s.interior_nonempty.mono interior_subset /-- Reinterpret a positive compact as a nonempty compact. -/ def to_nonempty_compacts (s : positive_compacts Ξ±) : nonempty_compacts Ξ± := ⟨s.to_compacts, s.nonempty⟩ @[ext] protected lemma ext {s t : positive_compacts Ξ±} (h : (s : set Ξ±) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : compacts Ξ±) (h) : (mk s h : set Ξ±) = s := rfl @[simp] lemma carrier_eq_coe (s : positive_compacts Ξ±) : s.carrier = s := rfl instance : has_sup (positive_compacts Ξ±) := ⟨λ s t, ⟨s.to_compacts βŠ” t.to_compacts, s.interior_nonempty.mono $ interior_mono $ subset_union_left _ _⟩⟩ instance [compact_space Ξ±] [nonempty Ξ±] : has_top (positive_compacts Ξ±) := ⟨⟨⊀, interior_univ.symm.subst univ_nonempty⟩⟩ instance : semilattice_sup (positive_compacts Ξ±) := set_like.coe_injective.semilattice_sup _ (Ξ» _ _, rfl) instance [compact_space Ξ±] [nonempty Ξ±] : order_top (positive_compacts Ξ±) := order_top.lift (coe : _ β†’ set Ξ±) (Ξ» _ _, id) rfl @[simp] lemma coe_sup (s t : positive_compacts Ξ±) : (↑(s βŠ” t) : set Ξ±) = s βˆͺ t := rfl @[simp] lemma coe_top [compact_space Ξ±] [nonempty Ξ±] : (↑(⊀ : positive_compacts Ξ±) : set Ξ±) = univ := rfl /-- The image of a positive compact set under a continuous open map. -/ protected def map (f : Ξ± β†’ Ξ²) (hf : continuous f) (hf' : is_open_map f) (K : positive_compacts Ξ±) : positive_compacts Ξ² := { interior_nonempty' := (K.interior_nonempty'.image _).mono (hf'.image_interior_subset K.to_compacts), ..K.map f hf } @[simp, norm_cast] lemma coe_map {f : Ξ± β†’ Ξ²} (hf : continuous f) (hf' : is_open_map f) (s : positive_compacts Ξ±) : (s.map f hf hf' : set Ξ²) = f '' s := rfl @[simp] lemma map_id (K : positive_compacts Ξ±) : K.map id continuous_id is_open_map.id = K := positive_compacts.ext $ set.image_id _ lemma map_comp (f : Ξ² β†’ Ξ³) (g : Ξ± β†’ Ξ²) (hf : continuous f) (hg : continuous g) (hf' : is_open_map f) (hg' : is_open_map g) (K : positive_compacts Ξ±) : K.map (f ∘ g) (hf.comp hg) (hf'.comp hg') = (K.map g hg hg').map f hf hf' := positive_compacts.ext $ set.image_comp _ _ _ lemma _root_.exists_positive_compacts_subset [locally_compact_space Ξ±] {U : set Ξ±} (ho : is_open U) (hn : U.nonempty) : βˆƒ K : positive_compacts Ξ±, ↑K βŠ† U := let ⟨x, hx⟩ := hn, ⟨K, hKc, hxK, hKU⟩ := exists_compact_subset ho hx in ⟨⟨⟨K, hKc⟩, ⟨x, hxK⟩⟩, hKU⟩ instance [compact_space Ξ±] [nonempty Ξ±] : inhabited (positive_compacts Ξ±) := ⟨⊀⟩ /-- In a nonempty locally compact space, there exists a compact set with nonempty interior. -/ instance nonempty' [locally_compact_space Ξ±] [nonempty Ξ±] : nonempty (positive_compacts Ξ±) := nonempty_of_exists $ exists_positive_compacts_subset is_open_univ univ_nonempty /-- The product of two `positive_compacts`, as a `positive_compacts` in the product space. -/ protected def prod (K : positive_compacts Ξ±) (L : positive_compacts Ξ²) : positive_compacts (Ξ± Γ— Ξ²) := { interior_nonempty' := begin simp only [compacts.carrier_eq_coe, compacts.coe_prod, interior_prod_eq], exact K.interior_nonempty.prod L.interior_nonempty, end, .. K.to_compacts.prod L.to_compacts } @[simp] lemma coe_prod (K : positive_compacts Ξ±) (L : positive_compacts Ξ²) : (K.prod L : set (Ξ± Γ— Ξ²)) = K Γ—Λ’ L := rfl end positive_compacts /-! ### Compact open sets -/ /-- The type of compact open sets of a topological space. This is useful in non Hausdorff contexts, in particular spectral spaces. -/ structure compact_opens (Ξ± : Type*) [topological_space Ξ±] extends compacts Ξ± := (is_open' : is_open carrier) namespace compact_opens instance : set_like (compact_opens Ξ±) Ξ± := { coe := Ξ» s, s.carrier, coe_injective' := Ξ» s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } } protected lemma is_compact (s : compact_opens Ξ±) : is_compact (s : set Ξ±) := s.is_compact' protected lemma is_open (s : compact_opens Ξ±) : is_open (s : set Ξ±) := s.is_open' /-- Reinterpret a compact open as an open. -/ @[simps] def to_opens (s : compact_opens Ξ±) : opens Ξ± := ⟨s, s.is_open⟩ /-- Reinterpret a compact open as a clopen. -/ @[simps] def to_clopens [t2_space Ξ±] (s : compact_opens Ξ±) : clopens Ξ± := ⟨s, s.is_open, s.is_compact.is_closed⟩ @[ext] protected lemma ext {s t : compact_opens Ξ±} (h : (s : set Ξ±) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : compacts Ξ±) (h) : (mk s h : set Ξ±) = s := rfl instance : has_sup (compact_opens Ξ±) := ⟨λ s t, ⟨s.to_compacts βŠ” t.to_compacts, s.is_open.union t.is_open⟩⟩ instance [quasi_separated_space Ξ±] : has_inf (compact_opens Ξ±) := ⟨λ U V, ⟨⟨(U : set Ξ±) ∩ (V : set Ξ±), quasi_separated_space.inter_is_compact U.1.1 V.1.1 U.2 U.1.2 V.2 V.1.2⟩, U.2.inter V.2⟩⟩ instance [quasi_separated_space Ξ±] : semilattice_inf (compact_opens Ξ±) := set_like.coe_injective.semilattice_inf _ (Ξ» _ _, rfl) instance [compact_space Ξ±] : has_top (compact_opens Ξ±) := ⟨⟨⊀, is_open_univ⟩⟩ instance : has_bot (compact_opens Ξ±) := ⟨⟨βŠ₯, is_open_empty⟩⟩ instance [t2_space Ξ±] : has_sdiff (compact_opens Ξ±) := ⟨λ s t, ⟨⟨s \ t, s.is_compact.diff t.is_open⟩, s.is_open.sdiff t.is_compact.is_closed⟩⟩ instance [t2_space Ξ±] [compact_space Ξ±] : has_compl (compact_opens Ξ±) := ⟨λ s, ⟨⟨sᢜ, s.is_open.is_closed_compl.is_compact⟩, s.is_compact.is_closed.is_open_compl⟩⟩ instance : semilattice_sup (compact_opens Ξ±) := set_like.coe_injective.semilattice_sup _ (Ξ» _ _, rfl) instance : order_bot (compact_opens Ξ±) := order_bot.lift (coe : _ β†’ set Ξ±) (Ξ» _ _, id) rfl instance [t2_space Ξ±] : generalized_boolean_algebra (compact_opens Ξ±) := set_like.coe_injective.generalized_boolean_algebra _ (Ξ» _ _, rfl) (Ξ» _ _, rfl) rfl (Ξ» _ _, rfl) instance [compact_space Ξ±] : bounded_order (compact_opens Ξ±) := bounded_order.lift (coe : _ β†’ set Ξ±) (Ξ» _ _, id) rfl rfl instance [t2_space Ξ±] [compact_space Ξ±] : boolean_algebra (compact_opens Ξ±) := set_like.coe_injective.boolean_algebra _ (Ξ» _ _, rfl) (Ξ» _ _, rfl) rfl rfl (Ξ» _, rfl) (Ξ» _ _, rfl) @[simp] lemma coe_sup (s t : compact_opens Ξ±) : (↑(s βŠ” t) : set Ξ±) = s βˆͺ t := rfl @[simp] lemma coe_inf [t2_space Ξ±] (s t : compact_opens Ξ±) : (↑(s βŠ“ t) : set Ξ±) = s ∩ t := rfl @[simp] lemma coe_top [compact_space Ξ±] : (↑(⊀ : compact_opens Ξ±) : set Ξ±) = univ := rfl @[simp] lemma coe_bot : (↑(βŠ₯ : compact_opens Ξ±) : set Ξ±) = βˆ… := rfl @[simp] lemma coe_sdiff [t2_space Ξ±] (s t : compact_opens Ξ±) : (↑(s \ t) : set Ξ±) = s \ t := rfl @[simp] lemma coe_compl [t2_space Ξ±] [compact_space Ξ±] (s : compact_opens Ξ±) : (↑sᢜ : set Ξ±) = sᢜ := rfl instance : inhabited (compact_opens Ξ±) := ⟨βŠ₯⟩ /-- The image of a compact open under a continuous open map. -/ @[simps] def map (f : Ξ± β†’ Ξ²) (hf : continuous f) (hf' : is_open_map f) (s : compact_opens Ξ±) : compact_opens Ξ² := ⟨s.to_compacts.map f hf, hf' _ s.is_open⟩ @[simp, norm_cast] lemma coe_map {f : Ξ± β†’ Ξ²} (hf : continuous f) (hf' : is_open_map f) (s : compact_opens Ξ±) : (s.map f hf hf' : set Ξ²) = f '' s := rfl @[simp] lemma map_id (K : compact_opens Ξ±) : K.map id continuous_id is_open_map.id = K := compact_opens.ext $ set.image_id _ lemma map_comp (f : Ξ² β†’ Ξ³) (g : Ξ± β†’ Ξ²) (hf : continuous f) (hg : continuous g) (hf' : is_open_map f) (hg' : is_open_map g) (K : compact_opens Ξ±) : K.map (f ∘ g) (hf.comp hg) (hf'.comp hg') = (K.map g hg hg').map f hf hf' := compact_opens.ext $ set.image_comp _ _ _ /-- The product of two `compact_opens`, as a `compact_opens` in the product space. -/ protected def prod (K : compact_opens Ξ±) (L : compact_opens Ξ²) : compact_opens (Ξ± Γ— Ξ²) := { is_open' := K.is_open.prod L.is_open, .. K.to_compacts.prod L.to_compacts } @[simp] lemma coe_prod (K : compact_opens Ξ±) (L : compact_opens Ξ²) : (K.prod L : set (Ξ± Γ— Ξ²)) = K Γ—Λ’ L := rfl end compact_opens end topological_space
7cbada1898f4bd8267ea0c92e91f67078c435b89
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/addDecorationsWithoutPartial.lean
73fa0aa51263c3313924f8b80c90e3d1db9ea4dd
[ "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
3,331
lean
import Lean namespace Lean namespace Expr namespace ReplaceImpl' abbrev cacheSize : USize := 8192 structure State where keys : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr results : Array Expr abbrev ReplaceM := StateM State unsafe def cache (i : USize) (key : Expr) (result : Expr) : ReplaceM Expr := do modify fun ⟨keys, results⟩ => { keys := keys.uset i key lcProof, results := results.uset i result lcProof }; pure result unsafe def replaceUnsafeM (size : USize) (e : Expr) (f? : (e' : Expr) β†’ sizeOf e' ≀ sizeOf e β†’ Option Expr) : ReplaceM Expr := do let rec visit (e : Expr) := do let c ← get let h := ptrAddrUnsafe e let i := h % size if ptrAddrUnsafe (c.keys.uget i lcProof) == h then pure <| c.results.uget i lcProof else match f? e lcProof with | some eNew => cache i e eNew | none => match e with | Expr.forallE _ d b _ => cache i e <| e.updateForallE! (← visit d) (← visit b) | Expr.lam _ d b _ => cache i e <| e.updateLambdaE! (← visit d) (← visit b) | Expr.mdata _ b => cache i e <| e.updateMData! (← visit b) | Expr.letE _ t v b _ => cache i e <| e.updateLet! (← visit t) (← visit v) (← visit b) | Expr.app f a => cache i e <| e.updateApp! (← visit f) (← visit a) | Expr.proj _ _ b => cache i e <| e.updateProj! (← visit b) | e => pure e visit e unsafe def initCache : State := { keys := mkArray cacheSize.toNat (cast lcProof ()), -- `()` is not a valid `Expr` results := mkArray cacheSize.toNat default } unsafe def replaceUnsafe (e : Expr) (f? : (e' : Expr) β†’ sizeOf e' ≀ sizeOf e β†’ Option Expr) : Expr := (replaceUnsafeM cacheSize e f?).run' initCache end ReplaceImpl' local macro "dec " h:ident : term => `(by apply Nat.le_trans _ $h; simp_arith) @[implementedBy ReplaceImpl'.replaceUnsafe] def replace' (e0 : Expr) (f? : (e : Expr) β†’ sizeOf e ≀ sizeOf e0 β†’ Option Expr) : Expr := let rec go (e : Expr) (h : sizeOf e ≀ sizeOf e0) : Expr := match f? e h with | some eNew => eNew | none => match e with | Expr.forallE _ d b _ => let d := go d (dec h); let b := go b (dec h); e.updateForallE! d b | Expr.lam _ d b _ => let d := go d (dec h); let b := go b (dec h); e.updateLambdaE! d b | Expr.mdata _ b => let b := go b (dec h); e.updateMData! b | Expr.letE _ t v b _ => let t := go t (dec h); let v := go v (dec h); let b := go b (dec h); e.updateLet! t v b | Expr.app f a => let f := go f (dec h); let a := go a (dec h); e.updateApp! f a | Expr.proj _ _ b => let b := go b (dec h); e.updateProj! b | e => e go e0 (Nat.le_refl ..) end Expr end Lean open Lean def addDecorations (e : Expr) : Expr := e.replace' fun expr h => match expr with | Expr.forallE name type body data => let n := name.toString let newType := addDecorations type let newBody := addDecorations body let rest := Expr.forallE name newType newBody data some <| mkApp2 (mkConst `SlimCheck.NamedBinder) (mkStrLit n) rest | _ => none decreasing_by exact Nat.le_trans (by simp_arith) h
ac7f9a27611e1c525e1b86305d9b1b46f223197b
0f5090f82d527e0df5bf3adac9f9e2e1d81d71e2
/src/kenji/dedekind.lean
95c56d88b3c025f373ecef826a32ab68e8713aec
[]
no_license
apurvanakade/mc2020-lean-projects
36eb42c4baccc37183635c36f8e1b3afa4ec1230
02466225aa629ab1232043bcc0a053a099fdb939
refs/heads/master
1,688,791,717,534
1,597,874,092,000
1,597,874,092,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,796
lean
import ring_theory.fractional_ideal import ring_theory.discrete_valuation_ring import linear_algebra.basic import order.zorn universes u v variables (R : Type u) [comm_ring R] {A : Type v} [comm_ring A] variables (K : Type u) [field K] (R' : Type u) [integral_domain R'] variables [algebra R A] open function open_locale big_operators structure is_integrally_closed_in : Prop := (inj : injective (algebra_map R A)) (closed : βˆ€ (a : A), is_integral R a β†’ βˆƒ r : R, algebra_map R A r = a) def is_integrally_closed_domain : Prop := βˆ€ {r s : R}, s β‰  0 β†’ (βˆƒ (n : β„•) (f : β„• β†’ R) (hf : f 0 = 1), βˆ‘ ij in finset.nat.antidiagonal n, f ij.1 * r ^ ij.2 * s ^ ij.1 = 0) β†’ s ∣ r /-! Any nontrivial localization of an integral domain results in an integral domain. -/ theorem local_id_is_id [integral_domain R'] (S : submonoid R') (zero_non_mem : ((0 : R') βˆ‰ S)) {f : localization_map S (localization S)} : is_integral_domain (localization S) := begin fsplit, {--nontrivial localization (pair ne) use [f.to_fun 1, f.to_fun 0], contrapose! zero_non_mem, -- intro one_eq_zero, have h2 := (localization_map.eq_iff_exists f).1 zero_non_mem, cases h2 with c h2, convert c.property, simp at h2; simp [h2], }, { exact mul_comm }, {--bulk intros x y mul_eq_zero, cases f.surj' x with a akey, cases f.surj' y with b bkey, have h1 : x * (f.to_fun a.snd) * y * (f.to_fun b.snd) = 0, { rw [mul_assoc x, ← mul_comm y, ← mul_assoc, mul_eq_zero], simp }, rw [akey, mul_assoc, bkey, ← f.map_mul', ← f.map_zero'] at h1, rw f.eq_iff_exists' at h1, cases h1 with c h1, rw [zero_mul, mul_comm] at h1, have h2 := eq_zero_or_eq_zero_of_mul_eq_zero h1, cases h2 with c_eq_zero h2, { exfalso, rw ← c_eq_zero at zero_non_mem, exact zero_non_mem c.property }, replace h2 := eq_zero_or_eq_zero_of_mul_eq_zero h2, cases h2 with a_eq_zero b_eq_zero, { left, rw a_eq_zero at akey, exact localization_map.eq_zero_of_fst_eq_zero f akey rfl }, { right, rw b_eq_zero at bkey, exact localization_map.eq_zero_of_fst_eq_zero f bkey rfl }, }, end /-! The localization of an integral domain at a prime ideal is an integral domain. -/ lemma local_at_prime_of_id_is_id (P : ideal R') (hp_prime : P.is_prime) : integral_domain (localization.at_prime P) := begin have zero_non_mem : (0 : R') βˆ‰ P.prime_compl, { have := ideal.zero_mem P, simpa }, have h1 := local_id_is_id R' P.prime_compl zero_non_mem, exact is_integral_domain.to_integral_domain (localization.at_prime P) h1, exact localization.of (ideal.prime_compl P), end /- Chopping block: -- class discrete_valuation_ring [comm_ring R] : Prop := -- (int_domain : is_integral_domain(R)) -- (unique_nonzero_prime : βˆƒ Q : ideal R, -- Q β‰  βŠ₯ β†’ Q.is_prime β†’ (βˆ€ P : ideal R, P.is_prime β†’ P = βŠ₯ ∨ P = Q) -- ) -- (is_pir : is_principal_ideal_ring(R)) -/ /-! Def 1: integral domain, noetherian, integrally closed, nonzero prime ideals are maximal -/ class dedekind_id [integral_domain R] : Prop := (noetherian : is_noetherian_ring R) (int_closed : is_integrally_closed_domain R) (max_nonzero_primes : βˆ€ P β‰  (βŠ₯ : ideal R), P.is_prime β†’ P.is_maximal) /- Def 2: noetherian ring, localization at each nonzero prime ideals is a DVR. Something is a discrete valuation ring if it is an integral domain and is a PIR and has one non-zero maximal ideal. -/ class dedekind_dvr [integral_domain R'] : Prop := (noetherian : is_noetherian_ring R') (local_dvr_nonzero_prime : βˆ€ P β‰  (βŠ₯ : ideal R'), P.is_prime β†’ @discrete_valuation_ring (localization.at_prime P) (by apply local_at_prime_of_id_is_id)) /- Def 3: every nonzero fractional ideal is invertible. Fractional ideal: I = {r | rI βŠ† R} It is invertible if there exists a fractional ideal J such that IJ=R. -/ class dedekind_inv [integral_domain R'] (f : localization_map (non_zero_divisors R') $ localization (non_zero_divisors R')) : Prop := (inv_ideals : βˆ€ I : ring.fractional_ideal f, (βˆƒ t : I, t β‰  0) β†’ (βˆƒ J : ring.fractional_ideal f, I * J = 1)) lemma dedekind_id_imp_dedekind_dvr (W : Type u) [integral_domain W] [dedekind_id W] : dedekind_dvr W := begin refine {noetherian := dedekind_id.noetherian, local_dvr_nonzero_prime := _}, intros P hp_nonzero hp_prime, letI := hp_prime, have f := localization.of (ideal.prime_compl P), letI := local_at_prime_of_id_is_id W P hp_prime, rw discrete_valuation_ring.iff_PID_with_one_nonzero_prime (localization.at_prime P), split, swap, { have p' := local_ring.maximal_ideal (localization.at_prime P), have hp' := local_ring.maximal_ideal.is_maximal (localization.at_prime P), --use p' does not work repeat {sorry}, }, repeat {sorry}, end -- CR jstark for kenji: You don't want both of these to be instances, since that creates a loop in typeclass inference. -- I'd guess both of these just want to be lemmas lemma dedekind_dvr_imp_dedekind_inv [dedekind_dvr R'] (f : fraction_map R' $ localization (non_zero_divisors R')) : dedekind_inv R' f := begin sorry, end lemma dedekind_inv_imp_dedekind_id (f : fraction_map R' $ localization (non_zero_divisors R')) [dedekind_inv R' f] : dedekind_id R' := begin sorry, end lemma dedekind_id_imp_dedekind_inv [dedekind_id R'] (f : fraction_map R' $ localization (non_zero_divisors R')) : dedekind_inv R' f := by {letI := dedekind_id_imp_dedekind_dvr R', exact dedekind_dvr_imp_dedekind_inv R' f,} lemma dedekind_inv_imp_dedekind_dvr (f : fraction_map R' $ localization (non_zero_divisors R')) [dedekind_inv R' f] : dedekind_dvr R' := by {letI := dedekind_inv_imp_dedekind_id R', exact dedekind_id_imp_dedekind_dvr R',} lemma dedekind_dvr_imp_dedekind_id (f : fraction_map R' $ localization (non_zero_divisors R')) [dedekind_dvr R'] : dedekind_id R' := by {letI := dedekind_dvr_imp_dedekind_inv R', exact dedekind_inv_imp_dedekind_id R' f,} /- Time to break a lot of things ! probably morally correct: fractional ideals have prime factorization ! (β†’ regular ideals have prime factorization) -/ open_locale classical /- Currently mathlib has the following two characteristics of Noetherian modules (i) - Every ascending chain of ideals is eventually constant i.e. I_1 βŠ‚ I_2 βŠ‚ I_3 βŠ‚ … βŠ‚ I_n βŠ‚ I_{n+1} = I_n (ii) - Every ideal is finitely generated This is the third that mathlib does not have (pertaining to rings, perhaps to modules(?)): (iii) - Every non-empty set S of ideals has a maximal member. i.e. if M βŠ‚ I, then I = R ∨ I = M Proof of equivalence: by mathlib (i) ↔ (ii). (i β†’ iii) - This is just the statement of Zorn's lemma applied to the poset of elements of S ordered under inclusion. (iii β†’ ii) - Let I be an ideal. Take S to be the set of subideals of I which are finitely generated. Then the maximal element of S has to equal I. -/ --this is not in mathlib for some reason(???) lemma in_submodule_span_of_gen_set {X : Type u} [ring R'] [add_comm_group X] [module R' X] {s : set X} {x : X} (h : x ∈ s) : x ∈ (submodule.span R' s) := submodule.subset_span h -- rcases mfg with ⟨ Mgen , Mgenkey⟩, -- use ↑Mgen, split, { apply finset.finite_to_set }, -- convert Mgenkey, apply max, theorem set_has_maximal_iff_noetherian {X : Type u} [add_comm_group X] [module R' X] : (βˆ€(a : set $ submodule R' X), a.nonempty β†’ βˆƒ (M ∈ a), βˆ€ (I ∈ a), M ≀ I β†’ I=M) ↔ is_noetherian R' X := begin split; intro h, { split, intro I, let S := {J : submodule R' X | J ≀ I ∧ J.fg}, have h2 : S.nonempty, { use (βŠ₯ : submodule R' X), convert submodule.fg_bot, simp }, rcases h S h2 with ⟨ M, ⟨hMI, ⟨Mgen, hMgen⟩⟩, max⟩, rw submodule.fg_def, contrapose! max, have : βˆƒ x ∈ I, x βˆ‰ M, { have := max ↑Mgen (finset.finite_to_set Mgen), contrapose! this, rw hMgen, ext, tauto }, rcases this with ⟨x, hxI, hxM⟩, use submodule.span R' (↑Mgen βˆͺ {x}), split, { split, { suffices : (↑Mgen : set X) βˆͺ {x} βŠ† I, { convert submodule.span_mono this, simp }, have : (↑Mgen : set X) βŠ† M, { convert submodule.subset_span, cc }, apply set.union_subset, { exact set.subset.trans this hMI }, { simp [hxI] } }, { rw submodule.fg_def, use (↑Mgen βˆͺ {x}), split, { split, exact additive.fintype, }, refl } }, split, { rw ← hMgen, convert submodule.span_mono _, simp }, { contrapose! hxM, rw ← hxM, apply submodule.subset_span, exact (↑Mgen : set X).mem_union_right rfl, } }, { rintros A ⟨a, ha⟩, rw is_noetherian_iff_well_founded at h, rw rel_embedding.well_founded_iff_no_descending_seq at h, by_contra hyp, push_neg at hyp, apply h, constructor, have h' : βˆ€ (M : submodule R' X), M ∈ A β†’ (βˆƒ (I : submodule R' X), I ∈ A ∧ M < I), { intros m mina, rcases hyp m mina with ⟨I, iina, mlei, mneqi⟩, use I, split, exact iina, split, exact mlei, intro ilem, apply mneqi, exact le_antisymm ilem mlei, }, have h'' : βˆ€ M : A, βˆƒ I : A, (M : submodule R' X) < I, { rintros ⟨M, M_in⟩, rcases h' M M_in with ⟨I, I_in, hMI⟩, exact ⟨⟨I, I_in⟩, hMI⟩ }, let f : β„• β†’ A := Ξ» n, nat.rec_on n ⟨a, ha⟩ (Ξ» n M, classical.some (h'' M)), exact rel_embedding.nat_gt (coe ∘ f) (Ξ» n, classical.some_spec (h'' $ f n)), }, end lemma set_has_maximal [is_noetherian_ring R'] (a : set $ ideal R') (ha : a.nonempty): βˆƒ (M ∈ a), βˆ€ (I ∈ a), M ≀ I β†’ I = M := begin have : is_noetherian R' R' := by assumption, rw ← set_has_maximal_iff_noetherian at this, exact this _ ha, end --ring with id is most general(?) lemma lt_add_nonmem (I : ideal R') (a βˆ‰ I) : I < I+ideal.span{a} := begin have blah : βˆ€ (x y : ideal R'), x ≀ x βŠ” y, { intros x y, simp only [le_sup_left],}, split, exact blah I (ideal.span{a}), have blah2 : βˆ€ (x y z : ideal R'), x βŠ” y ≀ z β†’ x ≀ z β†’ y ≀ z, { intros x y z, simp only [sup_le_iff], tauto,}, have h : I ≀ I, exact le_refl I, rw ideal.add_eq_sup, intro bad, have h1 := blah2 I (ideal.span{a}) I bad h, have h2 : a ∈ ideal.span{a}, { rw ideal.mem_span_singleton', use 1, rw one_mul,}, have : βˆ€ (x ∈ ideal.span{a}), x ∈ I, simpa only [], exact H (this a h2), end lemma zero_prime [integral_domain R'] : (βŠ₯ : ideal R').is_prime := begin split, { intro, have h1 := (ideal.eq_top_iff_one) (βŠ₯ : ideal R'), rw h1 at a, have : 1 = (0 : R'), tauto, simpa, }, { intros, have h1 : x * y = 0, tauto, have x_or_y0 : x = 0 ∨ y = 0, exact zero_eq_mul.mp (eq.symm h1), tauto, }, end namespace dedekind /- Suppose not, then the set of ideals that do not contain a product of primes is nonempty, and by set_has_maximal must have a maximal element M. Since M is not prime, βˆƒ (r,s : R-M) such that rs ∈ M. Since r βˆ‰ M, M+(r) > M, and since M is maximal, M+(r) and M+(s) must be divisible by some prime. Now observe that (M+(r))(M+(s)) is divisible by some primes, but M*M βŠ‚ M, rM βŠ‚ M, sM βŠ‚ M, and rs βŠ‚ M, so this is contained in M, but this is a contradiction. -/ lemma ideal_contains_prime_product [dedekind_id R'] (I : ideal R') (gt_zero : βŠ₯ < I) : βˆƒ(plist : list $ ideal R'), plist.prod ≀ I ∧ (βˆ€(P ∈ plist), ideal.is_prime P ∧ βŠ₯ < P) := begin letI : is_noetherian_ring R', exact dedekind_id.noetherian, by_contra hyp, push_neg at hyp, let A := {J : ideal R' | βˆ€(qlist : list $ ideal R'), qlist.prod ≀ J β†’ (βˆƒ (P : ideal R'), P ∈ qlist ∧ (P.is_prime β†’ Β¬βŠ₯ < P))}, have key : A.nonempty, {use I, exact hyp,}, rcases set_has_maximal R' A key with ⟨ M, Mkey, maximal⟩, rw set.mem_set_of_eq at Mkey, by_cases M = βŠ₯, { have h1 := maximal I, have h2 : I ∈ A, simpa, rw h at h1, have h3 := h1 h2, have h4 : βŠ₯ ≀ I, {cases gt_zero, exact gt_zero_left,}, cases gt_zero, have := h3 h4, rw this at *, tauto, }, by_cases M.is_prime, { have : [M].prod ≀ M, rw list.prod_singleton, exact le_refl M, sorry, }, repeat{sorry}, end /- --what is this even trying to prove? chopping block 2.0 lemma ideal_contains_prime_product [dedekind_id R'] (I : ideal R') (gt_zero : βŠ₯ < I ) : βˆƒ (plist : list $ ideal R'), plist.prod ≀ I ∧ (βˆ€(P ∈ plist), ideal.is_prime P ∧ βŠ₯ < P ) := begin /- IMPORTANT NOTE: some things here work that work for the wrong reasons (read: ne_top) -/ letI : is_noetherian_ring R', exact dedekind_id.noetherian, by_contradiction hyp, push_neg at hyp, let A := {J : ideal R' | βˆ€(qlist : list $ ideal R'), qlist.prod ≀ J β†’ (βˆƒ(P ∈ qlist), ideal.is_prime(P) β†’ Β¬βŠ₯ < P)}, have key : A.nonempty, { use I, simpa only [exists_prop, set.mem_set_of_eq],}, rcases set_has_maximal R' A key with ⟨ M, Mkey, maximal⟩, rw set.mem_set_of_eq at Mkey, by_cases M = βŠ₯, { have h1 := maximal I, have h2 : I ∈ A, simpa, rw h at h1, have h3 := h1 h2, have h4 : βŠ₯ ≀ I, { cases gt_zero, exact gt_zero_left,}, cases gt_zero, have := h3 h4, rw this at *, tauto, }, have h1 : Β¬ M.is_prime, { by_contradiction, have h1 := Mkey [M], rw list.prod_singleton at h1, have : M ≀ M, exact le_refl M, rcases h1 this with ⟨ P, Pkey, hp ⟩, have blah: P = M, exact list.mem_singleton.mp Pkey, rw blah at hp, have hp' := hp a, clear' h1 Pkey this blah hp P, sorry, }, unfold ideal.is_prime at h1, push_neg at h1, have ne_top : M β‰  ⊀ , sorry, have h2 := h1 ne_top, rcases h2 with ⟨r,s,rs_in_m, r_nin_m, s_nin_m⟩, set ray := M + ideal.span({r}) with mr, have hmr : M < ray, { exact lt_add_nonmem R' M r r_nin_m,}, set say := M + ideal.span({s}) with ms, have hms : M < say, { exact lt_add_nonmem R' M s s_nin_m,}, clear r_nin_m s_nin_m ne_top, have main : ray*say ≀ M, {--bashing simplifications, I think this would be a very nice simp tactic rw [ms,mr,left_distrib,right_distrib,right_distrib,← add_assoc], repeat {rw [ideal.add_eq_sup]}, have blah : βˆ€ (x y z : ideal R'), x ≀ z β†’ y ≀ z β†’ x βŠ” y ≀ z, simp only [sup_le_iff], tauto, have part1 : M*M ≀ M, exact ideal.mul_le_left, have part2 : ideal.span{r} * M ≀ M, exact ideal.mul_le_left, have part3 : M*ideal.span{s} ≀ M, exact ideal.mul_le_right, have part4' : ideal.span {r} * ideal.span {s} = (ideal.span{r*s} : ideal R'), { unfold ideal.span, rw [submodule.span_mul_span, set.singleton_mul_singleton], }, rw part4', have part4 : ideal.span{r*s} ≀ M, { rw ideal.span_le, simpa,}, have h1 := blah (M*M) (ideal.span{r} * M βŠ” M * ideal.span {s} βŠ” ideal.span{r*s}) M part1, rw [←sup_assoc,← sup_assoc] at h1, apply h1, clear' h1 part1, have h1 := blah (ideal.span{r} * M) (M * ideal.span{s} βŠ” ideal.span{r*s}) M part2, rw [←sup_assoc] at h1, apply h1, clear' h1 part2, exact blah (M * ideal.span{s}) (ideal.span {r*s}) M part3 part4, }, have say_contains_prime : βˆƒ (P : ideal R'), P.is_prime ∧ say < P, {--sketch: since M < say and M is maximal of the set, say is not in A, and so has prime factor sorry, }, --there are too many variables that may or may not be needed.... rcases say_contains_prime with ⟨ P , P_prime , P_dvd⟩, --have h2 : P ∣ M, {sorry,}, --clear' P_dvd, --exact Mkey P P_prime h2, sorry, end -/ /- For any proper ideal I, there exists an element, Ξ³, in K (the field of fractions of R) such that Ξ³ I βŠ‚ R. Proof: This is really annoying. Pick some a ∈ I, then (a) contains a product of primes, and fix P_1, … such that P_1…P_r βŠ‚ (a), etc. broken, not sure how to state it. lemma frac_mul_ideal_contains_ring [dedekind_id R'] (I : ideal R') (h_nonzero : I β‰  βŠ₯) (h_nontop : I β‰  ⊀ ) : βˆƒ (Ξ³ : fraction_ring R'), Ξ³I βŠ‚ R := begin sorry, end -/ /- For any ideal I, there exists J such that IJ is principal. proof: Let 0 β‰  Ξ± ∈ I, and let J = { Ξ² ∈ R : Ξ² I βŠ‚ (Ξ± )}. We can see that J is an ideal. and we have that IJ βŠ‚ (Ξ±). Since IJ βŠ‚ (Ξ±), we have that A = IJ/Ξ± is an ideal of R. If A = R, then IJ = (Ξ±) and we are done, otherwise, A is a proper ideal, and we can use frac_mul_ideal_contains_ring to have a Ξ³ ∈ K-R such that Ξ³ A βŠ‚ R. Since R is integrally closed, it suffices to show that Ξ³ is a root of a monic polynomial over R. We have that J βŠ‚ A, as Ξ± ∈ I. so Ξ³ J βŠ‚ Ξ³ A βŠ‚ R. We make the observation that Ξ³ J βŠ‚ J. (rest is sketchy and annoying) Need to refine conditions (mainly non-zero). -/ lemma exists_ideal_prod_principal [dedekind_id R'](I : ideal R') : βˆƒ (J : ideal R'), (I * J).is_principal ∧ (J β‰  βŠ₯ ) := begin sorry, end --this seems true, should check! lemma ideal_mul_eq_zero [integral_domain R'] {I J : ideal R'} : (I * J = βŠ₯) ↔ I = βŠ₯ ∨ J = βŠ₯ := begin have hJ : inhabited J, by exact submodule.inhabited J, have j := inhabited.default J, clear hJ, split, swap, { intros, cases a, {rw [← ideal.mul_bot J, a, ideal.mul_comm],}, {rw [← ideal.mul_bot I, a, ideal.mul_comm],}, }, intro hij, by_cases J = βŠ₯, tauto, left, rw submodule.eq_bot_iff, intros i hi, rcases J.ne_bot_iff.1 h with ⟨ j', hj, ne0⟩, rw submodule.eq_bot_iff at hij, specialize hij (i * j'), have := eq_zero_or_eq_zero_of_mul_eq_zero ( hij (ideal.mul_mem_mul hi hj)), tauto, end --this is probably useless and cumbersome to use (if ever used) lemma prod_principal_eq_zero_iff_eq_zero [dedekind_id R'] (I : ideal R') (J : ideal R') (hj : (I*J).is_principal) (nonzero : (J β‰  βŠ₯ )) : (I * J) = βŠ₯ ↔ I = βŠ₯ := begin split, swap, {intro, rw a, simp,}, intro h, have h1 := (ideal_mul_eq_zero(R')).1 h, cases h1, exact h1, simpa only [], end lemma ddk_mul_right_inj [dedekind_id R'] (A B C : ideal R') (A β‰  βŠ₯ ) : A * B = A * C ↔ B=C := begin symmetry, split, {intro, rw a,}, rcases exists_ideal_prod_principal(R')(A) with ⟨ J ,Jkey, ne_bot⟩, intro ab_eq_ac, have : J * A * B = J * A * C, {rw [mul_assoc, ab_eq_ac,mul_assoc],}, rw mul_comm(J)(A) at this, sorry, end /- TODO: Refactor ddk_left_inj to be more like mul_left_inj -/ lemma ddk_left_inj [dedekind_id R'] (A B C : ideal R') ( C β‰  βŠ₯ ) : A * C = B * C ↔ A = B := begin rw [mul_comm(A), mul_comm(B)], have h1 := ddk_mul_right_inj R' C A B C H, --why does this require so many args? exact h1, end --This is currently dead wrong lemma ideal_prime_factorization [dedekind_id R'] (I : ideal R') : βˆƒ (pset : finset $ ideal R'), βˆƒ(powset : finset $ β„• ), (finset.card pset = finset.card powset) ∧ (βˆ€(P ∈ pset), ideal.is_prime(P)) ∧ false := begin sorry, end --every nonzero ideal has an element that's not 0 lemma nonzero_mem_of_neq_bot [integral_domain R'] (I : ideal R') (gt_bot : βŠ₯ < I) : βˆƒ a : I, a β‰  0 := begin have h := (submodule.lt_iff_le_and_exists.1 gt_bot).2, clear gt_bot, rcases h with ⟨ x, hx, key ⟩, use [x, hx], simp only [submodule.mem_bot] at key, simpa only [ne.def, submodule.mk_eq_zero], end --every ideal is generated by at most two elements of dedekind domain lemma two_generators [dedekind_id R'] (I : ideal R') : βˆƒ ( a b : R'), I = ideal.span {a,b} := begin by_cases βŠ₯ < I, tactic.swap, { have h1 : I = βŠ₯ , sorry, use (0 : R'), use (0 : R'), rw h1, simp, }, have h1 := nonzero_mem_of_neq_bot R' I h, cases h1 with a a_neq_zero, use a, sorry, end end dedekind
58d8b2b6a3be38c965756255e0d18292153c3018
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/PointedSteinerMagma.lean
3015f56749b19fb8da898af3b5f4c41c8e19e71f
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
7,332
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section PointedSteinerMagma structure PointedSteinerMagma (A : Type) : Type := (op : (A β†’ (A β†’ A))) (e : A) (commutative_op : (βˆ€ {x y : A} , (op x y) = (op y x))) (antiAbsorbent : (βˆ€ {x y : A} , (op x (op x y)) = y)) open PointedSteinerMagma structure Sig (AS : Type) : Type := (opS : (AS β†’ (AS β†’ AS))) (eS : AS) structure Product (A : Type) : Type := (opP : ((Prod A A) β†’ ((Prod A A) β†’ (Prod A A)))) (eP : (Prod A A)) (commutative_opP : (βˆ€ {xP yP : (Prod A A)} , (opP xP yP) = (opP yP xP))) (antiAbsorbentP : (βˆ€ {xP yP : (Prod A A)} , (opP xP (opP xP yP)) = yP)) structure Hom {A1 : Type} {A2 : Type} (Po1 : (PointedSteinerMagma A1)) (Po2 : (PointedSteinerMagma A2)) : Type := (hom : (A1 β†’ A2)) (pres_op : (βˆ€ {x1 x2 : A1} , (hom ((op Po1) x1 x2)) = ((op Po2) (hom x1) (hom x2)))) (pres_e : (hom (e Po1)) = (e Po2)) structure RelInterp {A1 : Type} {A2 : Type} (Po1 : (PointedSteinerMagma A1)) (Po2 : (PointedSteinerMagma A2)) : Type 1 := (interp : (A1 β†’ (A2 β†’ Type))) (interp_op : (βˆ€ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) β†’ ((interp x2 y2) β†’ (interp ((op Po1) x1 x2) ((op Po2) y1 y2)))))) (interp_e : (interp (e Po1) (e Po2))) inductive PointedSteinerMagmaTerm : Type | opL : (PointedSteinerMagmaTerm β†’ (PointedSteinerMagmaTerm β†’ PointedSteinerMagmaTerm)) | eL : PointedSteinerMagmaTerm open PointedSteinerMagmaTerm inductive ClPointedSteinerMagmaTerm (A : Type) : Type | sing : (A β†’ ClPointedSteinerMagmaTerm) | opCl : (ClPointedSteinerMagmaTerm β†’ (ClPointedSteinerMagmaTerm β†’ ClPointedSteinerMagmaTerm)) | eCl : ClPointedSteinerMagmaTerm open ClPointedSteinerMagmaTerm inductive OpPointedSteinerMagmaTerm (n : β„•) : Type | v : ((fin n) β†’ OpPointedSteinerMagmaTerm) | opOL : (OpPointedSteinerMagmaTerm β†’ (OpPointedSteinerMagmaTerm β†’ OpPointedSteinerMagmaTerm)) | eOL : OpPointedSteinerMagmaTerm open OpPointedSteinerMagmaTerm inductive OpPointedSteinerMagmaTerm2 (n : β„•) (A : Type) : Type | v2 : ((fin n) β†’ OpPointedSteinerMagmaTerm2) | sing2 : (A β†’ OpPointedSteinerMagmaTerm2) | opOL2 : (OpPointedSteinerMagmaTerm2 β†’ (OpPointedSteinerMagmaTerm2 β†’ OpPointedSteinerMagmaTerm2)) | eOL2 : OpPointedSteinerMagmaTerm2 open OpPointedSteinerMagmaTerm2 def simplifyCl {A : Type} : ((ClPointedSteinerMagmaTerm A) β†’ (ClPointedSteinerMagmaTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | eCl := eCl | (sing x1) := (sing x1) def simplifyOpB {n : β„•} : ((OpPointedSteinerMagmaTerm n) β†’ (OpPointedSteinerMagmaTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | eOL := eOL | (v x1) := (v x1) def simplifyOp {n : β„•} {A : Type} : ((OpPointedSteinerMagmaTerm2 n A) β†’ (OpPointedSteinerMagmaTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | eOL2 := eOL2 | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((PointedSteinerMagma A) β†’ (PointedSteinerMagmaTerm β†’ A)) | Po (opL x1 x2) := ((op Po) (evalB Po x1) (evalB Po x2)) | Po eL := (e Po) def evalCl {A : Type} : ((PointedSteinerMagma A) β†’ ((ClPointedSteinerMagmaTerm A) β†’ A)) | Po (sing x1) := x1 | Po (opCl x1 x2) := ((op Po) (evalCl Po x1) (evalCl Po x2)) | Po eCl := (e Po) def evalOpB {A : Type} {n : β„•} : ((PointedSteinerMagma A) β†’ ((vector A n) β†’ ((OpPointedSteinerMagmaTerm n) β†’ A))) | Po vars (v x1) := (nth vars x1) | Po vars (opOL x1 x2) := ((op Po) (evalOpB Po vars x1) (evalOpB Po vars x2)) | Po vars eOL := (e Po) def evalOp {A : Type} {n : β„•} : ((PointedSteinerMagma A) β†’ ((vector A n) β†’ ((OpPointedSteinerMagmaTerm2 n A) β†’ A))) | Po vars (v2 x1) := (nth vars x1) | Po vars (sing2 x1) := x1 | Po vars (opOL2 x1 x2) := ((op Po) (evalOp Po vars x1) (evalOp Po vars x2)) | Po vars eOL2 := (e Po) def inductionB {P : (PointedSteinerMagmaTerm β†’ Type)} : ((βˆ€ (x1 x2 : PointedSteinerMagmaTerm) , ((P x1) β†’ ((P x2) β†’ (P (opL x1 x2))))) β†’ ((P eL) β†’ (βˆ€ (x : PointedSteinerMagmaTerm) , (P x)))) | popl pel (opL x1 x2) := (popl _ _ (inductionB popl pel x1) (inductionB popl pel x2)) | popl pel eL := pel def inductionCl {A : Type} {P : ((ClPointedSteinerMagmaTerm A) β†’ Type)} : ((βˆ€ (x1 : A) , (P (sing x1))) β†’ ((βˆ€ (x1 x2 : (ClPointedSteinerMagmaTerm A)) , ((P x1) β†’ ((P x2) β†’ (P (opCl x1 x2))))) β†’ ((P eCl) β†’ (βˆ€ (x : (ClPointedSteinerMagmaTerm A)) , (P x))))) | psing popcl pecl (sing x1) := (psing x1) | psing popcl pecl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl pecl x1) (inductionCl psing popcl pecl x2)) | psing popcl pecl eCl := pecl def inductionOpB {n : β„•} {P : ((OpPointedSteinerMagmaTerm n) β†’ Type)} : ((βˆ€ (fin : (fin n)) , (P (v fin))) β†’ ((βˆ€ (x1 x2 : (OpPointedSteinerMagmaTerm n)) , ((P x1) β†’ ((P x2) β†’ (P (opOL x1 x2))))) β†’ ((P eOL) β†’ (βˆ€ (x : (OpPointedSteinerMagmaTerm n)) , (P x))))) | pv popol peol (v x1) := (pv x1) | pv popol peol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol peol x1) (inductionOpB pv popol peol x2)) | pv popol peol eOL := peol def inductionOp {n : β„•} {A : Type} {P : ((OpPointedSteinerMagmaTerm2 n A) β†’ Type)} : ((βˆ€ (fin : (fin n)) , (P (v2 fin))) β†’ ((βˆ€ (x1 : A) , (P (sing2 x1))) β†’ ((βˆ€ (x1 x2 : (OpPointedSteinerMagmaTerm2 n A)) , ((P x1) β†’ ((P x2) β†’ (P (opOL2 x1 x2))))) β†’ ((P eOL2) β†’ (βˆ€ (x : (OpPointedSteinerMagmaTerm2 n A)) , (P x)))))) | pv2 psing2 popol2 peol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 peol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 peol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 peol2 x1) (inductionOp pv2 psing2 popol2 peol2 x2)) | pv2 psing2 popol2 peol2 eOL2 := peol2 def stageB : (PointedSteinerMagmaTerm β†’ (Staged PointedSteinerMagmaTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | eL := (Now eL) def stageCl {A : Type} : ((ClPointedSteinerMagmaTerm A) β†’ (Staged (ClPointedSteinerMagmaTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | eCl := (Now eCl) def stageOpB {n : β„•} : ((OpPointedSteinerMagmaTerm n) β†’ (Staged (OpPointedSteinerMagmaTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | eOL := (Now eOL) def stageOp {n : β„•} {A : Type} : ((OpPointedSteinerMagmaTerm2 n A) β†’ (Staged (OpPointedSteinerMagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | eOL2 := (Now eOL2) structure StagedRepr (A : Type) (Repr : (Type β†’ Type)) : Type := (opT : ((Repr A) β†’ ((Repr A) β†’ (Repr A)))) (eT : (Repr A)) end PointedSteinerMagma
ee32a5928f210e9f6ba118f5fc17a5b578edf0b1
4fa161becb8ce7378a709f5992a594764699e268
/src/data/real/hyperreal.lean
f1c9a7336d143dcb20a98c1e77e5ad753beb19e4
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
36,759
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ import order.filter.filter_product import analysis.specific_limits open filter filter.filter_product open_locale topological_space classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ @[reducible] def hyperreal := filter.filterprod ℝ (@hyperfilter β„•) namespace hyperreal notation `ℝ*` := hyperreal private def U : is_ultrafilter (@hyperfilter β„•) := is_ultrafilter_hyperfilter noncomputable instance : discrete_linear_ordered_field ℝ* := filter_product.discrete_linear_ordered_field U @[simp] lemma hyperfilter_ne_bot {Ξ±} [infinite Ξ±] : Β¬ @hyperfilter Ξ± = βŠ₯ := is_ultrafilter_hyperfilter.1 @[simp] lemma hyperfilter_ne_bot' {Ξ±} [infinite Ξ±] : Β¬ βŠ₯ = @hyperfilter Ξ± := hyperfilter_ne_bot ∘ eq.symm @[simp, norm_cast] lemma coe_eq_coe (x y : ℝ) : (x : ℝ*) = y ↔ x = y := filter_product.coe_inj _ _ (by simp) @[simp, norm_cast] lemma cast_div (x y : ℝ) : ((x / y : ℝ) : ℝ*) = x / y := filter_product.of_div is_ultrafilter_hyperfilter _ _ @[simp, norm_cast] lemma coe_lt_coe (x y : ℝ) : (x : ℝ*) < y ↔ x < y := (filter_product.of_lt is_ultrafilter_hyperfilter).symm @[simp, norm_cast] lemma coe_le_coe (x y : ℝ) : (x : ℝ*) ≀ y ↔ x ≀ y := (filter_product.of_le hyperfilter_ne_bot).symm @[simp, norm_cast] lemma coe_abs (x : ℝ) : ((abs x : ℝ) : ℝ*) = abs x := filter_product.of_abs _ _ @[simp, norm_cast] lemma coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := filter_product.of_max _ _ _ @[simp, norm_cast] lemma coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := filter_product.of_min _ _ _ /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq (Ξ» n, n⁻¹) /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq (Ξ» n, n) localized "notation `Ξ΅` := hyperreal.epsilon" in hyperreal localized "notation `Ο‰` := hyperreal.omega" in hyperreal lemma epsilon_eq_inv_omega : Ξ΅ = ω⁻¹ := rfl lemma inv_epsilon_eq_omega : Ρ⁻¹ = Ο‰ := @inv_inv' _ _ Ο‰ lemma epsilon_pos : 0 < Ξ΅ := suffices βˆ€αΆ  i in hyperfilter, (0 : ℝ) < (i : β„•)⁻¹, by rwa lt_def U, have h0' : {n : β„• | Β¬ n > 0} = {0} := by simp only [not_lt, (set.set_of_eq_eq_singleton).symm]; ext; exact nat.le_zero_iff, begin simp only [inv_pos, nat.cast_pos], exact mem_hyperfilter_of_finite_compl (by convert set.finite_singleton _), end lemma epsilon_ne_zero : Ξ΅ β‰  0 := ne_of_gt epsilon_pos lemma omega_pos : 0 < Ο‰ := by rw ←inv_epsilon_eq_omega; exact inv_pos.2 epsilon_pos lemma omega_ne_zero : Ο‰ β‰  0 := ne_of_gt omega_pos theorem epsilon_mul_omega : Ξ΅ * Ο‰ = 1 := @inv_mul_cancel _ _ Ο‰ omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : β„• β†’ ℝ} (hf : tendsto f at_top (𝓝 0)) : βˆ€ {r : ℝ}, r > 0 β†’ of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, dist_zero_right, norm, lt_def U] at hf ⊒, intros r hr, cases hf r hr with N hf', have hs : -{i : β„• | f i < r} βŠ† {i : β„• | i ≀ N} := Ξ» i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact Ξ» hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl (set.finite_subset (set.finite_le_nat N) hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : β„• β†’ ℝ} (hf : tendsto f at_top (𝓝 0)) : βˆ€ {r : ℝ}, r > 0 β†’ (-r : ℝ*) < of_seq f := Ξ» r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : β„• β†’ ℝ} (hf : tendsto f at_top (𝓝 0)) : βˆ€ {r : ℝ}, r < 0 β†’ (r : ℝ*) < of_seq f := Ξ» r hr, by rw [←neg_neg r, of_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : x > 0 β†’ Ξ΅ < of x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := βˆ€ Ξ΄ : ℝ, Ξ΄ > 0 β†’ (r - Ξ΄ : ℝ*) < x ∧ x < r + Ξ΄ /-- Standard part function: like a "round" to ℝ instead of β„€ -/ noncomputable def st : ℝ* β†’ ℝ := Ξ» x, if h : βˆƒ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := βˆ€ r : ℝ, x > r /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := βˆ€ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x -- SOME FACTS ABOUT ST private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith, begin norm_cast at *, rw h at hs', exact not_lt_of_lt hs' hr' end theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (βˆƒ r : ℝ, is_st x r) β†’ Β¬ infinite x := Ξ» he hi, Exists.dcases_on he $ Ξ» r hr, hi.elim (Ξ» hip, not_lt_of_lt (hr 2 two_pos).2 (hip $ r + 2)) (Ξ» hin, not_lt_of_lt (hr 2 two_pos).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : Β¬ infinite x) : is_st x (Sup {y : ℝ | of y < x}) := let S : set ℝ := {y : ℝ | of y < x} in let R : _ := Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ Ξ» r₁ hr₁ rβ‚‚ hrβ‚‚, have HR₁ : βˆƒ y : ℝ, y ∈ S := ⟨ r₁ - 1, lt_of_lt_of_le (of_lt_of_lt U (sub_one_lt _)) (not_lt.mp hr₁) ⟩, have HRβ‚‚ : βˆƒ z : ℝ, βˆ€ y ∈ S, y ≀ z := ⟨ rβ‚‚, Ξ» y hy, le_of_lt ((of_lt U).mpr (lt_of_lt_of_le hy (not_lt.mp hrβ‚‚))) ⟩, Ξ» Ξ΄ hΞ΄, ⟨ lt_of_not_ge' $ Ξ» c, have hc : βˆ€ y ∈ S, y ≀ R - Ξ΄ := Ξ» y hy, (of_le U.1).mpr $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le ((real.Sup_le _ HR₁ HRβ‚‚).mpr hc) $ sub_lt_self R hΞ΄, lt_of_not_ge' $ Ξ» c, have hc : of (R + Ξ΄ / 2) < x := lt_of_lt_of_le (add_lt_add_left (of_lt_of_lt U (half_lt_self hΞ΄)) (of R)) c, not_lt_of_le (real.le_Sup _ HRβ‚‚ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : Β¬ infinite x) : βˆƒ r : ℝ, is_st x r := ⟨ Sup {y : ℝ | of y < x}, is_st_Sup hni ⟩ theorem st_eq_Sup {x : ℝ*} : st x = Sup {y : ℝ | of y < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (Ξ» i, ⟨λ hi, set.mem_univ i, Ξ» hi, H i⟩) : {y : ℝ | of y < x} = set.univ), exact (real.Sup_univ).symm }, { rw (set.ext (Ξ» i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), Ξ» hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | of y < x} = βˆ…), exact (real.Sup_empty).symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (βˆƒ r : ℝ, is_st x r) ↔ Β¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ Β¬ βˆƒ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : βˆƒ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (Ξ» r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x β‰  0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : Β¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := Ξ» Ξ΄ hΞ΄, ⟨ sub_lt_self _ (of_lt_of_lt U hΞ΄), (lt_add_of_pos_right _ (of_lt_of_lt U hΞ΄)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s β†’ r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, Ξ» hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s β†’ is_st s t β†’ is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ rβ‚‚ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st rβ‚‚ s) : r₁ = rβ‚‚ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ βˆ€ (Ξ΄ : ℝ), Ξ΄ > 0 β†’ abs (x - r) < Ξ΄ := by simp only [abs_sub_lt_iff, @sub_lt _ _ (r : ℝ*) x _, @sub_lt_iff_lt_add' _ _ x (r : ℝ*) _, and_comm]; refl lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r β†’ is_st y s β†’ is_st (x + y) (r + s) := Ξ» hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), ⟨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith, by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarith⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := Ξ» d hd, by show -(r : ℝ*) - d < -x ∧ -x < -r + d; cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r β†’ is_st y s β†’ is_st (x - y) (r - s) := Ξ» hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) β†’ (x < y) β†’ (x ≀ y) β†’ (st x ≀ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s β†’ x < y := Ξ» hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, begin norm_cast at *, rw H1 at hxr', rw H2 at hys', exact lt_trans hxr' hys' end lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≀ y β†’ r ≀ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : Β¬ infinite x) (hiy : Β¬ infinite y) : x ≀ y β†’ st x ≀ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : Β¬ infinite x) (hiy : Β¬ infinite y) : st x < st y β†’ x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' -- BASIC LEMMAS ABOUT INFINITE lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ βˆ€ r : ℝ, x > r := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ βˆ€ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x β†’ x β‰  0 := Ξ» hI h0, or.cases_on hI (Ξ» hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (Ξ» hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : Β¬ infinite 0 := Ξ» hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x β†’ x > 0 := Ξ» hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x β†’ x < 0 := Ξ» hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x β†’ Β¬ infinite_pos x := Ξ» hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x β†’ Β¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x β†’ infinite_neg (-x) := Ξ» hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x β†’ infinite_pos (-x) := Ξ» hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, Ξ» hin, neg_neg x β–Έ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, Ξ» hin, neg_neg x β–Έ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ Ξ» hi, or.cases_on hi (Ξ» hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (Ξ» hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), Ξ» hi, or.cases_on hi (Ξ» hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (Ξ» hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x β†’ Β¬ infinite x := Ξ» hi hI, have hi' : _ := (hi 2 two_pos), or.dcases_on hI (Ξ» hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (Ξ» hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x β†’ Β¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x β†’ Β¬ infinitesimal x := Ξ» hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x β†’ Β¬ infinitesimal x := Ξ» hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ x > 0) := ⟨ Ξ» hip, ⟨or.inl hip, hip 0⟩, Ξ» ⟨hi, hp⟩, hi.cases_on (Ξ» hip, hip) (Ξ» hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ Ξ» hip, ⟨or.inr hip, hip 0⟩, Ξ» ⟨hi, hp⟩, hi.cases_on (Ξ» hin, false.elim (not_lt_of_lt hp (hin 0))) (Ξ» hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : x > 0) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, Ξ» hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : x β‰₯ 0) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (Ξ» h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), Ξ» hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, Ξ» hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (abs x) ↔ infinite (abs x) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (abs x) := ⟨ Ξ» hi d, or.cases_on hi (Ξ» hip, by rw [abs_of_pos (hip 0)]; exact hip d) (Ξ» hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), Ξ» hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (abs x) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ βˆ€ r : ℝ, (abs r : ℝ*) < abs x := ⟨ Ξ» hI r, (of_abs U r) β–Έ infinite_iff_infinite_pos_abs.mp hI (abs r), Ξ» hR, or.cases_on (max_choice x (-x)) (Ξ» h, or.inl $ Ξ» r, lt_of_le_of_lt (le_abs_self _) (h β–Έ (hR r))) (Ξ» h, or.inr $ Ξ» r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h β–Έ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x β†’ Β¬ infinite_neg y β†’ infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with rβ‚‚ hrβ‚‚, convert add_lt_add_of_lt_of_le (hip (r + -rβ‚‚)) (not_lt.mp hrβ‚‚) using 1, simp end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : Β¬ infinite_neg x β†’ infinite_pos y β†’ infinite_pos (x + y) := Ξ» hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x β†’ Β¬ infinite_pos y β†’ infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : Β¬ infinite_pos x β†’ infinite_neg y β†’ infinite_neg (x + y) := Ξ» hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x β†’ infinite_pos y β†’ infinite_pos (x + y) := Ξ» hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x β†’ infinite_neg y β†’ infinite_neg (x + y) := Ξ» hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x β†’ Β¬ infinite y β†’ infinite_pos (x + y) := Ξ» hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x β†’ Β¬ infinite y β†’ infinite_neg (x + y) := Ξ» hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : β„• β†’ ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := Ξ» r, have hf' : _ := (tendsto_at_top_at_top _).mp hf, Exists.cases_on (hf' (r + 1)) $ Ξ» i hi, have hi' : βˆ€ (a : β„•), f a < (r + 1) β†’ a < i := Ξ» a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : - {a : β„• | r < f a} βŠ† {a : β„• | a ≀ i} := by simp only [set.compl_set_of, not_lt]; exact Ξ» a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), (lt_def U).mpr $ mem_hyperfilter_of_finite_compl $ set.finite_subset (set.finite_le_nat _) hS theorem infinite_neg_of_tendsto_bot {f : β„• β†’ ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := Ξ» r, have hf' : _ := (tendsto_at_top_at_bot _).mp hf, Exists.cases_on (hf' (r - 1)) $ Ξ» i hi, have hi' : βˆ€ (a : β„•), r - 1 < f a β†’ a < i := Ξ» a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : - {a : β„• | f a < r} βŠ† {a : β„• | a ≀ i} := by simp only [set.compl_set_of, not_lt]; exact Ξ» a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), (lt_def U).mpr $ mem_hyperfilter_of_finite_compl $ set.finite_subset (set.finite_le_nat _) hS lemma not_infinite_neg {x : ℝ*} : Β¬ infinite x β†’ Β¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : Β¬ infinite x) (hy : Β¬ infinite y) : Β¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ Ξ» r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : Β¬ infinite x ↔ βˆƒ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ Ξ» hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ Ξ» r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩ ⟩, Ξ» hrs, Exists.dcases_on hrs $ Ξ» r hr, Exists.dcases_on hr $ Ξ» s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : Β¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, by rw [←of_eq_coe, ←of_eq_coe, ←of_lt U]; exact sub_one_lt _, by rw [←of_eq_coe, ←of_eq_coe, ←of_lt U]; exact lt_add_one _⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x β†’ βˆ€ r : ℝ, x β‰  of r := Ξ» hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi -- FACTS ABOUT ST THAT REQUIRE SOME INFINITE MACHINERY private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s β‰  0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ Ξ» u h', Exists.cases_on h' $ Ξ» t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ Ξ» d hd, calc abs (x * y - of (r * s)) = abs (x * y - (of r) * (of s)) : by simp ... = abs (x * (y - of s) + (x - of r) * (of s)) : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≀ abs (x * (y - of s)) + abs ((x - of r) * (of s)) : abs_add _ _ ... ≀ abs x * abs (y - of s) + abs (x - of r) * abs (of s) : by simp only [abs_mul] ... ≀ abs x * ((d / t) / 2 : ℝ) + ((d / abs s) / 2 : ℝ) * abs s : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ (of_lt U).mpr $ lt_of_le_of_lt (abs_nonneg _) ht) $ abs_nonneg _ ) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos_of_ne_zero hs) $ abs_nonneg _) ... = (d / 2 * (abs x / t) + d / 2 : ℝ*) : by { rw [div_div_eq_div_mul, mul_comm t 2, ←div_div_eq_div_mul, of_div U, div_div_eq_div_mul, mul_comm (abs s) 2, ←div_div_eq_div_mul, mul_div_comm, of_div U, of_div U, of_div U, of_abs U, div_mul_cancel _ (ne_of_gt (abs_pos_of_ne_zero ((of_ne_zero U.1 _).mp hs)))], refl } ... < (d / 2 * 1 + d / 2 : ℝ*) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one_iff_lt $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ of_lt_of_lt U hd) _ ... = (d : ℝ*) : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ Ξ» u h', Exists.cases_on h' $ Ξ» t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd ((of_lt U).mpr (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, of_zero, sub_zero] at hys', rw [hs, mul_zero, of_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←of_div U], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : Β¬ infinite x) (hy : Β¬ infinite y) : Β¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ Ξ» r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : Β¬infinite x) (hy : Β¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : Β¬infinite x) (hy : Β¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' -- BASIC LEMMAS ABOUT INFINITESIMAL theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (βˆ€ r : ℝ, r > 0 β†’ -(r : ℝ*) < x ∧ x < r) := ⟨ Ξ» hi r hr, by { convert (hi r hr), exact (zero_sub (of r)).symm, exact (zero_add (of r)).symm }, Ξ» hi d hd, by { convert (hi d hd), exact zero_sub (of d), exact zero_add (of d) } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x β†’ βˆ€ r : ℝ, r > 0 β†’ x < r := Ξ» hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x β†’ βˆ€ r : ℝ, r > 0 β†’ x > -r := Ξ» hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x β†’ βˆ€ r : ℝ, r < 0 β†’ x > r := Ξ» hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg (of r)).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ βˆ€ r : ℝ, r β‰  0 β†’ abs x < abs r := ⟨ Ξ» hi r hr, abs_lt.mpr (by rw ←of_abs U; exact infinitesimal_def.mp hi (abs r) (abs_pos_of_ne_zero hr)), Ξ» hR, infinitesimal_def.mpr $ Ξ» r hr, abs_lt.mp $ (abs_of_pos $ of_lt_of_lt U hr : abs (r : ℝ*) = r) β–Έ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r β†’ r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, Ξ» hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy lemma infinitesimal_neg {x : ℝ*} (hx : infinitesimal x) : infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, Ξ» h, (neg_neg x) β–Έ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x * y) := by simpa only [mul_zero] using is_st_mul hx hy theorem infinitesimal_of_tendsto_zero {f : β„• β†’ ℝ} : tendsto f at_top (𝓝 0) β†’ infinitesimal (of_seq f) := Ξ» hf d hd, by rw [sub_eq_add_neg, ←of_neg, ←of_add, ←of_add, zero_add, zero_add]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal Ξ΅ := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x β†’ x β‰  0 β†’ βˆ€ r : ℝ, x β‰  of r := Ξ» hi hx r hr, hx (is_st_unique (hr.symm β–Έ is_st_refl_real r : is_st x r) hi β–Έ hr : x = of 0) theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x + -r) 0, by rw ←add_neg_self r; exact is_st_add hxr (is_st_refl_real (-r)) theorem infinitesimal_sub_st {x : ℝ*} (hx : Β¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ > 0) := ⟨ Ξ» hip, ⟨ infinitesimal_def.mpr $ Ξ» r hr, ⟨ lt_trans (of_lt_of_lt U (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (of_lt_of_lt U hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos.2 $ hip 0 ⟩, Ξ» ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (x > (r : ℝ*)) (Ξ» h, eq.substr h (inv_pos.mp hp)) $ Ξ» h, lt_of_le_of_lt (of_le_of_le (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (of_lt_of_lt U (abs_pos_of_ne_zero h))).mp ((infinitesimal_def.mp hi) ((abs r)⁻¹) (inv_pos.2 (abs_pos_of_ne_zero h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ Ξ» hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv], Ξ» hin, have h0 : x β‰  0 := Ξ» h0, (lt_irrefl (0 : ℝ*) (by convert hin.2; rw [h0, inv_zero])), by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x β†’ infinitesimal x⁻¹ := Ξ» hi, or.cases_on hi (Ξ» hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (Ξ» hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x β‰  0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x β‰  0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ x > 0) := by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv'] lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv'] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x β‰  0) : infinitesimal x ↔ infinite x⁻¹ := by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv'] -- ST STUFF THAT REQUIRES INFINITESIMAL MACHINERY theorem is_st_of_tendsto {f : β„• β†’ ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (Ξ» n, f n - r) at_top (𝓝 0) := (sub_self r) β–Έ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (Ξ» n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : Β¬ infinitesimal x) : is_st x r β†’ is_st x⁻¹ r⁻¹ := Ξ» hxr, have h : x β‰  0 := (Ξ» h, hi (h.symm β–Έ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ Ξ» s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h β–Έ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div_eq_inv r β–Έ eq_one_div_of_mul_eq_one (eq_of_is_st_real H').symm, H'' β–Έ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←of_zero, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end -- INFINITE STUFF THAT REQUIRES INFINITESIMAL MACHINERY lemma infinite_pos_omega : infinite_pos Ο‰ := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite Ο‰ := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x β†’ Β¬ infinitesimal y β†’ y > 0 β†’ infinite_pos (x * y) := Ξ» hx hy₁ hyβ‚‚ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ Ξ» r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hyβ‚‚] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), of_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (of_lt_of_lt U hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : Β¬ infinitesimal x β†’ 0 < x β†’ infinite_pos y β†’ infinite_pos (x * y) := Ξ» hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x β†’ Β¬ infinitesimal y β†’ y < 0 β†’ infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : Β¬ infinitesimal x β†’ x < 0 β†’ infinite_neg y β†’ infinite_pos (x * y) := Ξ» hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x β†’ Β¬ infinitesimal y β†’ y < 0 β†’ infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : Β¬ infinitesimal x β†’ x < 0 β†’ infinite_pos y β†’ infinite_neg (x * y) := Ξ» hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x β†’ Β¬ infinitesimal y β†’ 0 < y β†’ infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : Β¬ infinitesimal x β†’ x > 0 β†’ infinite_neg y β†’ infinite_neg (x * y) := Ξ» hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x β†’ infinite_pos y β†’ infinite_pos (x * y) := Ξ» hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x β†’ infinite_neg y β†’ infinite_pos (x * y) := Ξ» hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x β†’ infinite_neg y β†’ infinite_neg (x * y) := Ξ» hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x β†’ infinite_pos y β†’ infinite_neg (x * y) := Ξ» hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x β†’ Β¬ infinitesimal y β†’ infinite (x * y) := Ξ» hx hy, have h0 : y < 0 ∨ y > 0 := lt_or_gt_of_ne (Ξ» H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (Ξ» H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (Ξ» H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (Ξ» H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (Ξ» H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : Β¬ infinitesimal x β†’ infinite y β†’ infinite (x * y) := Ξ» hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite_mul_infinite {x y : ℝ*} : infinite x β†’ infinite y β†’ infinite (x * y) := Ξ» hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal
6d479fcf665a5eced82fb0d8a81dbc67204103b4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/prod/lex.lean
9d8f30c6645d979fc1c8bffca67d4755d7f0ab76
[ "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
3,953
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Minchao Wu -/ import order.synonym /-! # Lexicographic order This file defines the lexicographic relation for pairs of orders, partial orders and linear orders. ## Main declarations * `prod.lex.<pre/partial_/linear_>order`: Instances lifting the orders on `Ξ±` and `Ξ²` to `Ξ± Γ—β‚— Ξ²`. ## Notation * `Ξ± Γ—β‚— Ξ²`: `Ξ± Γ— Ξ²` equipped with the lexicographic order ## See also Related files are: * `data.finset.colex`: Colexicographic order on finite sets. * `data.list.lex`: Lexicographic order on lists. * `data.pi.lex`: Lexicographic order on `Ξ β‚— i, Ξ± i`. * `data.psigma.order`: Lexicographic order on `Ξ£' i, Ξ± i`. * `data.sigma.order`: Lexicographic order on `Ξ£ i, Ξ± i`. -/ variables {Ξ± Ξ² Ξ³ : Type*} namespace prod.lex notation Ξ± ` Γ—β‚— `:35 Ξ²:34 := lex (prod Ξ± Ξ²) meta instance [has_to_format Ξ±] [has_to_format Ξ²] : has_to_format (Ξ± Γ—β‚— Ξ²) := prod.has_to_format instance decidable_eq (Ξ± Ξ² : Type*) [decidable_eq Ξ±] [decidable_eq Ξ²] : decidable_eq (Ξ± Γ—β‚— Ξ²) := prod.decidable_eq instance inhabited (Ξ± Ξ² : Type*) [inhabited Ξ±] [inhabited Ξ²] : inhabited (Ξ± Γ—β‚— Ξ²) := prod.inhabited /-- Dictionary / lexicographic ordering on pairs. -/ instance has_le (Ξ± Ξ² : Type*) [has_lt Ξ±] [has_le Ξ²] : has_le (Ξ± Γ—β‚— Ξ²) := { le := prod.lex (<) (≀) } instance has_lt (Ξ± Ξ² : Type*) [has_lt Ξ±] [has_lt Ξ²] : has_lt (Ξ± Γ—β‚— Ξ²) := { lt := prod.lex (<) (<) } lemma le_iff [has_lt Ξ±] [has_le Ξ²] (a b : Ξ± Γ— Ξ²) : to_lex a ≀ to_lex b ↔ a.1 < b.1 ∨ a.1 = b.1 ∧ a.2 ≀ b.2 := prod.lex_def (<) (≀) lemma lt_iff [has_lt Ξ±] [has_lt Ξ²] (a b : Ξ± Γ— Ξ²) : to_lex a < to_lex b ↔ a.1 < b.1 ∨ a.1 = b.1 ∧ a.2 < b.2 := prod.lex_def (<) (<) /-- Dictionary / lexicographic preorder for pairs. -/ instance preorder (Ξ± Ξ² : Type*) [preorder Ξ±] [preorder Ξ²] : preorder (Ξ± Γ—β‚— Ξ²) := { le_refl := by { haveI : is_refl Ξ² (≀) := ⟨le_refl⟩, exact refl_of (prod.lex _ _), }, le_trans := Ξ» _ _ _, by { haveI : is_trans Ξ± (<) := ⟨λ _ _ _, lt_trans⟩, haveI : is_trans Ξ² (≀) := ⟨λ _ _ _, le_trans⟩, exact trans_of (prod.lex _ _) }, lt_iff_le_not_le := Ξ» x₁ xβ‚‚, match x₁, xβ‚‚ with | to_lex (a₁, b₁), to_lex (aβ‚‚, bβ‚‚) := begin split, { rintros (⟨_, _, _, _, hlt⟩ | ⟨_, _, _, hlt⟩), { split, { left, assumption }, { rintro ⟨l,r⟩, { apply lt_asymm hlt, assumption }, { apply lt_irrefl _ hlt } } }, { split, { right, rw lt_iff_le_not_le at hlt, exact hlt.1 }, { rintro ⟨l,r⟩, { apply lt_irrefl a₁, assumption }, { rw lt_iff_le_not_le at hlt, apply hlt.2, assumption } } } }, { rintros ⟨⟨h₁ll, h₁lr⟩, hβ‚‚r⟩, { left, assumption }, { right, rw lt_iff_le_not_le, split, { assumption }, { intro h, apply hβ‚‚r, right, exact h } } } end end, .. prod.lex.has_le Ξ± Ξ², .. prod.lex.has_lt Ξ± Ξ² } /-- Dictionary / lexicographic partial_order for pairs. -/ instance partial_order (Ξ± Ξ² : Type*) [partial_order Ξ±] [partial_order Ξ²] : partial_order (Ξ± Γ—β‚— Ξ²) := { le_antisymm := by { haveI : is_strict_order Ξ± (<) := { irrefl := lt_irrefl, trans := Ξ» _ _ _, lt_trans }, haveI : is_antisymm Ξ² (≀) := ⟨λ _ _, le_antisymm⟩, exact @antisymm _ (prod.lex _ _) _, }, .. prod.lex.preorder Ξ± Ξ² } /-- Dictionary / lexicographic linear_order for pairs. -/ instance linear_order (Ξ± Ξ² : Type*) [linear_order Ξ±] [linear_order Ξ²] : linear_order (Ξ± Γ—β‚— Ξ²) := { le_total := total_of (prod.lex _ _), decidable_le := prod.lex.decidable _ _, decidable_lt := prod.lex.decidable _ _, decidable_eq := lex.decidable_eq _ _, .. prod.lex.partial_order Ξ± Ξ² } end prod.lex
2d1a4d4331a4f29f44c36e8412fa2e6261373ea8
26ac254ecb57ffcb886ff709cf018390161a9225
/src/group_theory/free_abelian_group.lean
8d60533fae4158f1db4c44541e52417fd380a2fe
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
12,400
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Free abelian groups as abelianization of free groups. -/ import algebra.pi_instances import group_theory.free_group import group_theory.abelianization universes u v variables (Ξ± : Type u) def free_abelian_group : Type u := additive $ abelianization $ free_group Ξ± instance : add_comm_group (free_abelian_group Ξ±) := @additive.add_comm_group _ $ abelianization.comm_group _ instance : inhabited (free_abelian_group Ξ±) := ⟨0⟩ variable {Ξ±} namespace free_abelian_group def of (x : Ξ±) : free_abelian_group Ξ± := abelianization.of $ free_group.of x def lift {Ξ² : Type v} [add_comm_group Ξ²] (f : Ξ± β†’ Ξ²) (x : free_abelian_group Ξ±) : Ξ² := @abelianization.lift _ _ (multiplicative Ξ²) _ (@free_group.to_group _ (multiplicative Ξ²) _ f) _ x namespace lift variables {Ξ² : Type v} [add_comm_group Ξ²] (f : Ξ± β†’ Ξ²) open free_abelian_group instance is_add_group_hom : is_add_group_hom (lift f) := { map_add := Ξ» x y, @is_mul_hom.map_mul _ (multiplicative Ξ²) _ _ _ (abelianization.lift.is_group_hom _).to_is_mul_hom x y } @[simp] protected lemma add (x y : free_abelian_group Ξ±) : lift f (x + y) = lift f x + lift f y := is_add_hom.map_add _ _ _ @[simp] protected lemma neg (x : free_abelian_group Ξ±) : lift f (-x) = -lift f x := is_add_group_hom.map_neg _ _ @[simp] protected lemma sub (x y : free_abelian_group Ξ±) : lift f (x - y) = lift f x - lift f y := by simp [sub_eq_add_neg] @[simp] protected lemma zero : lift f 0 = 0 := is_add_group_hom.map_zero _ @[simp] protected lemma of (x : Ξ±) : lift f (of x) = f x := by unfold of; unfold lift; simp protected theorem unique (g : free_abelian_group Ξ± β†’ Ξ²) [is_add_group_hom g] (hg : βˆ€ x, g (of x) = f x) {x} : g x = lift f x := @abelianization.lift.unique (free_group Ξ±) _ (multiplicative Ξ²) _ _ _ g { map_mul := Ξ» x y, is_add_hom.map_add g x y } (Ξ» x, @free_group.to_group.unique Ξ± (multiplicative Ξ²) _ _ (g ∘ abelianization.of) { map_mul := Ξ» m n, is_add_hom.map_add g (abelianization.of m) (abelianization.of n) } hg _) _ protected theorem ext (g h : free_abelian_group Ξ± β†’ Ξ²) [is_add_group_hom g] [is_add_group_hom h] (H : βˆ€ x, g (of x) = h (of x)) {x} : g x = h x := (lift.unique (g ∘ of) g (Ξ» _, rfl)).trans $ eq.symm $ lift.unique _ _ $ Ξ» x, eq.symm $ H x lemma map_hom {Ξ± Ξ² Ξ³} [add_comm_group Ξ²] [add_comm_group Ξ³] (a : free_abelian_group Ξ±) (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) [is_add_group_hom g] : g (a.lift f) = a.lift (g ∘ f) := show (g ∘ lift f) a = a.lift (g ∘ f), begin haveI : is_add_group_hom (g ∘ lift f) := is_add_group_hom.comp _ _, apply @lift.unique, assume a, simp only [(∘), lift.of] end end lift section variables (X : Type*) (G : Type*) [add_comm_group G] /-- The bijection underlying the free-forgetful adjunction for abelian groups.-/ def hom_equiv : (free_abelian_group X β†’+ G) ≃ (X β†’ G) := { to_fun := Ξ» f, f.1 ∘ of, inv_fun := Ξ» f, add_monoid_hom.of (lift f), left_inv := Ξ» f, begin ext, simp, exact (lift.unique _ _ (Ξ» x, rfl)).symm, end, right_inv := Ξ» f, funext $ Ξ» x, lift.of f x } @[simp] lemma hom_equiv_apply (f) (x) : ((hom_equiv X G) f) x = f (of x) := rfl @[simp] lemma hom_equiv_symm_apply (f) (x) : ((hom_equiv X G).symm f) x = (lift f) x := rfl end local attribute [instance] quotient_group.left_rel normal_subgroup.to_is_subgroup @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group Ξ± β†’ Prop} (z : free_abelian_group Ξ±) (C0 : C 0) (C1 : βˆ€ x, C $ of x) (Cn : βˆ€ x, C (of x) β†’ C (-of x)) (Cp : βˆ€ x y, C x β†’ C y β†’ C (x + y)) : C z := quotient.induction_on z $ Ξ» x, quot.induction_on x $ Ξ» L, list.rec_on L C0 $ Ξ» ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) theorem lift.add' {Ξ± Ξ²} [add_comm_group Ξ²] (a : free_abelian_group Ξ±) (f g : Ξ± β†’ Ξ²) : a.lift (f + g) = (a.lift f) + (a.lift g) := begin refine free_abelian_group.induction_on a _ _ _ _, { simp only [lift.zero, zero_add] }, { assume x, simp only [lift.of, pi.add_apply] }, { assume x h, simp only [lift.neg, lift.of, pi.add_apply, neg_add] }, { assume x y hx hy, simp only [lift.add, hx, hy], ac_refl } end instance is_add_group_hom_lift' {Ξ±} (Ξ²) [add_comm_group Ξ²] (a : free_abelian_group Ξ±) : is_add_group_hom (Ξ»f, (a.lift f : Ξ²)) := { map_add := Ξ» f g, lift.add' a f g } variables {Ξ² : Type u} instance : monad free_abelian_group.{u} := { pure := Ξ» Ξ±, of, bind := Ξ» Ξ± Ξ² x f, lift f x } @[elab_as_eliminator] protected theorem induction_on' {C : free_abelian_group Ξ± β†’ Prop} (z : free_abelian_group Ξ±) (C0 : C 0) (C1 : βˆ€ x, C $ pure x) (Cn : βˆ€ x, C (pure x) β†’ C (-pure x)) (Cp : βˆ€ x y, C x β†’ C y β†’ C (x + y)) : C z := free_abelian_group.induction_on z C0 C1 Cn Cp @[simp] lemma map_pure (f : Ξ± β†’ Ξ²) (x : Ξ±) : f <$> (pure x : free_abelian_group Ξ±) = pure (f x) := lift.of _ _ @[simp] lemma map_zero (f : Ξ± β†’ Ξ²) : f <$> (0 : free_abelian_group Ξ±) = 0 := lift.zero (of ∘ f) @[simp] lemma map_add (f : Ξ± β†’ Ξ²) (x y : free_abelian_group Ξ±) : f <$> (x + y) = f <$> x + f <$> y := lift.add _ _ _ @[simp] lemma map_neg (f : Ξ± β†’ Ξ²) (x : free_abelian_group Ξ±) : f <$> (-x) = -(f <$> x) := lift.neg _ _ @[simp] lemma map_sub (f : Ξ± β†’ Ξ²) (x y : free_abelian_group Ξ±) : f <$> (x - y) = f <$> x - f <$> y := lift.sub _ _ _ @[simp] lemma map_of (f : Ξ± β†’ Ξ²) (y : Ξ±) : f <$> of y = of (f y) := rfl lemma lift_comp {Ξ±} {Ξ²} {Ξ³} [add_comm_group Ξ³] (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) (x : free_abelian_group Ξ±) : lift (g ∘ f) x = lift g (f <$> x) := begin apply free_abelian_group.induction_on x, { simp only [lift.zero, map_zero], }, { intro y, simp [lift.of, map_of, function.comp_app], }, { intros x w, simp only [w, neg_inj, lift.neg, map_neg], }, { intros x y w₁ wβ‚‚, simp only [w₁, wβ‚‚, lift.add, add_right_inj, map_add], }, end @[simp] lemma pure_bind (f : Ξ± β†’ free_abelian_group Ξ²) (x) : pure x >>= f = f x := lift.of _ _ @[simp] lemma zero_bind (f : Ξ± β†’ free_abelian_group Ξ²) : 0 >>= f = 0 := lift.zero f @[simp] lemma add_bind (f : Ξ± β†’ free_abelian_group Ξ²) (x y : free_abelian_group Ξ±) : x + y >>= f = (x >>= f) + (y >>= f) := lift.add _ _ _ @[simp] lemma neg_bind (f : Ξ± β†’ free_abelian_group Ξ²) (x : free_abelian_group Ξ±) : -x >>= f = -(x >>= f) := lift.neg _ _ @[simp] lemma sub_bind (f : Ξ± β†’ free_abelian_group Ξ²) (x y : free_abelian_group Ξ±) : x - y >>= f = (x >>= f) - (y >>= f) := lift.sub _ _ _ @[simp] lemma pure_seq (f : Ξ± β†’ Ξ²) (x : free_abelian_group Ξ±) : pure f <*> x = f <$> x := pure_bind _ _ @[simp] lemma zero_seq (x : free_abelian_group Ξ±) : (0 : free_abelian_group (Ξ± β†’ Ξ²)) <*> x = 0 := zero_bind _ @[simp] lemma add_seq (f g : free_abelian_group (Ξ± β†’ Ξ²)) (x : free_abelian_group Ξ±) : f + g <*> x = (f <*> x) + (g <*> x) := add_bind _ _ _ @[simp] lemma neg_seq (f : free_abelian_group (Ξ± β†’ Ξ²)) (x : free_abelian_group Ξ±) : -f <*> x = -(f <*> x) := neg_bind _ _ @[simp] lemma sub_seq (f g : free_abelian_group (Ξ± β†’ Ξ²)) (x : free_abelian_group Ξ±) : f - g <*> x = (f <*> x) - (g <*> x) := sub_bind _ _ _ instance is_add_group_hom_seq (f : free_abelian_group (Ξ± β†’ Ξ²)) : is_add_group_hom ((<*>) f) := { map_add := Ξ» x y, show lift (<$> (x+y)) _ = _, by simp only [map_add]; exact @@is_add_hom.map_add _ _ _ (@@free_abelian_group.is_add_group_hom_lift' (free_abelian_group Ξ²) _ _).to_is_add_hom _ _ } @[simp] lemma seq_zero (f : free_abelian_group (Ξ± β†’ Ξ²)) : f <*> 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma seq_add (f : free_abelian_group (Ξ± β†’ Ξ²)) (x y : free_abelian_group Ξ±) : f <*> (x + y) = (f <*> x) + (f <*> y) := is_add_hom.map_add _ _ _ @[simp] lemma seq_neg (f : free_abelian_group (Ξ± β†’ Ξ²)) (x : free_abelian_group Ξ±) : f <*> (-x) = -(f <*> x) := is_add_group_hom.map_neg _ _ @[simp] lemma seq_sub (f : free_abelian_group (Ξ± β†’ Ξ²)) (x y : free_abelian_group Ξ±) : f <*> (x - y) = (f <*> x) - (f <*> y) := is_add_group_hom.map_sub _ _ _ instance : is_lawful_monad free_abelian_group.{u} := { id_map := Ξ» Ξ± x, free_abelian_group.induction_on' x (map_zero id) (Ξ» x, map_pure id x) (Ξ» x ih, by rw [map_neg, ih]) (Ξ» x y ihx ihy, by rw [map_add, ihx, ihy]), pure_bind := Ξ» Ξ± Ξ² x f, pure_bind f x, bind_assoc := Ξ» Ξ± Ξ² Ξ³ x f g, free_abelian_group.induction_on' x (by iterate 3 { rw zero_bind }) (Ξ» x, by iterate 2 { rw pure_bind }) (Ξ» x ih, by iterate 3 { rw neg_bind }; rw ih) (Ξ» x y ihx ihy, by iterate 3 { rw add_bind }; rw [ihx, ihy]) } instance : is_comm_applicative free_abelian_group.{u} := { commutative_prod := Ξ» Ξ± Ξ² x y, free_abelian_group.induction_on' x (by rw [map_zero, zero_seq, seq_zero]) (Ξ» p, by rw [map_pure, pure_seq]; exact free_abelian_group.induction_on' y (by rw [map_zero, map_zero, zero_seq]) (Ξ» q, by rw [map_pure, map_pure, pure_seq, map_pure]) (Ξ» q ih, by rw [map_neg, map_neg, neg_seq, ih]) (Ξ» y₁ yβ‚‚ ih1 ih2, by rw [map_add, map_add, add_seq, ih1, ih2])) (Ξ» p ih, by rw [map_neg, neg_seq, seq_neg, ih]) (Ξ» x₁ xβ‚‚ ih1 ih2, by rw [map_add, add_seq, seq_add, ih1, ih2]) } variable (Ξ±) instance [monoid Ξ±] : semigroup (free_abelian_group Ξ±) := { mul := Ξ» x, lift $ Ξ» xβ‚‚, lift (Ξ» x₁, of $ x₁ * xβ‚‚) x, mul_assoc := Ξ» x y z, begin unfold has_mul.mul, refine free_abelian_group.induction_on z rfl _ _ _, { intros L3, rw [lift.of, lift.of], refine free_abelian_group.induction_on y rfl _ _ _, { intros L2, iterate 3 { rw lift.of }, refine free_abelian_group.induction_on x rfl _ _ _, { intros L1, iterate 3 { rw lift.of }, congr' 1, exact mul_assoc _ _ _ }, { intros L1 ih, iterate 3 { rw lift.neg }, rw ih }, { intros x1 x2 ih1 ih2, iterate 3 { rw lift.add }, rw [ih1, ih2] } }, { intros L2 ih, iterate 4 { rw lift.neg }, rw ih }, { intros y1 y2 ih1 ih2, iterate 4 { rw lift.add }, rw [ih1, ih2] } }, { intros L3 ih, iterate 3 { rw lift.neg }, rw ih }, { intros z1 z2 ih1 ih2, iterate 2 { rw lift.add }, rw [ih1, ih2], exact (lift.add _ _ _).symm } end } lemma mul_def [monoid Ξ±] (x y : free_abelian_group Ξ±) : x * y = lift (Ξ» xβ‚‚, lift (Ξ» x₁, of (x₁ * xβ‚‚)) x) y := rfl instance [monoid Ξ±] : ring (free_abelian_group Ξ±) := { one := free_abelian_group.of 1, mul_one := Ξ» x, begin unfold has_mul.mul semigroup.mul has_one.one, rw lift.of, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, erw [lift.of], congr' 1, exact mul_one L }, { intros L ih, rw [lift.neg, ih] }, { intros x1 x2 ih1 ih2, rw [lift.add, ih1, ih2] } end, one_mul := Ξ» x, begin unfold has_mul.mul semigroup.mul has_one.one, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, rw [lift.of, lift.of], congr' 1, exact one_mul L }, { intros L ih, rw [lift.neg, ih] }, { intros x1 x2 ih1 ih2, rw [lift.add, ih1, ih2] } end, left_distrib := Ξ» x y z, lift.add _ _ _, right_distrib := Ξ» x y z, begin unfold has_mul.mul semigroup.mul, refine free_abelian_group.induction_on z rfl _ _ _, { intros L, iterate 3 { rw lift.of }, rw lift.add, refl }, { intros L ih, iterate 3 { rw lift.neg }, rw [ih, neg_add], refl }, { intros z1 z2 ih1 ih2, iterate 3 { rw lift.add }, rw [ih1, ih2], rw [add_assoc, add_assoc], congr' 1, apply add_left_comm } end, .. free_abelian_group.add_comm_group Ξ±, .. free_abelian_group.semigroup Ξ± } instance [comm_monoid Ξ±] : comm_ring (free_abelian_group Ξ±) := { mul_comm := Ξ» x y, begin refine free_abelian_group.induction_on x (zero_mul y) _ _ _, { intros s, refine free_abelian_group.induction_on y (zero_mul _).symm _ _ _, { intros t, unfold has_mul.mul semigroup.mul ring.mul, iterate 4 { rw lift.of }, congr' 1, exact mul_comm _ _ }, { intros t ih, rw [mul_neg_eq_neg_mul_symm, ih, neg_mul_eq_neg_mul] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_mul, ih1, ih2] } }, { intros s ih, rw [neg_mul_eq_neg_mul_symm, ih, neg_mul_eq_mul_neg] }, { intros x1 x2 ih1 ih2, rw [add_mul, mul_add, ih1, ih2] } end .. free_abelian_group.ring Ξ± } end free_abelian_group
9e67e57dfac8f22f7819992cc3497dfa6b00fd2b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/860.lean
07377b7a5547d127762419e30a844eb3f3bcc2b3
[ "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
996
lean
def evenq (n: Nat) : Bool := Nat.mod n 2 = 0 private theorem pack_loop_terminates : (n : Nat) β†’ n / 2 < n.succ | 0 => by decide | 1 => by decide | n+2 => by rw [Nat.div_eq] split Β· rw [Nat.add_sub_self_right] have := pack_loop_terminates n calc n/2 + 1 < Nat.succ n + 1 := Nat.add_le_add_right this 1 _ < Nat.succ (n + 2) := Nat.succ_lt_succ (Nat.succ_lt_succ (Nat.lt_succ_self _)) Β· apply Nat.zero_lt_succ def pack (n: Nat) : List Nat := let rec loop (n : Nat) (acc : Nat) (accs: List Nat) : List Nat := let next (n: Nat) := n / 2; match n with | Nat.zero => List.cons acc accs | n+1 => match evenq n with | true => loop (next n) 0 (List.cons acc accs) | false => loop (next n) (acc+1) accs loop n 0 [] termination_by' invImage (fun ⟨n, _, _⟩ => n) Nat.lt_wfRel decreasing_by simp [invImage, InvImage, Prod.lex, sizeOfWFRel, measure, Nat.lt_wfRel] apply pack_loop_terminates #eval pack 27
a7354b33509c5c370b89da55874a7a46623172db
618003631150032a5676f229d13a079ac875ff77
/archive/imo1988_q6.lean
a40510ad180ea0ce7784045667f0c01a240cbc9f
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
13,812
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.rat.basic import tactic /-! # IMO1988 Q6 and constant descent Vieta jumping Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers could not tackle the question within the given time limit. The problem lead to the introduction of a new proof technique, so called β€œVieta jumping”. In this file we formalise constant descent Vieta jumping, and apply this to prove Q6 of IMO1988. To illustrate the technique, we also prove a similar result. -/ -- open_locale classical local attribute [instance] classical.prop_decidable local attribute [simp] nat.pow_two /-- Constant descent Vieta jumping. This proof technique allows one to prove an arbitrary proposition `claim`, by running a descent argument on a hyperbola `H` in the first quadrant of the plane, under the following conditions: * `hβ‚€` : There exists an integral point `(x,y)` on the hyperbola `H`. * `H_symm` : The hyperbola has a symmetry along the diagonal in the plane. * `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true. * `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true. * `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`, with `x < y` then there exists a β€œsmaller” point on `H`: a point `(x',y')` with `x' < y' ≀ x`. For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate. (In question 6 of IMO1988, where this proof technique was first developped, the predicate `claim` would be `βˆƒ (d : β„•), d ^ 2 = k` for some natural number `k`, and the predicate `H` would be `Ξ» a b, a * a + b * b = (a * b + 1) * k`.) To ensure that the predicate `H` actually describes a hyperbola, the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation. Finally, `H_quad` is the proof obligation that the quadratic equation `(y:β„€) * y - B x * y + C x = 0` describes the same hyperbola as the predicate `H`. For extra flexibility, one must provide a predicate `base` on the integral points in the plane. In the descent step `H_desc` this will give the user the additional assumption that the point `(x,y)` does not lie in this base locus. The user must provide a proof that the proposition `claim` is true if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus. If such a base locus is not necessary, once can simply let it be `Ξ» x y, false`. -/ lemma constant_descent_vieta_jumping (x y : β„•) {claim : Prop} {H : β„• β†’ β„• β†’ Prop} (hβ‚€ : H x y) (B : β„• β†’ β„€) (C : β„• β†’ β„€) (base : β„• β†’ β„• β†’ Prop) (H_quad : βˆ€ {x y}, H x y ↔ (y:β„€) * y - B x * y + C x = 0) (H_symm : βˆ€ {x y}, H x y ↔ H y x) (H_zero : βˆ€ {x}, H x 0 β†’ claim) (H_diag : βˆ€ {x}, H x x β†’ claim) (H_desc : βˆ€ {x y}, 0 < x β†’ x < y β†’ Β¬base x y β†’ H x y β†’ βˆ€ y', y' * y' - B x * y' + C x = 0 β†’ y' = B x - y β†’ y' * y = C x β†’ 0 ≀ y' ∧ y' ≀ x) (H_base : βˆ€ {x y}, H x y β†’ base x y β†’ claim) : claim := begin -- First of all, we may assume that x ≀ y. -- We justify this using H_symm. wlog hxy : x ≀ y, swap, { rw H_symm at hβ‚€, solve_by_elim }, -- In fact, we can easily deal with the case x = y. by_cases x_eq_y : x = y, {subst x_eq_y, exact H_diag hβ‚€}, -- Hence we may assume that x < y. replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y, clear x_eq_y, -- Consider the upper branch of the hyperbola defined by H. let upper_branch : set (β„• Γ— β„•) := {p | H p.1 p.2 ∧ p.1 < p.2}, -- Note that the point p = (x,y) lies on the upper branch. let p : β„• Γ— β„• := ⟨x,y⟩, have hp : p ∈ upper_branch := ⟨hβ‚€, hxy⟩, -- We also consider the exceptional set of solutions (a,b) that satisfy -- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus. let exceptional : set (β„• Γ— β„•) := {p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1) }, -- Let S be the projection of the upper branch on to the y-axis -- after removing the exceptional locus. let S : set β„• := prod.snd '' (upper_branch \ exceptional), -- The strategy is to show that the exceptional locus in nonempty -- by running a descent argument that starts with the given point p = (x,y). -- Our assumptions ensure that we can then prove the claim. suffices exc : exceptional.nonempty, { -- Suppose that there exists an element in the exceptional locus. simp [exceptional, -add_comm, set.nonempty] at exc, -- Let (a,b) be such an element, and consider all the possible cases. rcases exc with ⟨a, b, hH, hb⟩, rcases hb with _|rfl|rfl|hB|hB, -- The first three cases are rather easy to solve. { solve_by_elim }, { rw H_symm at hH, solve_by_elim }, { solve_by_elim }, -- The final two cases are very similar. all_goals { -- Consider the quadratic equation that (a,b) satisfies. rw H_quad at hH, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hVβ‚‚βŸ©, -- By substitutions we find that b = 0 or b = a. simp [hB] at hV₁, subst hV₁, rw [← int.coe_nat_zero] at *, rw ← H_quad at h_root, -- And hence we are done by H_zero and H_diag. solve_by_elim } }, -- To finish the main proof, we need to show that the exceptional locus is nonempty. -- So we assume that the exceptional locus is empty, and work towards dering a contradiction. rw ← set.ne_empty_iff_nonempty, assume exceptional_empty, -- Observe that S is nonempty. have S_nonempty : S.nonempty, { -- It contains the image of p. use p.2, apply set.mem_image_of_mem, -- After all, we assumed that the exceptional locus is empty. rwa [exceptional_empty, set.diff_empty], }, -- We are now set for an infinite descent argument. -- Let m be the smallest element of the nonempty set S. let m : β„• := well_founded.min nat.lt_wf S S_nonempty, have m_mem : m ∈ S := well_founded.min_mem nat.lt_wf S S_nonempty, have m_min : βˆ€ k ∈ S, Β¬ k < m := Ξ» k hk, well_founded.not_lt_min nat.lt_wf S S_nonempty hk, -- It suffices to show that there is point (a,b) with b ∈ S and b < m. suffices hp' : βˆƒ p' : β„• Γ— β„•, p'.2 ∈ S ∧ p'.2 < m, { rcases hp' with ⟨p', p'_mem, p'_small⟩, solve_by_elim }, -- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S -- and that does not lie in the exceptional locus. rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩, -- This means that m_y = m, -- and the conditions H(m_x, m_y) and m_x < m_y are satisfied. simp [exceptional, hHm] at mx_lt_my h_base m_eq, push_neg at h_base, -- Finally, it also means that (m_x, m_y) does not lie in the base locus, -- that m_x β‰  0, m_x β‰  m_y, B(m_x) β‰  m_y, and B(m_x) β‰  m_x + m_y. rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_Bβ‚‚βŸ©, replace hmx : 0 < mx := nat.pos_iff_ne_zero.mpr hmx, -- Consider the quadratic equation that (m_x, m_y) satisfies. have h_quad := hHm, rw H_quad at h_quad, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hVβ‚‚βŸ©, -- No we rewrite Vietas formulas a bit, and apply the descent step. replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁, rw mul_comm at hVβ‚‚, have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hVβ‚‚, -- This means that we may assume that c β‰₯ 0 and c ≀ m_x. cases Hc with c_nonneg c_lt, -- In other words, c is a natural number. lift c to β„• using c_nonneg, -- Recall that we are trying find a point (a,b) such that b ∈ S and b < m. -- We claim that p' = (c, m_x) does the job. let p' : β„• Γ— β„• := ⟨c, mx⟩, use p', -- The second condition is rather easy to check, so we do that first. split, swap, { rwa m_eq at mx_lt_my }, -- Now we need to show that p' projects onto S. In other words, that c ∈ S. -- We do that, by showing that it lies in the upper branch -- (which is sufficient, because we assumed that the exceptional locus is empty). apply set.mem_image_of_mem, rw [exceptional_empty, set.diff_empty], -- Now we are ready to prove that p' = (c, m_x) lies on the upper branch. -- We need to check two conditions: H(c, m_x) and c < m_x. split; dsimp only, { -- The first condition is not so hard. After all, c is the other root of the quadratic equation. rw [H_symm, H_quad], simpa using h_root, }, { -- For the second condition, we note that it suffices to check that c β‰  m_x. suffices hc : c β‰  mx, { refine lt_of_le_of_ne _ hc, exact_mod_cast c_lt, }, -- However, recall that B(m_x) β‰  m_x + m_y. -- If c = m_x, we can prove B(m_x) = m_x + m_y. contrapose! hm_Bβ‚‚, subst c, simp [hV₁], } -- Hence p' = (c, m_x) lies on the upper branch, and we are done. end /--Question 6 of IMO1988. If a and b are two natural numbers such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square.-/ lemma imo1988_q6 {a b : β„•} (h : (a*b+1) ∣ a^2 + b^2) : βˆƒ d, d^2 = (a^2 + b^2)/(a*b + 1) := begin rcases h with ⟨k, hk⟩, rw [hk, nat.mul_div_cancel_left _ (nat.succ_pos (a*b))], simp only [nat.pow_two] at hk, apply constant_descent_vieta_jumping a b hk (Ξ» x, k * x) (Ξ» x, x*x - k) (Ξ» x y, false); clear hk a b, { -- We will now show that the fibres of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, norm_cast, simp, ring, }, { -- Show that the solution set is symmetric in a and b. intros x y, simp [add_comm (x*x), mul_comm x], }, { -- Show that the claim is true if b = 0. suffices : βˆ€ a, a * a = k β†’ βˆƒ d, d * d = k, by simpa, rintros x rfl, use x }, { -- Show that the claim is true if a = b. intros x hx, suffices : k ≀ 1, { rw [nat.le_add_one_iff, nat.le_zero_iff] at this, rcases this with rfl|rfl, { use 0, simp }, { use 1, simp } }, contrapose! hx with k_lt_one, apply ne_of_lt, calc x*x + x*x = x*x * 2 : by rw mul_two ... ≀ x*x * k : nat.mul_le_mul_left (x*x) k_lt_one ... < (x*x + 1) * k : by apply mul_lt_mul; linarith }, { -- Show the descent step. intros x y hx x_lt_y hxky h z h_root hV₁ hVβ‚€, split, { dsimp [-sub_eq_add_neg] at *, have hpos : z*z + x*x > 0, { apply add_pos_of_nonneg_of_pos, { apply mul_self_nonneg }, { apply mul_pos; exact_mod_cast hx }, }, have hzx : z*z + x*x = (z * x + 1) * k, { rw [← sub_eq_zero, ← h_root], ring, }, rw hzx at hpos, replace hpos : z * x + 1 > 0 := pos_of_mul_pos_right hpos (int.coe_zero_le k), replace hpos : z * x β‰₯ 0 := int.le_of_lt_add_one hpos, apply nonneg_of_mul_nonneg_right hpos (by exact_mod_cast hx), }, { contrapose! hVβ‚€ with x_lt_z, apply ne_of_gt, calc z * y > x*x : by apply mul_lt_mul'; linarith ... β‰₯ x*x - k : sub_le_self _ (int.coe_zero_le k) }, }, { -- There is no base case in this application of Vieta jumping. simp }, end /- The following example illustrates the use of constant descent Vieta jumping in the presence of a non-trivial base case. -/ example {a b : β„•} (h : a*b ∣ a^2 + b^2 + 1) : 3*a*b = a^2 + b^2 + 1 := begin rcases h with ⟨k, hk⟩, suffices : k = 3, { simp * at *, ring, }, simp only [nat.pow_two] at hk, apply constant_descent_vieta_jumping a b hk (Ξ» x, k * x) (Ξ» x, x*x + 1) (Ξ» x y, x ≀ 1); clear hk a b, { -- We will now show that the fibres of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, simp, ring, }, { -- Show that the solution set is symmetric in a and b. cc }, { -- Show that the claim is true if b = 0. simp }, { -- Show that the claim is true if a = b. intros x hx, have x_sq_dvd : x*x ∣ x*x*k := dvd_mul_right (x*x) k, rw ← hx at x_sq_dvd, obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [nat.dvd_add_self_left, add_assoc] using x_sq_dvd, obtain ⟨rfl,rfl⟩ : x = 1 ∧ y = 1 := by simpa [nat.mul_eq_one_iff] using hy.symm, simpa using hx.symm, }, { -- Show the descent step. intros x y x_lt_y hx h_base h z h_root hV₁ hVβ‚€, split, { have zy_pos : z * y β‰₯ 0, { rw hVβ‚€, exact_mod_cast (nat.zero_le _) }, apply nonneg_of_mul_nonneg_right zy_pos, linarith }, { contrapose! hVβ‚€ with x_lt_z, apply ne_of_gt, push_neg at h_base, calc z * y > x * y : by apply mul_lt_mul_of_pos_right; linarith ... β‰₯ x * (x + 1) : by apply mul_le_mul; linarith ... > x * x + 1 : begin rw [mul_add, mul_one], apply add_lt_add_left, assumption_mod_cast end, } }, { -- Show the base case. intros x y h h_base, obtain rfl|rfl : x = 0 ∨ x = 1 := by rwa [nat.le_add_one_iff, nat.le_zero_iff] at h_base, { simpa using h, }, { simp only [mul_one, one_mul, add_comm, zero_add] at h, have y_dvd : y ∣ y * k := dvd_mul_right y k, rw [← h, ← add_assoc, nat.dvd_add_left (dvd_mul_left y y)] at y_dvd, obtain rfl|rfl : y = 1 ∨ y = 2 := nat.prime_two.2 y y_dvd, all_goals { ring at h, omega } } } end
f70770d4a0899413e70dea2a03436243be4f34a6
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/trunc.hlean
6b92cb49e1d59b18aa1df5b9455c9ee54a12ae50
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,971
hlean
-- Copyright (c) 2015 Jakob von Raumer. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Jakob von Raumer -- Truncation properties of truncatedness import types.pi open truncation sigma sigma.ops pi function eq equiv namespace truncation definition is_contr.sigma_char (A : Type) : (Ξ£ (center : A), Ξ  (a : A), center = a) ≃ (is_contr A) := begin fapply equiv.mk, intro S, apply is_contr.mk, exact S.2, fapply is_equiv.adjointify, intro H, apply sigma.mk, exact (@contr A H), intro H, apply (is_trunc.rec_on H), intro Hint, apply (contr_internal.rec_on Hint), intros (H1, H2), apply idp, intro S, apply (sigma.rec_on S), intros (H1, H2), apply idp, end set_option pp.implicit true definition is_trunc.pi_char (n : trunc_index) (A : Type) : (Ξ  (x y : A), is_trunc n (x = y)) ≃ (is_trunc (n .+1) A) := begin fapply equiv.mk, intro H, apply is_trunc_succ, exact H, fapply is_equiv.adjointify, intros (H, x, y), apply succ_is_trunc, exact H, intro H, apply (is_trunc.rec_on H), intro Hint, apply idp, intro P, exact sorry, end definition is_trunc_is_hprop {n : trunc_index} : Ξ  (A : Type), is_hprop (is_trunc n A) := begin apply (trunc_index.rec_on n), intro A, apply trunc_equiv, apply equiv.to_is_equiv, apply is_contr.sigma_char, apply (@is_hprop.mk), intros, fapply sigma.path, apply x.2, apply (@is_hprop.elim), apply trunc_pi, intro a, apply is_hprop.mk, intros (w, z), assert (H : is_hset A), apply trunc_succ, apply trunc_succ, apply is_contr.mk, exact y.2, fapply (@is_hset.elim A _ _ _ w z), intros (n', IH, A), apply trunc_equiv, apply equiv.to_is_equiv, apply is_trunc.pi_char, apply trunc_pi, intro a, apply trunc_pi, intro b, apply (IH (a = b)), end end truncation
24d8077dca79de66f579426c9ff4f39c7f3d6a72
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/list_vector_overload.lean
49f481620d9e91b22107de6e4b84adcb7d8d6e5b
[ "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
218
lean
import data.list data.examples.vector open list vector nat variables (A : Type) (a b c : A) check [a, b, c] check (#list [a, b, c]) check (#vector [a, b, c]) check ([a, b, c] : vector A _) check ([a, b, c] : list A)
ac682fd6770cf9de9b5afdb1b71d7b0ca5d1102d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/polynomial/dickson.lean
0dd36c85cf213e02b793342dc9ac3851a46471c7
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
10,578
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import ring_theory.polynomial.chebyshev import ring_theory.localization import data.zmod.basic import algebra.char_p.invertible /-! # Dickson polynomials The (generalised) Dickson polynomials are a family of polynomials indexed by `β„• Γ— β„•`, with coefficients in a commutative ring `R` depending on an element `a∈R`. More precisely, the they satisfy the recursion `dickson k a (n + 2) = X * (dickson k a n + 1) - a * (dickson k a n)` with starting values `dickson k a 0 = 3 - k` and `dickson k a 1 = X`. In the literature, `dickson k a n` is called the `n`-th Dickson polynomial of the `k`-th kind associated to the parameter `a : R`. They are closely related to the Chebyshev polynomials in the case that `a=1`. When `a=0` they are just the family of monomials `X ^ n`. ## Main definition * `polynomial.dickson`: the generalised Dickson polynomials. ## Main statements * `polynomial.dickson_one_one_mul`, the `(m * n)`-th Dickson polynomial of the first kind for parameter `1 : R` is the composition of the `m`-th and `n`-th Dickson polynomials of the first kind for `1 : R`. * `polynomial.dickson_one_one_char_p`, for a prime number `p`, the `p`-th Dickson polynomial of the first kind associated to parameter `1 : R` is congruent to `X ^ p` modulo `p`. ## References * [R. Lidl, G. L. Mullen and G. Turnwald, _Dickson polynomials_][MR1237403] ## TODO * Redefine `dickson` in terms of `linear_recurrence`. * Show that `dickson 2 1` is equal to the characteristic polynomial of the adjacency matrix of a type A Dynkin diagram. * Prove that the adjacency matrices of simply laced Dynkin diagrams are precisely the adjacency matrices of simple connected graphs which annihilate `dickson 2 1`. -/ noncomputable theory namespace polynomial variables {R S : Type*} [comm_ring R] [comm_ring S] (k : β„•) (a : R) /-- `dickson` is the `n`the (generalised) Dickson polynomial of the `k`-th kind associated to the element `a ∈ R`. -/ noncomputable def dickson : β„• β†’ polynomial R | 0 := 3 - k | 1 := X | (n + 2) := X * dickson (n + 1) - (C a) * dickson n @[simp] lemma dickson_zero : dickson k a 0 = 3 - k := rfl @[simp] lemma dickson_one : dickson k a 1 = X := rfl lemma dickson_two : dickson k a 2 = X ^ 2 - C a * (3 - k) := by simp only [dickson, sq] @[simp] lemma dickson_add_two (n : β„•) : dickson k a (n + 2) = X * dickson k a (n + 1) - C a * dickson k a n := by rw dickson lemma dickson_of_two_le {n : β„•} (h : 2 ≀ n) : dickson k a n = X * dickson k a (n - 1) - C a * dickson k a (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact dickson_add_two k a n end variables {R S k a} lemma map_dickson (f : R β†’+* S) : βˆ€ (n : β„•), map f (dickson k a n) = dickson k (f a) n | 0 := by simp only [dickson_zero, map_sub, polynomial.map_nat_cast, bit1, bit0, map_add, map_one] | 1 := by simp only [dickson_one, map_X] | (n + 2) := begin simp only [dickson_add_two, map_sub, map_mul, map_X, map_C], rw [map_dickson, map_dickson] end variable {R} @[simp] lemma dickson_two_zero : βˆ€ (n : β„•), dickson 2 (0 : R) n = X ^ n | 0 := by { simp only [dickson_zero, pow_zero], norm_num } | 1 := by simp only [dickson_one, pow_one] | (n + 2) := begin simp only [dickson_add_two, C_0, zero_mul, sub_zero], rw [dickson_two_zero, pow_add X (n + 1) 1, mul_comm, pow_one] end section dickson /-! ### A Lambda structure on `polynomial β„€` Mathlib doesn't currently know what a Lambda ring is. But once it does, we can endow `polynomial β„€` with a Lambda structure in terms of the `dickson 1 1` polynomials defined below. There is exactly one other Lambda structure on `polynomial β„€` in terms of binomial polynomials. -/ variables {R} lemma dickson_one_one_eval_add_inv (x y : R) (h : x * y = 1) : βˆ€ n, (dickson 1 (1 : R) n).eval (x + y) = x ^ n + y ^ n | 0 := by { simp only [bit0, eval_one, eval_add, pow_zero, dickson_zero], norm_num } | 1 := by simp only [eval_X, dickson_one, pow_one] | (n + 2) := begin simp only [eval_sub, eval_mul, dickson_one_one_eval_add_inv, eval_X, dickson_add_two, C_1, eval_one], conv_lhs { simp only [pow_succ, add_mul, mul_add, h, ← mul_assoc, mul_comm y x, one_mul] }, ring_exp end variables (R) lemma dickson_one_one_eq_chebyshev_T [invertible (2 : R)] : βˆ€ n, dickson 1 (1 : R) n = 2 * (chebyshev.T R n).comp (C (β…Ÿ2) * X) | 0 := by { simp only [chebyshev.T_zero, mul_one, one_comp, dickson_zero], norm_num } | 1 := by rw [dickson_one, chebyshev.T_one, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul, mul_inv_of_self, C_1, one_mul] | (n + 2) := begin simp only [dickson_add_two, chebyshev.T_add_two, dickson_one_one_eq_chebyshev_T (n + 1), dickson_one_one_eq_chebyshev_T n, sub_comp, mul_comp, add_comp, X_comp, bit0_comp, one_comp], simp only [← C_1, ← C_bit0, ← mul_assoc, ← C_mul, mul_inv_of_self], rw [C_1, one_mul], ring end lemma chebyshev_T_eq_dickson_one_one [invertible (2 : R)] (n : β„•) : chebyshev.T R n = C (β…Ÿ2) * (dickson 1 1 n).comp (2 * X) := begin rw dickson_one_one_eq_chebyshev_T, simp only [comp_assoc, mul_comp, C_comp, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul], rw [inv_of_mul_self, C_1, one_mul, one_mul, comp_X] end /-- The `(m * n)`-th Dickson polynomial of the first kind is the composition of the `m`-th and `n`-th. -/ lemma dickson_one_one_mul (m n : β„•) : dickson 1 (1 : R) (m * n) = (dickson 1 1 m).comp (dickson 1 1 n) := begin have h : (1 : R) = int.cast_ring_hom R (1), simp only [ring_hom.eq_int_cast, int.cast_one], rw h, simp only [← map_dickson (int.cast_ring_hom R), ← map_comp], congr' 1, apply map_injective (int.cast_ring_hom β„š) int.cast_injective, simp only [map_dickson, map_comp, ring_hom.eq_int_cast, int.cast_one, dickson_one_one_eq_chebyshev_T, chebyshev.T_mul, two_mul, ← add_comp], simp only [← two_mul, ← comp_assoc], apply evalβ‚‚_congr rfl rfl, rw [comp_assoc], apply evalβ‚‚_congr rfl _ rfl, rw [mul_comp, C_comp, X_comp, ← mul_assoc, ← C_1, ← C_bit0, ← C_mul, inv_of_mul_self, C_1, one_mul] end lemma dickson_one_one_comp_comm (m n : β„•) : (dickson 1 (1 : R) m).comp (dickson 1 1 n) = (dickson 1 1 n).comp (dickson 1 1 m) := by rw [← dickson_one_one_mul, mul_comm, dickson_one_one_mul] lemma dickson_one_one_zmod_p (p : β„•) [fact p.prime] : dickson 1 (1 : zmod p) p = X ^ p := begin -- Recall that `dickson_eval_add_inv` characterises `dickson 1 1 p` -- as a polynomial that maps `x + x⁻¹` to `x ^ p + (x⁻¹) ^ p`. -- Since `X ^ p` also satisfies this property in characteristic `p`, -- we can use a variant on `polynomial.funext` to conclude that these polynomials are equal. -- For this argument, we need an arbitrary infinite field of characteristic `p`. obtain ⟨K, _, _, H⟩ : βˆƒ (K : Type) (_ : field K), by exactI βˆƒ (_ : char_p K p), infinite K, { let K := fraction_ring (polynomial (zmod p)), let f : zmod p β†’+* K := (algebra_map _ (fraction_ring _)).comp C, haveI : char_p K p, { rw ← f.char_p_iff_char_p, apply_instance }, haveI : infinite K := infinite.of_injective (algebra_map (polynomial (zmod p)) (fraction_ring (polynomial (zmod p)))) (is_fraction_ring.injective _ _), refine ⟨K, _, _, _⟩; apply_instance }, resetI, apply map_injective (zmod.cast_hom (dvd_refl p) K) (ring_hom.injective _), rw [map_dickson, polynomial.map_pow, map_X], apply eq_of_infinite_eval_eq, -- The two polynomials agree on all `x` of the form `x = y + y⁻¹`. apply @set.infinite.mono _ {x : K | βˆƒ y, x = y + y⁻¹ ∧ y β‰  0}, { rintro _ ⟨x, rfl, hx⟩, simp only [eval_X, eval_pow, set.mem_set_of_eq, @add_pow_char K _ p, dickson_one_one_eval_add_inv _ _ (mul_inv_cancel hx), inv_powβ‚€, zmod.cast_hom_apply, zmod.cast_one'] }, -- Now we need to show that the set of such `x` is infinite. -- If the set is finite, then we will show that `K` is also finite. { intro h, rw ← set.infinite_univ_iff at H, apply H, -- To each `x` of the form `x = y + y⁻¹` -- we `bind` the set of `y` that solve the equation `x = y + y⁻¹`. -- For every `x`, that set is finite (since it is governed by a quadratic equation). -- For the moment, we claim that all these sets together cover `K`. suffices : (set.univ : set K) = {x : K | βˆƒ (y : K), x = y + y⁻¹ ∧ y β‰  0} >>= (Ξ» x, {y | x = y + y⁻¹ ∨ y = 0}), { rw this, clear this, refine h.bUnion (Ξ» x hx, _), -- The following quadratic polynomial has as solutions the `y` for which `x = y + y⁻¹`. let Ο† : polynomial K := X ^ 2 - C x * X + 1, have hΟ† : Ο† β‰  0, { intro H, have : Ο†.eval 0 = 0, by rw [H, eval_zero], simpa [eval_X, eval_one, eval_pow, eval_sub, sub_zero, eval_add, eval_mul, mul_zero, sq, zero_add, one_ne_zero] }, classical, convert (Ο†.roots βˆͺ {0}).to_finset.finite_to_set using 1, ext1 y, simp only [multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe, multiset.mem_union, mem_roots hΟ†, is_root, eval_add, eval_sub, eval_pow, eval_mul, eval_X, eval_C, eval_one, multiset.mem_singleton], by_cases hy : y = 0, { simp only [hy, eq_self_iff_true, or_true] }, apply or_congr _ iff.rfl, rw [← mul_left_inj' hy, eq_comm, ← sub_eq_zero, add_mul, inv_mul_cancel hy], apply eq_iff_eq_cancel_right.mpr, ring }, -- Finally, we prove the claim that our finite union of finite sets covers all of `K`. { apply (set.eq_univ_of_forall _).symm, intro x, simp only [exists_prop, set.mem_Union, set.bind_def, ne.def, set.mem_set_of_eq], by_cases hx : x = 0, { simp only [hx, and_true, eq_self_iff_true, inv_zero, or_true], exact ⟨_, 1, rfl, one_ne_zero⟩ }, { simp only [hx, or_false, exists_eq_right], exact ⟨_, rfl, hx⟩ } } } end lemma dickson_one_one_char_p (p : β„•) [fact p.prime] [char_p R p] : dickson 1 (1 : R) p = X ^ p := begin have h : (1 : R) = zmod.cast_hom (dvd_refl p) R (1), simp only [zmod.cast_hom_apply, zmod.cast_one'], rw [h, ← map_dickson (zmod.cast_hom (dvd_refl p) R), dickson_one_one_zmod_p, polynomial.map_pow, map_X] end end dickson end polynomial
3a2b1880fdad479464faeb8d59f56fd0ef8f312c
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/char_zero.lean
647f0e2f043a0da84c7f9f542b5ba4b3dd2aa10d
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
3,591
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import algebra.field import data.nat.cast import tactic.wlog /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (Ξ± : Type*) [add_monoid Ξ±] [has_one Ξ±] : Prop := (cast_injective : function.injective (coe : β„• β†’ Ξ±)) theorem char_zero_of_inj_zero {Ξ± : Type*} [add_monoid Ξ±] [has_one Ξ±] (add_left_cancel : βˆ€ a b c : Ξ±, a + b = a + c β†’ b = c) (H : βˆ€ n:β„•, (n:Ξ±) = 0 β†’ n = 0) : char_zero Ξ± := ⟨λ m n, begin assume h, wlog hle : m ≀ n, cases nat.le.dest hle with k e, suffices : k = 0, by rw [← e, this, add_zero], apply H, apply add_left_cancel n, rw [← h, ← nat.cast_add, e, add_zero, h] end⟩ -- We have no `left_cancel_add_monoid`, so we restate it for `add_group` -- and `ordered_cancel_comm_monoid`. theorem add_group.char_zero_of_inj_zero {Ξ± : Type*} [add_group Ξ±] [has_one Ξ±] (H : βˆ€ n:β„•, (n:Ξ±) = 0 β†’ n = 0) : char_zero Ξ± := char_zero_of_inj_zero (@add_left_cancel _ _) H theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {Ξ± : Type*} [ordered_cancel_add_comm_monoid Ξ±] [has_one Ξ±] (H : βˆ€ n:β„•, (n:Ξ±) = 0 β†’ n = 0) : char_zero Ξ± := char_zero_of_inj_zero (@add_left_cancel _ _) H @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {Ξ± : Type*} [linear_ordered_semiring Ξ±] : char_zero Ξ± := ordered_cancel_comm_monoid.char_zero_of_inj_zero $ Ξ» n h, nat.eq_zero_of_le_zero $ (@nat.cast_le Ξ± _ _ _).1 (le_of_eq h) namespace nat variables {Ξ± : Type*} [add_monoid Ξ±] [has_one Ξ±] [char_zero Ξ±] theorem cast_injective : function.injective (coe : β„• β†’ Ξ±) := char_zero.cast_injective @[simp, norm_cast] theorem cast_inj {m n : β„•} : (m : Ξ±) = n ↔ m = n := cast_injective.eq_iff @[simp, norm_cast] theorem cast_eq_zero {n : β„•} : (n : Ξ±) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[norm_cast] theorem cast_ne_zero {n : β„•} : (n : Ξ±) β‰  0 ↔ n β‰  0 := not_congr cast_eq_zero lemma cast_add_one_ne_zero (n : β„•) : (n + 1 : Ξ±) β‰  0 := by exact_mod_cast n.succ_ne_zero @[simp, norm_cast] theorem cast_dvd_char_zero {Ξ± : Type*} [field Ξ±] [char_zero Ξ±] {m n : β„•} (n_dvd : n ∣ m) : ((m / n : β„•) : Ξ±) = m / n := begin by_cases hn : n = 0, { subst hn, simp }, { exact cast_dvd n_dvd (cast_ne_zero.mpr hn), }, end end nat @[field_simps] lemma two_ne_zero' {Ξ± : Type*} [add_monoid Ξ±] [has_one Ξ±] [char_zero Ξ±] : (2:Ξ±) β‰  0 := have ((2:β„•):Ξ±) β‰  0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {Ξ± : Type*} [semiring Ξ±] [no_zero_divisors Ξ±] [char_zero Ξ±] lemma add_self_eq_zero {a : Ξ±} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : Ξ±} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {Ξ± : Type*} [division_ring Ξ±] [char_zero Ξ±] @[simp] lemma half_add_self (a : Ξ±) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : Ξ±) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : Ξ±) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : Ξ±) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end
ff98453bb3ecb55fecfda33222bbc8025341c5ba
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/generalize.lean
566463a8bea57939b22e6f6769e3205240ec4caf
[ "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
650
lean
new_frontend theorem tst0 (x : Nat) : x + 0 = x + 0 := by { generalize x + 0 = y; exact (Eq.refl y) } theorem tst1 (x : Nat) : x + 0 = x + 0 := by { generalize h : x + 0 = y; exact (Eq.refl y) } theorem tst2 (x y w : Nat) (h : y = w) : (x + x) + w = (x + x) + y := by { generalize h' : x + x = z; subst y; exact Eq.refl $ z + w } theorem tst3 (x y w : Nat) (h : x + x = y) : (x + x) + (x+x) = (x + x) + y := by { generalize h' : x + x = z; subst z; subst y; exact rfl } theorem tst4 (x y w : Nat) (h : y = w) : (x + x) + w = (x + x) + y := by { generalize h' : x + y = z; -- just add equality subst h; exact rfl }
61ef25829a6cc24488cecd2ad3db9986f37ff618
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/reverse.lean
38373d31395af4aa056d969f047059cfba077814
[ "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
12,914
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.degree.trailing_degree import data.polynomial.erase_lead import data.polynomial.eval /-! # Reverse of a univariate polynomial The main definition is `reverse`. Applying `reverse` to a polynomial `f : R[X]` produces the polynomial with a reversed list of coefficients, equivalent to `X^f.nat_degree * f(1/X)`. The main result is that `reverse (f * g) = reverse f * reverse g`, provided the leading coefficients of `f` and `g` do not multiply to zero. -/ namespace polynomial open polynomial finsupp finset open_locale classical polynomial section semiring variables {R : Type*} [semiring R] {f : R[X]} /-- If `i ≀ N`, then `rev_at_fun N i` returns `N - i`, otherwise it returns `i`. This is the map used by the embedding `rev_at`. -/ def rev_at_fun (N i : β„•) : β„• := ite (i ≀ N) (N-i) i lemma rev_at_fun_invol {N i : β„•} : rev_at_fun N (rev_at_fun N i) = i := begin unfold rev_at_fun, split_ifs with h j, { exact tsub_tsub_cancel_of_le h, }, { exfalso, apply j, exact nat.sub_le N i, }, { refl, }, end lemma rev_at_fun_inj {N : β„•} : function.injective (rev_at_fun N) := begin intros a b hab, rw [← @rev_at_fun_invol N a, hab, rev_at_fun_invol], end /-- If `i ≀ N`, then `rev_at N i` returns `N - i`, otherwise it returns `i`. Essentially, this embedding is only used for `i ≀ N`. The advantage of `rev_at N i` over `N - i` is that `rev_at` is an involution. -/ def rev_at (N : β„•) : function.embedding β„• β„• := { to_fun := Ξ» i , (ite (i ≀ N) (N-i) i), inj' := rev_at_fun_inj } /-- We prefer to use the bundled `rev_at` over unbundled `rev_at_fun`. -/ @[simp] lemma rev_at_fun_eq (N i : β„•) : rev_at_fun N i = rev_at N i := rfl @[simp] lemma rev_at_invol {N i : β„•} : (rev_at N) (rev_at N i) = i := rev_at_fun_invol @[simp] lemma rev_at_le {N i : β„•} (H : i ≀ N) : rev_at N i = N - i := if_pos H lemma rev_at_add {N O n o : β„•} (hn : n ≀ N) (ho : o ≀ O) : rev_at (N + O) (n + o) = rev_at N n + rev_at O o := begin rcases nat.le.dest hn with ⟨n', rfl⟩, rcases nat.le.dest ho with ⟨o', rfl⟩, repeat { rw rev_at_le (le_add_right rfl.le) }, rw [add_assoc, add_left_comm n' o, ← add_assoc, rev_at_le (le_add_right rfl.le)], repeat {rw add_tsub_cancel_left}, end @[simp] lemma rev_at_zero (N : β„•) : rev_at N 0 = N := by simp [rev_at] /-- `reflect N f` is the polynomial such that `(reflect N f).coeff i = f.coeff (rev_at N i)`. In other words, the terms with exponent `[0, ..., N]` now have exponent `[N, ..., 0]`. In practice, `reflect` is only used when `N` is at least as large as the degree of `f`. Eventually, it will be used with `N` exactly equal to the degree of `f`. -/ noncomputable def reflect (N : β„•) : R[X] β†’ R[X] | ⟨f⟩ := ⟨finsupp.emb_domain (rev_at N) f⟩ lemma reflect_support (N : β„•) (f : R[X]) : (reflect N f).support = image (rev_at N) f.support := begin rcases f, ext1, rw [reflect, mem_image, support, support, support_emb_domain, mem_map], end @[simp] lemma coeff_reflect (N : β„•) (f : R[X]) (i : β„•) : coeff (reflect N f) i = f.coeff (rev_at N i) := begin rcases f, simp only [reflect, coeff], calc finsupp.emb_domain (rev_at N) f i = finsupp.emb_domain (rev_at N) f (rev_at N (rev_at N i)) : by rw rev_at_invol ... = f (rev_at N i) : finsupp.emb_domain_apply _ _ _ end @[simp] lemma reflect_zero {N : β„•} : reflect N (0 : R[X]) = 0 := rfl @[simp] lemma reflect_eq_zero_iff {N : β„•} {f : R[X]} : reflect N (f : R[X]) = 0 ↔ f = 0 := by { rcases f, simp [reflect] } @[simp] lemma reflect_add (f g : R[X]) (N : β„•) : reflect N (f + g) = reflect N f + reflect N g := by { ext, simp only [coeff_add, coeff_reflect], } @[simp] lemma reflect_C_mul (f : R[X]) (r : R) (N : β„•) : reflect N (C r * f) = C r * (reflect N f) := by { ext, simp only [coeff_reflect, coeff_C_mul], } @[simp] lemma reflect_C_mul_X_pow (N n : β„•) {c : R} : reflect N (C c * X ^ n) = C c * X ^ (rev_at N n) := begin ext, rw [reflect_C_mul, coeff_C_mul, coeff_C_mul, coeff_X_pow, coeff_reflect], split_ifs with h j, { rw [h, rev_at_invol, coeff_X_pow_self], }, { rw [not_mem_support_iff.mp], intro a, rw [← one_mul (X ^ n), ← C_1] at a, apply h, rw [← (mem_support_C_mul_X_pow a), rev_at_invol], }, end @[simp] lemma reflect_C (r : R) (N : β„•) : reflect N (C r) = C r * X ^ N := by conv_lhs { rw [← mul_one (C r), ← pow_zero X, reflect_C_mul_X_pow, rev_at_zero] } @[simp] lemma reflect_monomial (N n : β„•) : reflect N ((X : R[X]) ^ n) = X ^ (rev_at N n) := by rw [← one_mul (X ^ n), ← one_mul (X ^ (rev_at N n)), ← C_1, reflect_C_mul_X_pow] lemma reflect_mul_induction (cf cg : β„•) : βˆ€ N O : β„•, βˆ€ f g : R[X], f.support.card ≀ cf.succ β†’ g.support.card ≀ cg.succ β†’ f.nat_degree ≀ N β†’ g.nat_degree ≀ O β†’ (reflect (N + O) (f * g)) = (reflect N f) * (reflect O g) := begin induction cf with cf hcf, --first induction (left): base case { induction cg with cg hcg, -- second induction (right): base case { intros N O f g Cf Cg Nf Og, rw [← C_mul_X_pow_eq_self Cf, ← C_mul_X_pow_eq_self Cg], simp_rw [mul_assoc, X_pow_mul, mul_assoc, ← pow_add (X : R[X]), reflect_C_mul, reflect_monomial, add_comm, rev_at_add Nf Og, mul_assoc, X_pow_mul, mul_assoc, ← pow_add (X : R[X]), add_comm], }, -- second induction (right): induction step { intros N O f g Cf Cg Nf Og, by_cases g0 : g = 0, { rw [g0, reflect_zero, mul_zero, mul_zero, reflect_zero], }, rw [← erase_lead_add_C_mul_X_pow g, mul_add, reflect_add, reflect_add, mul_add, hcg, hcg]; try { assumption }, { exact le_add_left card_support_C_mul_X_pow_le_one }, { exact (le_trans (nat_degree_C_mul_X_pow_le g.leading_coeff g.nat_degree) Og) }, { exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cg (erase_lead_support_card_lt g0)) }, { exact le_trans erase_lead_nat_degree_le_aux Og } } }, --first induction (left): induction step { intros N O f g Cf Cg Nf Og, by_cases f0 : f = 0, { rw [f0, reflect_zero, zero_mul, zero_mul, reflect_zero], }, rw [← erase_lead_add_C_mul_X_pow f, add_mul, reflect_add, reflect_add, add_mul, hcf, hcf]; try { assumption }, { exact le_add_left card_support_C_mul_X_pow_le_one }, { exact (le_trans (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree) Nf) }, { exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cf (erase_lead_support_card_lt f0)) }, { exact (le_trans erase_lead_nat_degree_le_aux Nf) } } end @[simp] theorem reflect_mul (f g : R[X]) {F G : β„•} (Ff : f.nat_degree ≀ F) (Gg : g.nat_degree ≀ G) : reflect (F + G) (f * g) = reflect F f * reflect G g := reflect_mul_induction _ _ F G f g f.support.card.le_succ g.support.card.le_succ Ff Gg section evalβ‚‚ variables {S : Type*} [comm_semiring S] lemma evalβ‚‚_reflect_mul_pow (i : R β†’+* S) (x : S) [invertible x] (N : β„•) (f : R[X]) (hf : f.nat_degree ≀ N) : evalβ‚‚ i (β…Ÿx) (reflect N f) * x ^ N = evalβ‚‚ i x f := begin refine induction_with_nat_degree_le (Ξ» f, evalβ‚‚ i (β…Ÿx) (reflect N f) * x ^ N = evalβ‚‚ i x f) _ _ _ _ f hf, { simp }, { intros n r hr0 hnN, simp only [rev_at_le hnN, reflect_C_mul_X_pow, evalβ‚‚_X_pow, evalβ‚‚_C, evalβ‚‚_mul], conv in (x ^ N) { rw [← nat.sub_add_cancel hnN] }, rw [pow_add, ← mul_assoc, mul_assoc (i r), ← mul_pow, inv_of_mul_self, one_pow, mul_one] }, { intros, simp [*, add_mul] } end lemma evalβ‚‚_reflect_eq_zero_iff (i : R β†’+* S) (x : S) [invertible x] (N : β„•) (f : R[X]) (hf : f.nat_degree ≀ N) : evalβ‚‚ i (β…Ÿx) (reflect N f) = 0 ↔ evalβ‚‚ i x f = 0 := begin conv_rhs { rw [← evalβ‚‚_reflect_mul_pow i x N f hf] }, split, { intro h, rw [h, zero_mul] }, { intro h, rw [← mul_one (evalβ‚‚ i (β…Ÿx) _), ← one_pow N, ← mul_inv_of_self x, mul_pow, ← mul_assoc, h, zero_mul] } end end evalβ‚‚ /-- The reverse of a polynomial f is the polynomial obtained by "reading f backwards". Even though this is not the actual definition, reverse f = f (1/X) * X ^ f.nat_degree. -/ noncomputable def reverse (f : R[X]) : R[X] := reflect f.nat_degree f lemma coeff_reverse (f : R[X]) (n : β„•) : f.reverse.coeff n = f.coeff (rev_at f.nat_degree n) := by rw [reverse, coeff_reflect] @[simp] lemma coeff_zero_reverse (f : R[X]) : coeff (reverse f) 0 = leading_coeff f := by rw [coeff_reverse, rev_at_le (zero_le f.nat_degree), tsub_zero, leading_coeff] @[simp] lemma reverse_zero : reverse (0 : R[X]) = 0 := rfl @[simp] lemma reverse_eq_zero : f.reverse = 0 ↔ f = 0 := by simp [reverse] lemma reverse_nat_degree_le (f : R[X]) : f.reverse.nat_degree ≀ f.nat_degree := begin rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero], intros n hn, rw with_bot.coe_lt_coe at hn, rw [coeff_reverse, rev_at, function.embedding.coe_fn_mk, if_neg (not_le_of_gt hn), coeff_eq_zero_of_nat_degree_lt hn], end lemma nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree (f : R[X]) : f.nat_degree = f.reverse.nat_degree + f.nat_trailing_degree := begin by_cases hf : f = 0, { rw [hf, reverse_zero, nat_degree_zero, nat_trailing_degree_zero] }, apply le_antisymm, { refine tsub_le_iff_right.mp _, apply le_nat_degree_of_ne_zero, rw [reverse, coeff_reflect, ←rev_at_le f.nat_trailing_degree_le_nat_degree, rev_at_invol], exact trailing_coeff_nonzero_iff_nonzero.mpr hf }, { rw ← le_tsub_iff_left f.reverse_nat_degree_le, apply nat_trailing_degree_le_of_ne_zero, have key := mt leading_coeff_eq_zero.mp (mt reverse_eq_zero.mp hf), rwa [leading_coeff, coeff_reverse, rev_at_le f.reverse_nat_degree_le] at key }, end lemma reverse_nat_degree (f : R[X]) : f.reverse.nat_degree = f.nat_degree - f.nat_trailing_degree := by rw [f.nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree, add_tsub_cancel_right] lemma reverse_leading_coeff (f : R[X]) : f.reverse.leading_coeff = f.trailing_coeff := by rw [leading_coeff, reverse_nat_degree, ←rev_at_le f.nat_trailing_degree_le_nat_degree, coeff_reverse, rev_at_invol, trailing_coeff] lemma reverse_nat_trailing_degree (f : R[X]) : f.reverse.nat_trailing_degree = 0 := begin by_cases hf : f = 0, { rw [hf, reverse_zero, nat_trailing_degree_zero] }, { rw ← nat.le_zero_iff, apply nat_trailing_degree_le_of_ne_zero, rw [coeff_zero_reverse], exact mt leading_coeff_eq_zero.mp hf }, end lemma reverse_trailing_coeff (f : R[X]) : f.reverse.trailing_coeff = f.leading_coeff := by rw [trailing_coeff, reverse_nat_trailing_degree, coeff_zero_reverse] theorem reverse_mul {f g : R[X]} (fg : f.leading_coeff * g.leading_coeff β‰  0) : reverse (f * g) = reverse f * reverse g := begin unfold reverse, rw [nat_degree_mul' fg, reflect_mul f g rfl.le rfl.le], end @[simp] lemma reverse_mul_of_domain {R : Type*} [ring R] [no_zero_divisors R] (f g : R[X]) : reverse (f * g) = reverse f * reverse g := begin by_cases f0 : f=0, { simp only [f0, zero_mul, reverse_zero], }, by_cases g0 : g=0, { rw [g0, mul_zero, reverse_zero, mul_zero], }, simp [reverse_mul, *], end lemma trailing_coeff_mul {R : Type*} [ring R] [no_zero_divisors R] (p q : R[X]) : (p * q).trailing_coeff = p.trailing_coeff * q.trailing_coeff := by rw [←reverse_leading_coeff, reverse_mul_of_domain, leading_coeff_mul, reverse_leading_coeff, reverse_leading_coeff] @[simp] lemma coeff_one_reverse (f : R[X]) : coeff (reverse f) 1 = next_coeff f := begin rw [coeff_reverse, next_coeff], split_ifs with hf, { have : coeff f 1 = 0 := coeff_eq_zero_of_nat_degree_lt (by simp only [hf, zero_lt_one]), simp [*, rev_at] }, { rw rev_at_le, exact nat.succ_le_iff.2 (pos_iff_ne_zero.2 hf) } end section evalβ‚‚ variables {S : Type*} [comm_semiring S] lemma evalβ‚‚_reverse_mul_pow (i : R β†’+* S) (x : S) [invertible x] (f : R[X]) : evalβ‚‚ i (β…Ÿx) (reverse f) * x ^ f.nat_degree = evalβ‚‚ i x f := evalβ‚‚_reflect_mul_pow i _ _ f le_rfl @[simp] lemma evalβ‚‚_reverse_eq_zero_iff (i : R β†’+* S) (x : S) [invertible x] (f : R[X]) : evalβ‚‚ i (β…Ÿx) (reverse f) = 0 ↔ evalβ‚‚ i x f = 0 := evalβ‚‚_reflect_eq_zero_iff i x _ _ le_rfl end evalβ‚‚ end semiring section ring variables {R : Type*} [ring R] @[simp] lemma reflect_neg (f : R[X]) (N : β„•) : reflect N (- f) = - reflect N f := by rw [neg_eq_neg_one_mul, ←C_1, ←C_neg, reflect_C_mul, C_neg, C_1, ←neg_eq_neg_one_mul] @[simp] lemma reflect_sub (f g : R[X]) (N : β„•) : reflect N (f - g) = reflect N f - reflect N g := by rw [sub_eq_add_neg, sub_eq_add_neg, reflect_add, reflect_neg] @[simp] lemma reverse_neg (f : R[X]) : reverse (- f) = - reverse f := by rw [reverse, reverse, reflect_neg, nat_degree_neg] end ring end polynomial
c3b139097f2326c4d0a15eb3d5ff2280906778f1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/integration.lean
104779460cd3ed54d24fcd3d9d68158d4385fc65
[ "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,943
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Martin Zinkevich, Vincent Beffara -/ import measure_theory.integral.set_integral import probability.independence.basic /-! # Integration in Probability Theory > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Integration results for independent random variables. Specifically, for two independent random variables X and Y over the extended non-negative reals, `E[X * Y] = E[X] * E[Y]`, and similar results. ## Implementation notes Many lemmas in this file take two arguments of the same typeclass. It is worth remembering that lean will always pick the later typeclass in this situation, and does not care whether the arguments are `[]`, `{}`, or `()`. All of these use the `measurable_space` `M2` to define `ΞΌ`: ```lean example {M1 : measurable_space Ξ©} [M2 : measurable_space Ξ©] {ΞΌ : measure Ξ©} : sorry := sorry example [M1 : measurable_space Ξ©] {M2 : measurable_space Ξ©} {ΞΌ : measure Ξ©} : sorry := sorry ``` -/ noncomputable theory open set measure_theory open_locale ennreal measure_theory variables {Ξ© : Type*} {mΞ© : measurable_space Ξ©} {ΞΌ : measure Ξ©} {f g : Ξ© β†’ ℝβ‰₯0∞} {X Y : Ξ© β†’ ℝ} namespace probability_theory /-- If a random variable `f` in `ℝβ‰₯0∞` is independent of an event `T`, then if you restrict the random variable to `T`, then `E[f * indicator T c 0]=E[f] * E[indicator T c 0]`. It is useful for `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space`. -/ lemma lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator {Mf mΞ© : measurable_space Ξ©} {ΞΌ : measure Ξ©} (hMf : Mf ≀ mΞ©) (c : ℝβ‰₯0∞) {T : set Ξ©} (h_meas_T : measurable_set T) (h_ind : indep_sets {s | measurable_set[Mf] s} {T} ΞΌ) (h_meas_f : measurable[Mf] f) : ∫⁻ Ο‰, f Ο‰ * T.indicator (Ξ» _, c) Ο‰ βˆ‚ΞΌ = ∫⁻ Ο‰, f Ο‰ βˆ‚ΞΌ * ∫⁻ Ο‰, T.indicator (Ξ» _, c) Ο‰ βˆ‚ΞΌ := begin revert f, have h_mul_indicator : βˆ€ g, measurable g β†’ measurable (Ξ» a, g a * T.indicator (Ξ» x, c) a), from Ξ» g h_mg, h_mg.mul (measurable_const.indicator h_meas_T), apply measurable.ennreal_induction, { intros c' s' h_meas_s', simp_rw [← inter_indicator_mul], rw [lintegral_indicator _ (measurable_set.inter (hMf _ h_meas_s') (h_meas_T)), lintegral_indicator _ (hMf _ h_meas_s'), lintegral_indicator _ h_meas_T], simp only [measurable_const, lintegral_const, univ_inter, lintegral_const_mul, measurable_set.univ, measure.restrict_apply], ring_nf, congr, rw [mul_comm, h_ind s' T h_meas_s' (set.mem_singleton _)], }, { intros f' g h_univ h_meas_f' h_meas_g h_ind_f' h_ind_g, have h_measM_f' : measurable f', from h_meas_f'.mono hMf le_rfl, have h_measM_g : measurable g, from h_meas_g.mono hMf le_rfl, simp_rw [pi.add_apply, right_distrib], rw [lintegral_add_left (h_mul_indicator _ h_measM_f'), lintegral_add_left h_measM_f', right_distrib, h_ind_f', h_ind_g] }, { intros f h_meas_f h_mono_f h_ind_f, have h_measM_f : βˆ€ n, measurable (f n), from Ξ» n, (h_meas_f n).mono hMf le_rfl, simp_rw [ennreal.supr_mul], rw [lintegral_supr h_measM_f h_mono_f, lintegral_supr, ennreal.supr_mul], { simp_rw [← h_ind_f] }, { exact Ξ» n, h_mul_indicator _ (h_measM_f n) }, { exact Ξ» m n h_le a, mul_le_mul_right' (h_mono_f h_le a) _, }, }, end /-- If `f` and `g` are independent random variables with values in `ℝβ‰₯0∞`, then `E[f * g] = E[f] * E[g]`. However, instead of directly using the independence of the random variables, it uses the independence of measurable spaces for the domains of `f` and `g`. This is similar to the sigma-algebra approach to independence. See `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_fn` for a more common variant of the product of independent variables. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space {Mf Mg mΞ© : measurable_space Ξ©} {ΞΌ : measure Ξ©} (hMf : Mf ≀ mΞ©) (hMg : Mg ≀ mΞ©) (h_ind : indep Mf Mg ΞΌ) (h_meas_f : measurable[Mf] f) (h_meas_g : measurable[Mg] g) : ∫⁻ Ο‰, f Ο‰ * g Ο‰ βˆ‚ΞΌ = ∫⁻ Ο‰, f Ο‰ βˆ‚ΞΌ * ∫⁻ Ο‰, g Ο‰ βˆ‚ΞΌ := begin revert g, have h_measM_f : measurable f, from h_meas_f.mono hMf le_rfl, apply measurable.ennreal_induction, { intros c s h_s, apply lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator hMf _ (hMg _ h_s) _ h_meas_f, apply indep_sets_of_indep_sets_of_le_right h_ind, rwa singleton_subset_iff, }, { intros f' g h_univ h_measMg_f' h_measMg_g h_ind_f' h_ind_g', have h_measM_f' : measurable f', from h_measMg_f'.mono hMg le_rfl, have h_measM_g : measurable g, from h_measMg_g.mono hMg le_rfl, simp_rw [pi.add_apply, left_distrib], rw [lintegral_add_left h_measM_f', lintegral_add_left (h_measM_f.mul h_measM_f'), left_distrib, h_ind_f', h_ind_g'] }, { intros f' h_meas_f' h_mono_f' h_ind_f', have h_measM_f' : βˆ€ n, measurable (f' n), from Ξ» n, (h_meas_f' n).mono hMg le_rfl, simp_rw [ennreal.mul_supr], rw [lintegral_supr, lintegral_supr h_measM_f' h_mono_f', ennreal.mul_supr], { simp_rw [← h_ind_f'], }, { exact Ξ» n, h_measM_f.mul (h_measM_f' n), }, { exact Ξ» n m (h_le : n ≀ m) a, mul_le_mul_left' (h_mono_f' h_le a) _, }, } end /-- If `f` and `g` are independent random variables with values in `ℝβ‰₯0∞`, then `E[f * g] = E[f] * E[g]`. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun (h_meas_f : measurable f) (h_meas_g : measurable g) (h_indep_fun : indep_fun f g ΞΌ) : ∫⁻ Ο‰, (f * g) Ο‰ βˆ‚ΞΌ = ∫⁻ Ο‰, f Ο‰ βˆ‚ΞΌ * ∫⁻ Ο‰, g Ο‰ βˆ‚ΞΌ := lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space (measurable_iff_comap_le.1 h_meas_f) (measurable_iff_comap_le.1 h_meas_g) h_indep_fun (measurable.of_comap_le le_rfl) (measurable.of_comap_le le_rfl) /-- If `f` and `g` with values in `ℝβ‰₯0∞` are independent and almost everywhere measurable, then `E[f * g] = E[f] * E[g]` (slightly generalizing `lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun`). -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' (h_meas_f : ae_measurable f ΞΌ) (h_meas_g : ae_measurable g ΞΌ) (h_indep_fun : indep_fun f g ΞΌ) : ∫⁻ Ο‰, (f * g) Ο‰ βˆ‚ΞΌ = ∫⁻ Ο‰, f Ο‰ βˆ‚ΞΌ * ∫⁻ Ο‰, g Ο‰ βˆ‚ΞΌ := begin have fg_ae : f * g =ᡐ[ΞΌ] (h_meas_f.mk _) * (h_meas_g.mk _), from h_meas_f.ae_eq_mk.mul h_meas_g.ae_eq_mk, rw [lintegral_congr_ae h_meas_f.ae_eq_mk, lintegral_congr_ae h_meas_g.ae_eq_mk, lintegral_congr_ae fg_ae], apply lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun h_meas_f.measurable_mk h_meas_g.measurable_mk, exact h_indep_fun.ae_eq h_meas_f.ae_eq_mk h_meas_g.ae_eq_mk end lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'' (h_meas_f : ae_measurable f ΞΌ) (h_meas_g : ae_measurable g ΞΌ) (h_indep_fun : indep_fun f g ΞΌ) : ∫⁻ Ο‰, f Ο‰ * g Ο‰ βˆ‚ΞΌ = ∫⁻ Ο‰, f Ο‰ βˆ‚ΞΌ * ∫⁻ Ο‰, g Ο‰ βˆ‚ΞΌ := lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' h_meas_f h_meas_g h_indep_fun /-- The product of two independent, integrable, real_valued random variables is integrable. -/ lemma indep_fun.integrable_mul {Ξ² : Type*} [measurable_space Ξ²] {X Y : Ξ© β†’ Ξ²} [normed_division_ring Ξ²] [borel_space Ξ²] (hXY : indep_fun X Y ΞΌ) (hX : integrable X ΞΌ) (hY : integrable Y ΞΌ) : integrable (X * Y) ΞΌ := begin let nX : Ξ© β†’ ennreal := Ξ» a, β€–X aβ€–β‚Š, let nY : Ξ© β†’ ennreal := Ξ» a, β€–Y aβ€–β‚Š, have hXY' : indep_fun (Ξ» a, β€–X aβ€–β‚Š) (Ξ» a, β€–Y aβ€–β‚Š) ΞΌ := hXY.comp measurable_nnnorm measurable_nnnorm, have hXY'' : indep_fun nX nY ΞΌ := hXY'.comp measurable_coe_nnreal_ennreal measurable_coe_nnreal_ennreal, have hnX : ae_measurable nX ΞΌ := hX.1.ae_measurable.nnnorm.coe_nnreal_ennreal, have hnY : ae_measurable nY ΞΌ := hY.1.ae_measurable.nnnorm.coe_nnreal_ennreal, have hmul : ∫⁻ a, nX a * nY a βˆ‚ΞΌ = ∫⁻ a, nX a βˆ‚ΞΌ * ∫⁻ a, nY a βˆ‚ΞΌ := by convert lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' hnX hnY hXY'', refine ⟨hX.1.mul hY.1, _⟩, simp_rw [has_finite_integral, pi.mul_apply, nnnorm_mul, ennreal.coe_mul, hmul], exact ennreal.mul_lt_top_iff.mpr (or.inl ⟨hX.2, hY.2⟩) end /-- If the product of two independent real_valued random variables is integrable and the second one is not almost everywhere zero, then the first one is integrable. -/ lemma indep_fun.integrable_left_of_integrable_mul {Ξ² : Type*} [measurable_space Ξ²] {X Y : Ξ© β†’ Ξ²} [normed_division_ring Ξ²] [borel_space Ξ²] (hXY : indep_fun X Y ΞΌ) (h'XY : integrable (X * Y) ΞΌ) (hX : ae_strongly_measurable X ΞΌ) (hY : ae_strongly_measurable Y ΞΌ) (h'Y : Β¬(Y =ᡐ[ΞΌ] 0)) : integrable X ΞΌ := begin refine ⟨hX, _⟩, have I : ∫⁻ Ο‰, β€–Y Ο‰β€–β‚Š βˆ‚ΞΌ β‰  0, { assume H, have I : (Ξ» Ο‰, ↑‖Y Ο‰β€–β‚Š) =ᡐ[ΞΌ] 0 := (lintegral_eq_zero_iff' hY.ennnorm).1 H, apply h'Y, filter_upwards [I] with Ο‰ hΟ‰, simpa using hΟ‰ }, apply lt_top_iff_ne_top.2 (Ξ» H, _), have J : indep_fun (Ξ» Ο‰, ↑‖X Ο‰β€–β‚Š) (Ξ» Ο‰, ↑‖Y Ο‰β€–β‚Š) ΞΌ, { have M : measurable (Ξ» (x : Ξ²), (β€–xβ€–β‚Š : ℝβ‰₯0∞)) := measurable_nnnorm.coe_nnreal_ennreal, apply indep_fun.comp hXY M M }, have A : ∫⁻ Ο‰, β€–X Ο‰ * Y Ο‰β€–β‚Š βˆ‚ΞΌ < ∞ := h'XY.2, simp only [nnnorm_mul, ennreal.coe_mul] at A, rw [lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'' hX.ennnorm hY.ennnorm J, H] at A, simpa [ennreal.top_mul, I] using A, end /-- If the product of two independent real_valued random variables is integrable and the first one is not almost everywhere zero, then the second one is integrable. -/ lemma indep_fun.integrable_right_of_integrable_mul {Ξ² : Type*} [measurable_space Ξ²] {X Y : Ξ© β†’ Ξ²} [normed_division_ring Ξ²] [borel_space Ξ²] (hXY : indep_fun X Y ΞΌ) (h'XY : integrable (X * Y) ΞΌ) (hX : ae_strongly_measurable X ΞΌ) (hY : ae_strongly_measurable Y ΞΌ) (h'X : Β¬(X =ᡐ[ΞΌ] 0)) : integrable Y ΞΌ := begin refine ⟨hY, _⟩, have I : ∫⁻ Ο‰, β€–X Ο‰β€–β‚Š βˆ‚ΞΌ β‰  0, { assume H, have I : (Ξ» Ο‰, ↑‖X Ο‰β€–β‚Š) =ᡐ[ΞΌ] 0 := (lintegral_eq_zero_iff' hX.ennnorm).1 H, apply h'X, filter_upwards [I] with Ο‰ hΟ‰, simpa using hΟ‰ }, apply lt_top_iff_ne_top.2 (Ξ» H, _), have J : indep_fun (Ξ» Ο‰, ↑‖X Ο‰β€–β‚Š) (Ξ» Ο‰, ↑‖Y Ο‰β€–β‚Š) ΞΌ, { have M : measurable (Ξ» (x : Ξ²), (β€–xβ€–β‚Š : ℝβ‰₯0∞)) := measurable_nnnorm.coe_nnreal_ennreal, apply indep_fun.comp hXY M M }, have A : ∫⁻ Ο‰, β€–X Ο‰ * Y Ο‰β€–β‚Š βˆ‚ΞΌ < ∞ := h'XY.2, simp only [nnnorm_mul, ennreal.coe_mul] at A, rw [lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'' hX.ennnorm hY.ennnorm J, H] at A, simpa [ennreal.top_mul, I] using A, end /-- The (Bochner) integral of the product of two independent, nonnegative random variables is the product of their integrals. The proof is just plumbing around `lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'`. -/ lemma indep_fun.integral_mul_of_nonneg (hXY : indep_fun X Y ΞΌ) (hXp : 0 ≀ X) (hYp : 0 ≀ Y) (hXm : ae_measurable X ΞΌ) (hYm : ae_measurable Y ΞΌ) : integral ΞΌ (X * Y) = integral ΞΌ X * integral ΞΌ Y := begin have h1 : ae_measurable (Ξ» a, ennreal.of_real (X a)) ΞΌ := ennreal.measurable_of_real.comp_ae_measurable hXm, have h2 : ae_measurable (Ξ» a, ennreal.of_real (Y a)) ΞΌ := ennreal.measurable_of_real.comp_ae_measurable hYm, have h3 : ae_measurable (X * Y) ΞΌ := hXm.mul hYm, have h4 : 0 ≀ᡐ[ΞΌ] (X * Y) := ae_of_all _ (Ξ» Ο‰, mul_nonneg (hXp Ο‰) (hYp Ο‰)), rw [integral_eq_lintegral_of_nonneg_ae (ae_of_all _ hXp) hXm.ae_strongly_measurable, integral_eq_lintegral_of_nonneg_ae (ae_of_all _ hYp) hYm.ae_strongly_measurable, integral_eq_lintegral_of_nonneg_ae h4 h3.ae_strongly_measurable], simp_rw [←ennreal.to_real_mul, pi.mul_apply, ennreal.of_real_mul (hXp _)], congr, apply lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' h1 h2, exact hXY.comp ennreal.measurable_of_real ennreal.measurable_of_real end /-- The (Bochner) integral of the product of two independent, integrable random variables is the product of their integrals. The proof is pedestrian decomposition into their positive and negative parts in order to apply `indep_fun.integral_mul_of_nonneg` four times. -/ theorem indep_fun.integral_mul_of_integrable (hXY : indep_fun X Y ΞΌ) (hX : integrable X ΞΌ) (hY : integrable Y ΞΌ) : integral ΞΌ (X * Y) = integral ΞΌ X * integral ΞΌ Y := begin let pos : ℝ β†’ ℝ := (Ξ» x, max x 0), let neg : ℝ β†’ ℝ := (Ξ» x, max (-x) 0), have posm : measurable pos := measurable_id'.max measurable_const, have negm : measurable neg := measurable_id'.neg.max measurable_const, let Xp := pos ∘ X, -- `X⁺` would look better but it makes `simp_rw` below fail let Xm := neg ∘ X, let Yp := pos ∘ Y, let Ym := neg ∘ Y, have hXpm : X = Xp - Xm := funext (Ξ» Ο‰, (max_zero_sub_max_neg_zero_eq_self (X Ο‰)).symm), have hYpm : Y = Yp - Ym := funext (Ξ» Ο‰, (max_zero_sub_max_neg_zero_eq_self (Y Ο‰)).symm), have hp1 : 0 ≀ Xm := Ξ» Ο‰, le_max_right _ _, have hp2 : 0 ≀ Xp := Ξ» Ο‰, le_max_right _ _, have hp3 : 0 ≀ Ym := Ξ» Ο‰, le_max_right _ _, have hp4 : 0 ≀ Yp := Ξ» Ο‰, le_max_right _ _, have hm1 : ae_measurable Xm ΞΌ := hX.1.ae_measurable.neg.max ae_measurable_const, have hm2 : ae_measurable Xp ΞΌ := hX.1.ae_measurable.max ae_measurable_const, have hm3 : ae_measurable Ym ΞΌ := hY.1.ae_measurable.neg.max ae_measurable_const, have hm4 : ae_measurable Yp ΞΌ := hY.1.ae_measurable.max ae_measurable_const, have hv1 : integrable Xm ΞΌ := hX.neg_part, have hv2 : integrable Xp ΞΌ := hX.pos_part, have hv3 : integrable Ym ΞΌ := hY.neg_part, have hv4 : integrable Yp ΞΌ := hY.pos_part, have hi1 : indep_fun Xm Ym ΞΌ := hXY.comp negm negm, have hi2 : indep_fun Xp Ym ΞΌ := hXY.comp posm negm, have hi3 : indep_fun Xm Yp ΞΌ := hXY.comp negm posm, have hi4 : indep_fun Xp Yp ΞΌ := hXY.comp posm posm, have hl1 : integrable (Xm * Ym) ΞΌ := hi1.integrable_mul hv1 hv3, have hl2 : integrable (Xp * Ym) ΞΌ := hi2.integrable_mul hv2 hv3, have hl3 : integrable (Xm * Yp) ΞΌ := hi3.integrable_mul hv1 hv4, have hl4 : integrable (Xp * Yp) ΞΌ := hi4.integrable_mul hv2 hv4, have hl5 : integrable (Xp * Yp - Xm * Yp) ΞΌ := hl4.sub hl3, have hl6 : integrable (Xp * Ym - Xm * Ym) ΞΌ := hl2.sub hl1, simp_rw [hXpm, hYpm, mul_sub, sub_mul], rw [integral_sub' hl5 hl6, integral_sub' hl4 hl3, integral_sub' hl2 hl1, integral_sub' hv2 hv1, integral_sub' hv4 hv3, hi1.integral_mul_of_nonneg hp1 hp3 hm1 hm3, hi2.integral_mul_of_nonneg hp2 hp3 hm2 hm3, hi3.integral_mul_of_nonneg hp1 hp4 hm1 hm4, hi4.integral_mul_of_nonneg hp2 hp4 hm2 hm4], ring end /-- The (Bochner) integral of the product of two independent random variables is the product of their integrals. -/ theorem indep_fun.integral_mul (hXY : indep_fun X Y ΞΌ) (hX : ae_strongly_measurable X ΞΌ) (hY : ae_strongly_measurable Y ΞΌ) : integral ΞΌ (X * Y) = integral ΞΌ X * integral ΞΌ Y := begin by_cases h'X : X =ᡐ[ΞΌ] 0, { have h' : X * Y =ᡐ[ΞΌ] 0, { filter_upwards [h'X] with Ο‰ hΟ‰, simp [hΟ‰] }, simp only [integral_congr_ae h'X, integral_congr_ae h', pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_mul] }, by_cases h'Y : Y =ᡐ[ΞΌ] 0, { have h' : X * Y =ᡐ[ΞΌ] 0, { filter_upwards [h'Y] with Ο‰ hΟ‰, simp [hΟ‰] }, simp only [integral_congr_ae h'Y, integral_congr_ae h', pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_mul] }, by_cases h : integrable (X * Y) ΞΌ, { have HX : integrable X ΞΌ := hXY.integrable_left_of_integrable_mul h hX hY h'Y, have HY : integrable Y ΞΌ := hXY.integrable_right_of_integrable_mul h hX hY h'X, exact hXY.integral_mul_of_integrable HX HY }, { have I : Β¬(integrable X ΞΌ ∧ integrable Y ΞΌ), { rintros ⟨HX, HY⟩, exact h (hXY.integrable_mul HX HY) }, rw not_and_distrib at I, cases I; simp [integral_undef, I, h] } end theorem indep_fun.integral_mul' (hXY : indep_fun X Y ΞΌ) (hX : ae_strongly_measurable X ΞΌ) (hY : ae_strongly_measurable Y ΞΌ) : integral ΞΌ (Ξ» Ο‰, X Ο‰ * Y Ο‰) = integral ΞΌ X * integral ΞΌ Y := hXY.integral_mul hX hY /-- Independence of functions `f` and `g` into arbitrary types is characterized by the relation `E[(Ο† ∘ f) * (ψ ∘ g)] = E[Ο† ∘ f] * E[ψ ∘ g]` for all measurable `Ο†` and `ψ` with values in `ℝ` satisfying appropriate integrability conditions. -/ theorem indep_fun_iff_integral_comp_mul [is_finite_measure ΞΌ] {Ξ² Ξ²' : Type*} {mΞ² : measurable_space Ξ²} {mΞ²' : measurable_space Ξ²'} {f : Ξ© β†’ Ξ²} {g : Ξ© β†’ Ξ²'} {hfm : measurable f} {hgm : measurable g} : indep_fun f g ΞΌ ↔ βˆ€ {Ο† : Ξ² β†’ ℝ} {ψ : Ξ²' β†’ ℝ}, measurable Ο† β†’ measurable ψ β†’ integrable (Ο† ∘ f) ΞΌ β†’ integrable (ψ ∘ g) ΞΌ β†’ integral ΞΌ ((Ο† ∘ f) * (ψ ∘ g)) = integral ΞΌ (Ο† ∘ f) * integral ΞΌ (ψ ∘ g) := begin refine ⟨λ hfg _ _ hΟ† hψ, indep_fun.integral_mul_of_integrable (hfg.comp hΟ† hψ), _⟩, rintro h _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, specialize h (measurable_one.indicator hA) (measurable_one.indicator hB) ((integrable_const 1).indicator (hfm.comp measurable_id hA)) ((integrable_const 1).indicator (hgm.comp measurable_id hB)), rwa [← ennreal.to_real_eq_to_real (measure_ne_top ΞΌ _), ennreal.to_real_mul, ← integral_indicator_one ((hfm hA).inter (hgm hB)), ← integral_indicator_one (hfm hA), ← integral_indicator_one (hgm hB), set.inter_indicator_one], exact ennreal.mul_ne_top (measure_ne_top ΞΌ _) (measure_ne_top ΞΌ _) end end probability_theory
8dd1db5ed467f4616b0beeaed2dd6ab203e02ca6
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/init/data/char/basic.lean
a95b7b89983d52398195b6d994ca6d5c302ec961
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
779
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.fin.basic open nat def char_sz : nat := succ 255 def char := fin char_sz instance : has_sizeof char := ⟨fin.sizeof _⟩ namespace char /- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/ lemma zero_lt_char_sz : 0 < char_sz := zero_lt_succ _ @[pattern] def of_nat (n : nat) : char := if h : n < char_sz then fin.mk n h else fin.mk 0 zero_lt_char_sz def to_nat (c : char) : nat := fin.val c end char instance : decidable_eq char := have decidable_eq (fin char_sz), from fin.decidable_eq _, this instance : inhabited char := ⟨#"A"⟩
83af6e6bfc1cdebd8c5b70084d3d2c4d436169a0
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebraic_topology/simplicial_object.lean
be384bc4a9b86f57880714d4ca567d7c57c62bfe
[ "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
19,470
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import algebraic_topology.simplex_category import category_theory.arrow import category_theory.limits.functor_category import category_theory.opposites /-! # Simplicial objects in a category. A simplicial object in a category `C` is a `C`-valued presheaf on `simplex_category`. (Similarly a cosimplicial object is functor `simplex_category β₯€ C`.) Use the notation `X _[n]` in the `simplicial` locale to obtain the `n`-th term of a (co)simplicial object `X`, where `n` is a natural number. -/ open opposite open category_theory open category_theory.limits universes v u v' u' namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of simplicial objects valued in a category `C`. This is the category of contravariant functors from `simplex_category` to `C`. -/ @[derive category, nolint has_nonempty_instance] def simplicial_object := simplex_categoryα΅’α΅– β₯€ C namespace simplicial_object localized "notation X `_[`:1000 n `]` := (X : category_theory.simplicial_object _).obj (opposite.op (simplex_category.mk n))" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_limits C] : has_limits (simplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_colimits C] : has_colimits (simplicial_object C) := ⟨infer_instance⟩ variables {C} (X : simplicial_object C) /-- Face maps for a simplicial object. -/ def Ξ΄ {n} (i : fin (n+2)) : X _[n+1] ⟢ X _[n] := X.map (simplex_category.Ξ΄ i).op /-- Degeneracy maps for a simplicial object. -/ def Οƒ {n} (i : fin (n+1)) : X _[n] ⟢ X _[n+1] := X.map (simplex_category.Οƒ i).op /-- Isomorphisms from identities in β„•. -/ def eq_to_iso {n m : β„•} (h : n = m) : X _[n] β‰… X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : β„•} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first simplicial identity -/ lemma Ξ΄_comp_Ξ΄ {n} {i j : fin (n+2)} (H : i ≀ j) : X.Ξ΄ j.succ ≫ X.Ξ΄ i = X.Ξ΄ i.cast_succ ≫ X.Ξ΄ j := by { dsimp [Ξ΄], simp only [←X.map_comp, ←op_comp, simplex_category.Ξ΄_comp_Ξ΄ H] } /-- The special case of the first simplicial identity -/ lemma Ξ΄_comp_Ξ΄_self {n} {i : fin (n+2)} : X.Ξ΄ i.cast_succ ≫ X.Ξ΄ i = X.Ξ΄ i.succ ≫ X.Ξ΄ i := by { dsimp [Ξ΄], simp only [←X.map_comp, ←op_comp, simplex_category.Ξ΄_comp_Ξ΄_self] } /-- The second simplicial identity -/ lemma Ξ΄_comp_Οƒ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≀ j.cast_succ) : X.Οƒ j.succ ≫ X.Ξ΄ i.cast_succ = X.Ξ΄ i ≫ X.Οƒ j := by { dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, ←op_comp, simplex_category.Ξ΄_comp_Οƒ_of_le H] } /-- The first part of the third simplicial identity -/ lemma Ξ΄_comp_Οƒ_self {n} {i : fin (n+1)} : X.Οƒ i ≫ X.Ξ΄ i.cast_succ = πŸ™ _ := begin dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, ←op_comp, simplex_category.Ξ΄_comp_Οƒ_self, op_id, X.map_id], end /-- The second part of the third simplicial identity -/ lemma Ξ΄_comp_Οƒ_succ {n} {i : fin (n+1)} : X.Οƒ i ≫ X.Ξ΄ i.succ = πŸ™ _ := begin dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, ←op_comp, simplex_category.Ξ΄_comp_Οƒ_succ, op_id, X.map_id], end /-- The fourth simplicial identity -/ lemma Ξ΄_comp_Οƒ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.Οƒ j.cast_succ ≫ X.Ξ΄ i.succ = X.Ξ΄ i ≫ X.Οƒ j := by { dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, ←op_comp, simplex_category.Ξ΄_comp_Οƒ_of_gt H] } /-- The fifth simplicial identity -/ lemma Οƒ_comp_Οƒ {n} {i j : fin (n+1)} (H : i ≀ j) : X.Οƒ j ≫ X.Οƒ i.cast_succ = X.Οƒ i ≫ X.Οƒ j.succ := by { dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, ←op_comp, simplex_category.Οƒ_comp_Οƒ H] } variable (C) /-- Functor composition induces a functor on simplicial objects. -/ @[simps] def whiskering (D : Type*) [category D] : (C β₯€ D) β₯€ simplicial_object C β₯€ simplicial_object D := whiskering_right _ _ _ /-- Truncated simplicial objects. -/ @[derive category, nolint has_nonempty_instance] def truncated (n : β„•) := (simplex_category.truncated n)α΅’α΅– β₯€ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (simplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (simplicial_object.truncated C n) := ⟨infer_instance⟩ variable (C) /-- Functor composition induces a functor on truncated simplicial objects. -/ @[simps] def whiskering {n} (D : Type*) [category D] : (C β₯€ D) β₯€ truncated C n β₯€ truncated D n := whiskering_right _ _ _ variable {C} end truncated section skeleton /-- The skeleton functor from simplicial objects to truncated simplicial objects. -/ def sk (n : β„•) : simplicial_object C β₯€ simplicial_object.truncated C n := (whiskering_left _ _ _).obj simplex_category.truncated.inclusion.op end skeleton variable (C) /-- The constant simplicial object is the constant functor. -/ abbreviation const : C β₯€ simplicial_object C := category_theory.functor.const _ /-- The category of augmented simplicial objects, defined as a comma category. -/ @[derive category, nolint has_nonempty_instance] def augmented := comma (𝟭 (simplicial_object C)) (const C) variable {C} namespace augmented /-- Drop the augmentation. -/ @[simps] def drop : augmented C β₯€ simplicial_object C := comma.fst _ _ /-- The point of the augmentation. -/ @[simps] def point : augmented C β₯€ C := comma.snd _ _ /-- The functor from augmented objects to arrows. -/ @[simps] def to_arrow : augmented C β₯€ arrow C := { obj := Ξ» X, { left := (drop.obj X) _[0], right := (point.obj X), hom := X.hom.app _ }, map := Ξ» X Y Ξ·, { left := (drop.map Ξ·).app _, right := (point.map Ξ·), w' := begin dsimp, rw ← nat_trans.comp_app, erw Ξ·.w, refl, end } } variable (C) /-- Functor composition induces a functor on augmented simplicial objects. -/ @[simp] def whiskering_obj (D : Type*) [category D] (F : C β₯€ D) : augmented C β₯€ augmented D := { obj := Ξ» X, { left := ((whiskering _ _).obj F).obj (drop.obj X), right := F.obj (point.obj X), hom := whisker_right X.hom F ≫ (functor.const_comp _ _ _).hom }, map := Ξ» X Y Ξ·, { left := whisker_right Ξ·.left _, right := F.map Ξ·.right, w' := begin ext, dsimp, rw [category.comp_id, category.comp_id, ← F.map_comp, ← F.map_comp, ← nat_trans.comp_app], erw Ξ·.w, refl, end } } /-- Functor composition induces a functor on augmented simplicial objects. -/ @[simps] def whiskering (D : Type u') [category.{v'} D] : (C β₯€ D) β₯€ augmented C β₯€ augmented D := { obj := whiskering_obj _ _, map := Ξ» X Y Ξ·, { app := Ξ» A, { left := whisker_left _ Ξ·, right := Ξ·.app _, w' := begin ext n, dsimp, rw [category.comp_id, category.comp_id, Ξ·.naturality], end }, }, } variable {C} end augmented open_locale simplicial /-- Aaugment a simplicial object with an object. -/ @[simps] def augment (X : simplicial_object C) (Xβ‚€ : C) (f : X _[0] ⟢ Xβ‚€) (w : βˆ€ (i : simplex_category) (g₁ gβ‚‚ : [0] ⟢ i), X.map g₁.op ≫ f = X.map gβ‚‚.op ≫ f) : simplicial_object.augmented C := { left := X, right := Xβ‚€, hom := { app := Ξ» i, X.map (simplex_category.const i.unop 0).op ≫ f, naturality' := begin intros i j g, dsimp, rw ← g.op_unop, simpa only [← X.map_comp, ← category.assoc, category.comp_id, ← op_comp] using w _ _ _, end } } @[simp] lemma augment_hom_zero (X : simplicial_object C) (Xβ‚€ : C) (f : X _[0] ⟢ Xβ‚€) (w) : (X.augment Xβ‚€ f w).hom.app (op [0]) = f := by { dsimp, rw [simplex_category.hom_zero_zero ([0].const 0), op_id, X.map_id, category.id_comp] } end simplicial_object /-- Cosimplicial objects. -/ @[derive category, nolint has_nonempty_instance] def cosimplicial_object := simplex_category β₯€ C namespace cosimplicial_object localized "notation X `_[`:1000 n `]` := (X : category_theory.cosimplicial_object _).obj (simplex_category.mk n)" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (cosimplicial_object C) := by {dsimp [cosimplicial_object], apply_instance} instance [has_limits C] : has_limits (cosimplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (cosimplicial_object C) := by {dsimp [cosimplicial_object], apply_instance} instance [has_colimits C] : has_colimits (cosimplicial_object C) := ⟨infer_instance⟩ variables {C} (X : cosimplicial_object C) /-- Coface maps for a cosimplicial object. -/ def Ξ΄ {n} (i : fin (n+2)) : X _[n] ⟢ X _[n+1] := X.map (simplex_category.Ξ΄ i) /-- Codegeneracy maps for a cosimplicial object. -/ def Οƒ {n} (i : fin (n+1)) : X _[n+1] ⟢ X _[n] := X.map (simplex_category.Οƒ i) /-- Isomorphisms from identities in β„•. -/ def eq_to_iso {n m : β„•} (h : n = m) : X _[n] β‰… X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : β„•} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first cosimplicial identity -/ lemma Ξ΄_comp_Ξ΄ {n} {i j : fin (n+2)} (H : i ≀ j) : X.Ξ΄ i ≫ X.Ξ΄ j.succ = X.Ξ΄ j ≫ X.Ξ΄ i.cast_succ := by { dsimp [Ξ΄], simp only [←X.map_comp, simplex_category.Ξ΄_comp_Ξ΄ H], } /-- The special case of the first cosimplicial identity -/ lemma Ξ΄_comp_Ξ΄_self {n} {i : fin (n+2)} : X.Ξ΄ i ≫ X.Ξ΄ i.cast_succ = X.Ξ΄ i ≫ X.Ξ΄ i.succ := by { dsimp [Ξ΄], simp only [←X.map_comp, simplex_category.Ξ΄_comp_Ξ΄_self] } /-- The second cosimplicial identity -/ lemma Ξ΄_comp_Οƒ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≀ j.cast_succ) : X.Ξ΄ i.cast_succ ≫ X.Οƒ j.succ = X.Οƒ j ≫ X.Ξ΄ i := by { dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, simplex_category.Ξ΄_comp_Οƒ_of_le H] } /-- The first part of the third cosimplicial identity -/ lemma Ξ΄_comp_Οƒ_self {n} {i : fin (n+1)} : X.Ξ΄ i.cast_succ ≫ X.Οƒ i = πŸ™ _ := begin dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, simplex_category.Ξ΄_comp_Οƒ_self, X.map_id], end /-- The second part of the third cosimplicial identity -/ lemma Ξ΄_comp_Οƒ_succ {n} {i : fin (n+1)} : X.Ξ΄ i.succ ≫ X.Οƒ i = πŸ™ _ := begin dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, simplex_category.Ξ΄_comp_Οƒ_succ, X.map_id], end /-- The fourth cosimplicial identity -/ lemma Ξ΄_comp_Οƒ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.Ξ΄ i.succ ≫ X.Οƒ j.cast_succ = X.Οƒ j ≫ X.Ξ΄ i := by { dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, simplex_category.Ξ΄_comp_Οƒ_of_gt H] } /-- The fifth cosimplicial identity -/ lemma Οƒ_comp_Οƒ {n} {i j : fin (n+1)} (H : i ≀ j) : X.Οƒ i.cast_succ ≫ X.Οƒ j = X.Οƒ j.succ ≫ X.Οƒ i := by { dsimp [Ξ΄, Οƒ], simp only [←X.map_comp, simplex_category.Οƒ_comp_Οƒ H] } variable (C) /-- Functor composition induces a functor on cosimplicial objects. -/ @[simps] def whiskering (D : Type*) [category D] : (C β₯€ D) β₯€ cosimplicial_object C β₯€ cosimplicial_object D := whiskering_right _ _ _ /-- Truncated cosimplicial objects. -/ @[derive category, nolint has_nonempty_instance] def truncated (n : β„•) := simplex_category.truncated n β₯€ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (cosimplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (cosimplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (cosimplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (cosimplicial_object.truncated C n) := ⟨infer_instance⟩ variable (C) /-- Functor composition induces a functor on truncated cosimplicial objects. -/ @[simps] def whiskering {n} (D : Type*) [category D] : (C β₯€ D) β₯€ truncated C n β₯€ truncated D n := whiskering_right _ _ _ variable {C} end truncated section skeleton /-- The skeleton functor from cosimplicial objects to truncated cosimplicial objects. -/ def sk (n : β„•) : cosimplicial_object C β₯€ cosimplicial_object.truncated C n := (whiskering_left _ _ _).obj simplex_category.truncated.inclusion end skeleton variable (C) /-- The constant cosimplicial object. -/ abbreviation const : C β₯€ cosimplicial_object C := category_theory.functor.const _ /-- Augmented cosimplicial objects. -/ @[derive category, nolint has_nonempty_instance] def augmented := comma (const C) (𝟭 (cosimplicial_object C)) variable {C} namespace augmented /-- Drop the augmentation. -/ @[simps] def drop : augmented C β₯€ cosimplicial_object C := comma.snd _ _ /-- The point of the augmentation. -/ @[simps] def point : augmented C β₯€ C := comma.fst _ _ /-- The functor from augmented objects to arrows. -/ @[simps] def to_arrow : augmented C β₯€ arrow C := { obj := Ξ» X, { left := (point.obj X), right := (drop.obj X) _[0], hom := X.hom.app _ }, map := Ξ» X Y Ξ·, { left := (point.map Ξ·), right := (drop.map Ξ·).app _, w' := begin dsimp, rw ← nat_trans.comp_app, erw ← Ξ·.w, refl, end } } variable (C) /-- Functor composition induces a functor on augmented cosimplicial objects. -/ @[simp] def whiskering_obj (D : Type*) [category D] (F : C β₯€ D) : augmented C β₯€ augmented D := { obj := Ξ» X, { left := F.obj (point.obj X), right := ((whiskering _ _).obj F).obj (drop.obj X), hom := (functor.const_comp _ _ _).inv ≫ whisker_right X.hom F }, map := Ξ» X Y Ξ·, { left := F.map Ξ·.left, right := whisker_right Ξ·.right _, w' := begin ext, dsimp, rw [category.id_comp, category.id_comp, ← F.map_comp, ← F.map_comp, ← nat_trans.comp_app], erw ← Ξ·.w, refl, end } } /-- Functor composition induces a functor on augmented cosimplicial objects. -/ @[simps] def whiskering (D : Type u') [category.{v'} D] : (C β₯€ D) β₯€ augmented C β₯€ augmented D := { obj := whiskering_obj _ _, map := Ξ» X Y Ξ·, { app := Ξ» A, { left := Ξ·.app _, right := whisker_left _ Ξ·, w' := begin ext n, dsimp, rw [category.id_comp, category.id_comp, Ξ·.naturality], end }, }, } variable {C} end augmented open_locale simplicial /-- Augment a cosimplicial object with an object. -/ @[simps] def augment (X : cosimplicial_object C) (Xβ‚€ : C) (f : Xβ‚€ ⟢ X.obj [0]) (w : βˆ€ (i : simplex_category) (g₁ gβ‚‚ : [0] ⟢ i), f ≫ X.map g₁ = f ≫ X.map gβ‚‚) : cosimplicial_object.augmented C := { left := Xβ‚€, right := X, hom := { app := Ξ» i, f ≫ X.map (simplex_category.const i 0), naturality' := begin intros i j g, dsimp, simpa [← X.map_comp] using w _ _ _, end } } @[simp] lemma augment_hom_zero (X : cosimplicial_object C) (Xβ‚€ : C) (f : Xβ‚€ ⟢ X.obj [0]) (w) : (X.augment Xβ‚€ f w).hom.app [0] = f := by { dsimp, rw [simplex_category.hom_zero_zero ([0].const 0), X.map_id, category.comp_id] } end cosimplicial_object /-- The anti-equivalence between simplicial objects and cosimplicial objects. -/ @[simps] def simplicial_cosimplicial_equiv : (simplicial_object C)α΅’α΅– β‰Œ (cosimplicial_object Cα΅’α΅–) := functor.left_op_right_op_equiv _ _ /-- The anti-equivalence between cosimplicial objects and simplicial objects. -/ @[simps] def cosimplicial_simplicial_equiv : (cosimplicial_object C)α΅’α΅– β‰Œ (simplicial_object Cα΅’α΅–) := functor.op_unop_equiv _ _ variable {C} /-- Construct an augmented cosimplicial object in the opposite category from an augmented simplicial object. -/ @[simps] def simplicial_object.augmented.right_op (X : simplicial_object.augmented C) : cosimplicial_object.augmented Cα΅’α΅– := { left := opposite.op X.right, right := X.left.right_op, hom := X.hom.right_op } /-- Construct an augmented simplicial object from an augmented cosimplicial object in the opposite category. -/ @[simps] def cosimplicial_object.augmented.left_op (X : cosimplicial_object.augmented Cα΅’α΅–) : simplicial_object.augmented C := { left := X.right.left_op, right := X.left.unop, hom := X.hom.left_op } /-- Converting an augmented simplicial object to an augmented cosimplicial object and back is isomorphic to the given object. -/ @[simps] def simplicial_object.augmented.right_op_left_op_iso (X : simplicial_object.augmented C) : X.right_op.left_op β‰… X := comma.iso_mk X.left.right_op_left_op_iso (eq_to_iso $ by simp) (by tidy) /-- Converting an augmented cosimplicial object to an augmented simplicial object and back is isomorphic to the given object. -/ @[simps] def cosimplicial_object.augmented.left_op_right_op_iso (X : cosimplicial_object.augmented Cα΅’α΅–) : X.left_op.right_op β‰… X := comma.iso_mk (eq_to_iso $ by simp) X.right.left_op_right_op_iso (by tidy) variable (C) /-- A functorial version of `simplicial_object.augmented.right_op`. -/ @[simps] def simplicial_to_cosimplicial_augmented : (simplicial_object.augmented C)α΅’α΅– β₯€ cosimplicial_object.augmented Cα΅’α΅– := { obj := Ξ» X, X.unop.right_op, map := Ξ» X Y f, { left := f.unop.right.op, right := f.unop.left.right_op, w' := begin ext x, dsimp, simp_rw ← op_comp, congr' 1, exact (congr_app f.unop.w (op x)).symm, end } } /-- A functorial version of `cosimplicial_object.augmented.left_op`. -/ @[simps] def cosimplicial_to_simplicial_augmented : cosimplicial_object.augmented Cα΅’α΅– β₯€ (simplicial_object.augmented C)α΅’α΅– := { obj := Ξ» X, opposite.op X.left_op, map := Ξ» X Y f, quiver.hom.op $ { left := f.right.left_op, right := f.left.unop, w' := begin ext x, dsimp, simp_rw ← unop_comp, congr' 1, exact (congr_app f.w x.unop).symm, end} } /-- The contravariant categorical equivalence between augmented simplicial objects and augmented cosimplicial objects in the opposite category. -/ @[simps] def simplicial_cosimplicial_augmented_equiv : (simplicial_object.augmented C)α΅’α΅– β‰Œ cosimplicial_object.augmented Cα΅’α΅– := { functor := simplicial_to_cosimplicial_augmented _, inverse := cosimplicial_to_simplicial_augmented _, unit_iso := nat_iso.of_components (Ξ» X, X.unop.right_op_left_op_iso.op) begin intros X Y f, dsimp, rw (show f = f.unop.op, by simp), simp_rw ← op_comp, congr' 1, tidy, end, counit_iso := nat_iso.of_components (Ξ» X, X.left_op_right_op_iso) (by tidy) } end category_theory
de5276bdfe28921d2d5b4d66a84c122731f3ef17
d1bbf1801b3dcb214451d48214589f511061da63
/src/algebra/ordered_field.lean
43e7e7a7c8f63f6416cca5b617bb8a863e8ac895
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,509
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.ordered_ring import algebra.field /-! ### Linear ordered fields A linear ordered field is a field equipped with a linear order such that * addition respects the order: `a ≀ b β†’ c + a ≀ c + b`; * multiplication of positives is positive: `0 < a β†’ 0 < b β†’ 0 < a * b`; * `0 < 1`. ### Main Definitions * `linear_ordered_field`: the class of linear ordered fields. -/ set_option old_structure_cmd true variable {Ξ± : Type*} /-- A linear ordered field is a field with a linear order respecting the operations. -/ @[protect_proj] class linear_ordered_field (Ξ± : Type*) extends linear_ordered_comm_ring Ξ±, field Ξ± section linear_ordered_field variables [linear_ordered_field Ξ±] {a b c d e : Ξ±} /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices βˆ€ a : Ξ±, 0 < a β†’ 0 < a⁻¹, from ⟨λ h, inv_inv' a β–Έ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] @[simp] lemma inv_nonneg : 0 ≀ a⁻¹ ↔ 0 ≀ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≀ 0 ↔ a ≀ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a β–Έ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a β–Έ inv_lt_zero lemma one_div_nonneg : 0 ≀ 1 / a ↔ 0 ≀ a := inv_eq_one_div a β–Έ inv_nonneg lemma one_div_nonpos : 1 / a ≀ 0 ↔ a ≀ 0 := inv_eq_one_div a β–Έ inv_nonpos lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≀ a / b ↔ 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≀ 0 ↔ 0 ≀ a ∧ b ≀ 0 ∨ a ≀ 0 ∧ 0 ≀ b := by simp [division_def, mul_nonpos_iff] lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := mul_pos ha (inv_pos.2 hb) lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := mul_pos_of_neg_of_neg ha (inv_lt_zero.2 hb) lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := mul_neg_of_neg_of_pos ha (inv_pos.2 hb) lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := mul_neg_of_pos_of_neg ha (inv_lt_zero.2 hb) lemma div_nonneg (ha : 0 ≀ a) (hb : 0 ≀ b) : 0 ≀ a / b := mul_nonneg ha (inv_nonneg.2 hb) lemma div_nonneg_of_nonpos (ha : a ≀ 0) (hb : b ≀ 0) : 0 ≀ a / b := mul_nonneg_of_nonpos_of_nonpos ha (inv_nonpos.2 hb) lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≀ 0) (hb : 0 ≀ b) : a / b ≀ 0 := mul_nonpos_of_nonpos_of_nonneg ha (inv_nonneg.2 hb) lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≀ a) (hb : b ≀ 0) : a / b ≀ 0 := mul_nonpos_of_nonneg_of_nonpos ha (inv_nonpos.2 hb) /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≀ b / c ↔ a * c ≀ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm β–Έ mul_le_mul_of_nonneg_right h hc.le, Ξ» h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≀ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma le_div_iff' (hc : 0 < c) : a ≀ b / c ↔ c * a ≀ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≀ c ↔ a ≀ c * b := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≀ c * b : mul_le_mul_of_nonneg_right h hb.le, Ξ» h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≀ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≀ c ↔ a ≀ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≀ c ↔ a ≀ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≀ c ↔ a ≀ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≀ c ↔ a ≀ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≀ c ↔ a ≀ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≀ b ↔ 1 ≀ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≀ b ↔ 1 ≀ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } lemma div_le_iff_of_neg (hc : c < 0) : b / c ≀ a ↔ a * c ≀ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) β–Έ mul_le_mul_of_nonpos_right h hc.le, Ξ» h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... β‰₯ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≀ a ↔ c * a ≀ b := by rw [mul_comm, div_le_iff_of_neg hc] lemma le_div_iff_of_neg (hc : c < 0) : a ≀ b / c ↔ b ≀ a * c := by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm] lemma le_div_iff_of_neg' (hc : c < 0) : a ≀ b / c ↔ b ≀ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≀ b) (hc : 0 ≀ c) (h : a ≀ c * b) : a / b ≀ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≀ b) (hb : 0 ≀ b) : a / b ≀ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≀ b) : b⁻¹ ≀ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≀ b⁻¹ ↔ b ≀ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≀ b ↔ b⁻¹ ≀ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv'] lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≀ b⁻¹ ↔ b ≀ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv'] lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≀ b⁻¹ ↔ b ≀ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≀ b ↔ b⁻¹ ≀ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv'] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≀ b⁻¹ ↔ b ≀ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv'] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt ((@zero_lt_one Ξ± _ _).trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (hβ‚‚ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv (@zero_lt_one Ξ± _ _) h₁, inv_one] lemma inv_le_one (ha : 1 ≀ a) : a⁻¹ ≀ 1 := by rwa [inv_le ((@zero_lt_one Ξ± _ _).trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (hβ‚‚ : a ≀ 1) : 1 ≀ a⁻¹ := by rwa [le_inv (@zero_lt_one Ξ± _ _) h₁, inv_one] lemma inv_lt_one_iff_of_pos (hβ‚€ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv' a β–Έ one_lt_inv (inv_pos.2 hβ‚€) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≀ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv' a β–Έ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≀ 1 ↔ a ≀ 0 ∨ 1 ≀ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one'.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≀ a⁻¹ ↔ 0 < a ∧ a ≀ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv' a β–Έ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ lemma div_le_div_of_le (hc : 0 ≀ c) (h : a ≀ b) : a / c ≀ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end lemma div_le_div_of_le_left (ha : 0 ≀ a) (hc : 0 < c) (h : c ≀ b) : a / b ≀ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≀ b) (hc : 0 ≀ c) : a / c ≀ b / c := mul_le_mul_of_nonneg_right hab (inv_nonneg.2 hc) lemma div_le_div_of_nonpos_of_le (hc : c ≀ 0) (h : b ≀ a) : a / c ≀ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≀ b / c ↔ a ≀ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≀ b / c ↔ b ≀ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_div_right_of_neg hc lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := (mul_lt_mul_left ha).trans (inv_lt_inv hb hc) lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≀ a / c ↔ c ≀ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≀ c / d ↔ a * d ≀ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] lemma div_le_div (hc : 0 ≀ c) (hac : a ≀ c) (hd : 0 < d) (hbd : d ≀ b) : a / b ≀ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≀ b) (c0 : 0 ≀ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≀ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma one_le_div (hb : 0 < b) : 1 ≀ a / b ↔ b ≀ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≀ 1 ↔ a ≀ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_le_div_of_neg (hb : b < 0) : 1 ≀ a / b ↔ a ≀ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≀ 1 ↔ b ≀ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≀ b ↔ 1 / b ≀ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≀ 1 / b ↔ b ≀ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≀ b ↔ 1 / b ≀ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≀ 1 / b ↔ b ≀ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≀ a / b ↔ 0 < b ∧ b ≀ a ∨ b < 0 ∧ a ≀ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≀ 1 ↔ 0 < b ∧ a ≀ b ∨ b = 0 ∨ b < 0 ∧ b ≀ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≀ b) : 1 / b ≀ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≀ b) : 1 / b ≀ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≀ 1 / b) : b ≀ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≀ 1 / b) : b ≀ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≀ 1 / b ↔ b ≀ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≀ 1 / b ↔ b ≀ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div (@zero_lt_one Ξ± _ _) h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≀ 1) : 1 ≀ 1 / a := by rwa [le_one_div (@zero_lt_one Ξ± _ _) h1, one_div_one] lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≀ a) : 1 / a ≀ -1 := suffices 1 / a ≀ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving. The equalities also hold in fields of characteristic `0`. -/ lemma add_halves (a : Ξ±) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] lemma sub_self_div_two (a : Ξ±) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : Ξ±) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : Ξ±) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:Ξ±) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (@zero_lt_two Ξ± _ _)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a β†’ a / 2 < a := div_two_lt_of_pos lemma one_half_lt_one : (1 / 2 : Ξ±) < 1 := half_lt_self zero_lt_one lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (@zero_lt_two Ξ± _ _)] end /-! ### Miscellaneous lemmas -/ lemma mul_sub_mul_div_mul_neg_iff (hc : c β‰  0) (hd : d β‰  0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg lemma mul_sub_mul_div_mul_nonpos_iff (hc : c β‰  0) (hd : d β‰  0) : (a * d - b * c) / (c * d) ≀ 0 ↔ a / c ≀ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≀ d) (hc : 0 < c) : b * a ≀ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≀ c / d) (he : 0 ≀ e) : a / (b * e) ≀ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_add_lt_and_pos_of_lt (h : b < a) : βˆƒ c : Ξ±, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma le_of_forall_sub_le (h : βˆ€ Ξ΅ > 0, b - Ξ΅ ≀ a) : b ≀ a := begin contrapose! h, simpa only [and_comm ((0 : Ξ±) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma monotone.div_const {Ξ² : Type*} [preorder Ξ²] {f : Ξ² β†’ Ξ±} (hf : monotone f) {c : Ξ±} (hc : 0 ≀ c) : monotone (Ξ» x, (f x) / c) := hf.mul_const (inv_nonneg.2 hc) lemma strict_mono.div_const {Ξ² : Type*} [preorder Ξ²] {f : Ξ² β†’ Ξ±} (hf : strict_mono f) {c : Ξ±} (hc : 0 < c) : strict_mono (Ξ» x, (f x) / c) := hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered Ξ± := { dense := Ξ» a₁ aβ‚‚ h, ⟨(a₁ + aβ‚‚) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + aβ‚‚) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_left h _), calc (a₁ + aβ‚‚) / 2 < (aβ‚‚ + aβ‚‚) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = aβ‚‚ : add_self_div_two aβ‚‚βŸ© } lemma mul_self_inj_of_nonneg (a0 : 0 ≀ a) (b0 : 0 ≀ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ Ξ» h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right {c : Ξ±} (hc : 0 ≀ c) (a b : Ξ±) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (Ξ» x y, div_le_div_of_le hc) lemma max_div_div_right {c : Ξ±} (hc : 0 ≀ c) (a b : Ξ±) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (Ξ» x y, div_le_div_of_le hc) lemma min_div_div_right_of_nonpos {c : Ξ±} (hc : c ≀ 0) (a b : Ξ±) : min (a / c) (b / c) = (max a b) / c := eq.symm $ @monotone.map_max Ξ± (order_dual Ξ±) _ _ _ _ _ (Ξ» x y, div_le_div_of_nonpos_of_le hc) lemma max_div_div_right_of_nonpos {c : Ξ±} (hc : c ≀ 0) (a b : Ξ±) : max (a / c) (b / c) = (min a b) / c := eq.symm $ @monotone.map_min Ξ± (order_dual Ξ±) _ _ _ _ _ (Ξ» x y, div_le_div_of_nonpos_of_le hc) lemma abs_div (a b : Ξ±) : abs (a / b) = abs a / abs b := (abs_hom : monoid_with_zero_hom Ξ± Ξ±).map_div a b lemma abs_one_div (a : Ξ±) : abs (1 / a) = 1 / abs a := by rw [abs_div, abs_one] lemma abs_inv (a : Ξ±) : abs a⁻¹ = (abs a)⁻¹ := (abs_hom : monoid_with_zero_hom Ξ± Ξ±).map_inv' a end linear_ordered_field
bee9b4dd5df39f28d3e7f58fa4f08331676d1d4f
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/topology/algebra/infinite_sum.lean
2891eae6bac733b06264ece7430459689b43a72a
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,317
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl -/ import algebra.big_operators.intervals import topology.instances.real import data.indicator_function import data.equiv.encodable.lattice import order.filter.at_top_bot /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 Β§5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} section has_sum variables [add_comm_monoid Ξ±] [topological_space Ξ±] /-- Infinite sum on a topological monoid The `at_top` filter on `finset Ξ±` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. For the definition or many statements, Ξ± does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : Ξ² β†’ Ξ±) (a : Ξ±) : Prop := tendsto (Ξ»s:finset Ξ², βˆ‘ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : Ξ² β†’ Ξ±) : Prop := βˆƒa, has_sum f a /-- `βˆ‘' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {Ξ²} (f : Ξ² β†’ Ξ±) := if h : summable f then classical.some h else 0 notation `βˆ‘'` binders `, ` r:(scoped f, tsum f) := r variables {f g : Ξ² β†’ Ξ±} {a b : Ξ±} {s : finset Ξ²} lemma summable.has_sum (ha : summable f) : has_sum f (βˆ‘'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (Ξ»b, 0 : Ξ² β†’ Ξ±) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (Ξ»b, 0 : Ξ² β†’ Ξ±) := has_sum_zero.summable lemma tsum_eq_zero_of_not_summable (h : Β¬ summable f) : (βˆ‘'b, f b) = 0 := by simp [tsum, h] lemma has_sum.has_sum_of_sum_eq {g : Ξ³ β†’ Ξ±} (h_eq : βˆ€u:finset Ξ³, βˆƒv:finset Ξ², βˆ€v', v βŠ† v' β†’ βˆƒu', u βŠ† u' ∧ βˆ‘ x in u', g x = βˆ‘ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : Ξ³ β†’ Ξ±} (h₁ : βˆ€u:finset Ξ³, βˆƒv:finset Ξ², βˆ€v', v βŠ† v' β†’ βˆƒu', u βŠ† u' ∧ βˆ‘ x in u', g x = βˆ‘ b in v', f b) (hβ‚‚ : βˆ€v:finset Ξ², βˆƒu:finset Ξ³, βˆ€u', u βŠ† u' β†’ βˆƒv', v βŠ† v' ∧ βˆ‘ b in v', f b = βˆ‘ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq hβ‚‚, has_sum.has_sum_of_sum_eq hβ‚βŸ© lemma function.injective.has_sum_iff {g : Ξ³ β†’ Ξ²} (hg : injective g) (hf : βˆ€ x βˆ‰ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : Ξ³ β†’ Ξ²} (hg : injective g) (hf : βˆ€ x βˆ‰ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ Ξ» _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set Ξ²} (hf : support f βŠ† s) : has_sum (f ∘ coe : s β†’ Ξ±) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set Ξ²} : has_sum (f ∘ coe : s β†’ Ξ±) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f β†’ Ξ±) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype Ξ²] (f : Ξ² β†’ Ξ±) : has_sum f (βˆ‘ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : has_sum (f ∘ coe : (↑s : set Ξ²) β†’ Ξ±) (βˆ‘ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : summable (f ∘ coe : (↑s : set Ξ²) β†’ Ξ±) := (s.has_sum f).summable protected lemma set.finite.summable {s : set Ξ²} (hs : s.finite) (f : Ξ² β†’ Ξ±) : summable (f ∘ coe : s β†’ Ξ±) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `βˆ‘ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : βˆ€bβˆ‰s, f b = 0) : has_sum f (βˆ‘ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : βˆ€bβˆ‰s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : Ξ² β†’ Ξ±} (b : Ξ²) (hf : βˆ€b' β‰  b, f b' = 0) : has_sum f (f b) := suffices has_sum f (βˆ‘ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : Ξ²) (a : Ξ±) : has_sum (Ξ»b', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : Ξ³ ≃ Ξ²) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma equiv.summable_iff (e : Ξ³ ≃ Ξ²) : summable (f ∘ e) ↔ summable f := exists_congr $ Ξ» a, e.has_sum_iff lemma summable.prod_symm {f : Ξ² Γ— Ξ³ β†’ Ξ±} (hf : summable f) : summable (Ξ» p : Ξ³ Γ— Ξ², f p.swap) := (equiv.prod_comm Ξ³ Ξ²).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : Ξ³ β†’ Ξ±} (e : support f ≃ support g) (he : βˆ€ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : Ξ³ β†’ Ξ±} (i : support g β†’ Ξ²) (hi : βˆ€ ⦃x y⦄, i x = i y β†’ (x : Ξ³) = y) (hf : support f βŠ† set.range i) (hfg : βˆ€ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (Ξ» x, ⟨i x, Ξ» hx, x.coe_prop $ hfg x β–Έ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, Ξ» y, (hf y.coe_prop).imp $ Ξ» x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : Ξ³ β†’ Ξ±} (e : support f ≃ support g) (he : βˆ€ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ Ξ» _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid Ξ³] [topological_space Ξ³] (hf : has_sum f a) (g : Ξ± β†’+ Ξ³) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (Ξ»s:finset Ξ², βˆ‘ b in s, f b) = (Ξ»s:finset Ξ², βˆ‘ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (Ξ»s:finset Ξ², βˆ‘ b in s, g (f b)) at_top (𝓝 (g a)), from this β–Έ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid Ξ³] [topological_space Ξ³] (hf : summable f) (g : Ξ± β†’+ Ξ³) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : β„• β†’ Ξ±` has sum `a`, then the partial sums `βˆ‘_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : β„• β†’ Ξ±} (h : has_sum f a) : tendsto (Ξ»n:β„•, βˆ‘ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ aβ‚‚ : Ξ±} [t2_space Ξ±] : has_sum f a₁ β†’ has_sum f aβ‚‚ β†’ a₁ = aβ‚‚ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space Ξ±] {f : β„• β†’ Ξ±} {a : Ξ±} (hf : summable f) : has_sum f a ↔ tendsto (Ξ»n:β„•, βˆ‘ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, Ξ» h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {Ξ±' : Type*} [add_comm_monoid Ξ±'] [topological_space Ξ±'] (e : Ξ±' ≃ Ξ±) {f : Ξ² β†’ Ξ±} {g : Ξ³ β†’ Ξ±'} (he : βˆ€ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, Ξ» ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add Ξ±] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (Ξ»b, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (Ξ»b, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : Ξ³ β†’ Ξ² β†’ Ξ±} {a : Ξ³ β†’ Ξ±} {s : finset Ξ³} : (βˆ€i∈s, has_sum (f i) (a i)) β†’ has_sum (Ξ»b, βˆ‘ i in s, f i b) (βˆ‘ i in s, a i) := finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum.add] {contextual := tt}) lemma summable_sum {f : Ξ³ β†’ Ξ² β†’ Ξ±} {s : finset Ξ³} (hf : βˆ€i∈s, summable (f i)) : summable (Ξ»b, βˆ‘ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_compl {s : set Ξ²} (ha : has_sum (f ∘ coe : s β†’ Ξ±) a) (hb : has_sum (f ∘ coe : sᢜ β†’ Ξ±) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.add_compl {s : set Ξ²} (hs : summable (f ∘ coe : s β†’ Ξ±)) (hsc : summable (f ∘ coe : sᢜ β†’ Ξ±)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set Ξ²} (ha : has_sum (f ∘ coe : sᢜ β†’ Ξ±) a) (hb : has_sum (f ∘ coe : s β†’ Ξ±) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.compl_add {s : set Ξ²} (hs : summable (f ∘ coe : sᢜ β†’ Ξ±)) (hsc : summable (f ∘ coe : s β†’ Ξ±)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma has_sum.sigma [regular_space Ξ±] {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£ b:Ξ², Ξ³ b) β†’ Ξ±} {g : Ξ² β†’ Ξ±} {a : Ξ±} (ha : has_sum f a) (hf : βˆ€b, has_sum (Ξ»c, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (Ξ» t : finset (Ξ£ b, Ξ³ b), βˆ‘ p in t.filter (Ξ» p, p.1 ∈ bs), f p) at_top (𝓝 $ βˆ‘ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (Ξ» b hb, _), change tendsto (Ξ» t, (Ξ» t, βˆ‘ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, Ξ» t ht, hu _ (Ξ» x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `Ξ² Γ— Ξ³` has sum `a` and for each `b` the restriction of `f` to `{b} Γ— Ξ³` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space Ξ±] {f : Ξ² Γ— Ξ³ β†’ Ξ±} {g : Ξ² β†’ Ξ±} {a : Ξ±} (ha : has_sum f a) (hf : βˆ€b, has_sum (Ξ»c, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod Ξ² Ξ³).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space Ξ±] {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£b:Ξ², Ξ³ b) β†’ Ξ±} (ha : summable f) (hf : βˆ€b, summable (Ξ»c, f ⟨b, c⟩)) : summable (Ξ»b, βˆ‘'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space Ξ±] {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£ b:Ξ², Ξ³ b) β†’ Ξ±} {g : Ξ² β†’ Ξ±} {a : Ξ±} (ha : has_sum g a) (hf : βˆ€b, has_sum (Ξ»c, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid Ξ±] [topological_space Ξ±] [t2_space Ξ±] variables {f g : Ξ² β†’ Ξ±} {a a₁ aβ‚‚ : Ξ±} lemma has_sum.tsum_eq (ha : has_sum f a) : (βˆ‘'b, f b) = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ (βˆ‘'b, f b) = a := iff.intro has_sum.tsum_eq (assume eq, eq β–Έ h.has_sum) @[simp] lemma tsum_zero : (βˆ‘'b:Ξ², 0:Ξ±) = 0 := has_sum_zero.tsum_eq lemma tsum_eq_sum {f : Ξ² β†’ Ξ±} {s : finset Ξ²} (hf : βˆ€bβˆ‰s, f b = 0) : (βˆ‘'b, f b) = βˆ‘ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_fintype [fintype Ξ²] (f : Ξ² β†’ Ξ±) : (βˆ‘'b, f b) = βˆ‘ b, f b := (has_sum_fintype f).tsum_eq @[simp] lemma finset.tsum_subtype (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : (βˆ‘'x : {x // x ∈ s}, f x) = βˆ‘ x in s, f x := (s.has_sum f).tsum_eq lemma tsum_eq_single {f : Ξ² β†’ Ξ±} (b : Ξ²) (hf : βˆ€b' β‰  b, f b' = 0) : (βˆ‘'b, f b) = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : Ξ²) (a : Ξ±) : (βˆ‘'b', if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {Ξ±' : Type*} [add_comm_monoid Ξ±'] [topological_space Ξ±'] (e : Ξ±' ≃ Ξ±) (h0 : e 0 = 0) {f : Ξ² β†’ Ξ±} {g : Ξ³ β†’ Ξ±'} (h : βˆ€ {a}, has_sum f (e a) ↔ has_sum g a) : (βˆ‘' b, f b) = e (βˆ‘' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : Β¬ summable g, have hf : Β¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : Ξ² β†’ Ξ±} {g : Ξ³ β†’ Ξ±} (h : βˆ€{a}, has_sum f a ↔ has_sum g a) : (βˆ‘'b, f b) = (βˆ‘'c, g c) := (equiv.refl Ξ±).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : Ξ³ ≃ Ξ²) (f : Ξ² β†’ Ξ±) : (βˆ‘'c, f (j c)) = (βˆ‘'b, f b) := tsum_eq_tsum_of_has_sum_iff_has_sum $ Ξ» a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : Ξ² β†’ Ξ±} {g : Ξ³ β†’ Ξ±} (e : support f ≃ support g) (he : βˆ€ x, g (e x) = f x) : (βˆ‘' x, f x) = βˆ‘' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ Ξ» _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : Ξ³ β†’ Ξ±} (i : support g β†’ Ξ²) (hi : βˆ€ ⦃x y⦄, i x = i y β†’ (x : Ξ³) = y) (hf : support f βŠ† set.range i) (hfg : βˆ€ x, f (i x) = g x) : (βˆ‘' x, f x) = βˆ‘' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ Ξ» _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set Ξ²) (f : Ξ² β†’ Ξ±) : (βˆ‘' x : s, f x) = βˆ‘' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ Ξ» _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add Ξ±] lemma tsum_add (hf : summable f) (hg : summable g) : (βˆ‘'b, f b + g b) = (βˆ‘'b, f b) + (βˆ‘'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : Ξ³ β†’ Ξ² β†’ Ξ±} {s : finset Ξ³} (hf : βˆ€i∈s, summable (f i)) : (βˆ‘'b, βˆ‘ i in s, f i b) = βˆ‘ i in s, βˆ‘'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space Ξ±] {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£b:Ξ², Ξ³ b) β†’ Ξ±} (h₁ : βˆ€b, summable (Ξ»c, f ⟨b, c⟩)) (hβ‚‚ : summable f) : (βˆ‘'p, f p) = (βˆ‘'b c, f ⟨b, c⟩) := (hβ‚‚.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space Ξ±] {f : Ξ² Γ— Ξ³ β†’ Ξ±} (h : summable f) (h₁ : βˆ€b, summable (Ξ»c, f (b, c))) : (βˆ‘'p, f p) = (βˆ‘'b c, f (b, c)) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space Ξ±] {f : Ξ² β†’ Ξ³ β†’ Ξ±} (h : summable (function.uncurry f)) (h₁ : βˆ€b, summable (f b)) (hβ‚‚ : βˆ€ c, summable (Ξ» b, f b c)) : (βˆ‘' c b, f b c) = (βˆ‘' b c, f b c) := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm hβ‚‚, ← (equiv.prod_comm Ξ² Ξ³).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable Ξ³] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 [complete_lattice Ξ²] (m : Ξ² β†’ Ξ±) (m0 : m βŠ₯ = 0) (s : Ξ³ β†’ Ξ²) : (βˆ‘' i : β„•, m (⨆ b ∈ decode2 Ξ³ i, s b)) = (βˆ‘' b : Ξ³, m (s b)) := begin have H : βˆ€ n, m (⨆ b ∈ decode2 Ξ³ n, s b) β‰  0 β†’ (decode2 Ξ³ n).is_some, { intros n h, cases decode2 Ξ³ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (Ξ» a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek2] at h ⊒, convert h, simp [set.ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode2 Ξ³ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 (m : set Ξ² β†’ Ξ±) (m0 : m βˆ… = 0) (s : Ξ³ β†’ set Ξ²) : (βˆ‘' i, m (⋃ b ∈ decode2 Ξ³ i, s b)) = (βˆ‘' b, m (s b)) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≀)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice Ξ²] (m : Ξ² β†’ Ξ±) (m0 : m βŠ₯ = 0) (R : Ξ± β†’ Ξ± β†’ Prop) (m_supr : βˆ€(s : β„• β†’ Ξ²), R (m (⨆ i, s i)) (βˆ‘' i, m (s i))) (s : Ξ³ β†’ Ξ²) : R (m (⨆ b : Ξ³, s b)) (βˆ‘' b : Ξ³, m (s b)) := by { rw [← supr_decode2, ← tsum_supr_decode2 _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice Ξ²] (m : Ξ² β†’ Ξ±) (m0 : m βŠ₯ = 0) (R : Ξ± β†’ Ξ± β†’ Prop) (m_supr : βˆ€(s : β„• β†’ Ξ²), R (m (⨆ i, s i)) (βˆ‘' i, m (s i))) (s : Ξ΄ β†’ Ξ²) (t : finset Ξ΄) : R (m (⨆ d ∈ t, s d)) (βˆ‘ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice Ξ²] (m : Ξ² β†’ Ξ±) (m0 : m βŠ₯ = 0) (R : Ξ± β†’ Ξ± β†’ Prop) (m_supr : βˆ€(s : β„• β†’ Ξ²), R (m (⨆ i, s i)) (βˆ‘' i, m (s i))) (s₁ sβ‚‚ : Ξ²) : R (m (s₁ βŠ” sβ‚‚)) (m s₁ + m sβ‚‚) := begin convert rel_supr_tsum m m0 R m_supr (Ξ» b, cond b s₁ sβ‚‚), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable end tsum section pi variables {ΞΉ : Type*} {Ο€ : Ξ± β†’ Type*} [βˆ€ x, add_comm_monoid (Ο€ x)] [βˆ€ x, topological_space (Ο€ x)] lemma pi.has_sum {f : ΞΉ β†’ βˆ€ x, Ο€ x} {g : βˆ€ x, Ο€ x} : has_sum f g ↔ βˆ€ x, has_sum (Ξ» i, f i x) (g x) := by simp [has_sum, tendsto_pi] lemma pi.summable {f : ΞΉ β†’ βˆ€ x, Ο€ x} : summable f ↔ βˆ€ x, summable (Ξ» i, f i x) := by simp [summable, pi.has_sum, classical.skolem] lemma tsum_apply [βˆ€ x, t2_space (Ο€ x)] {f : ΞΉ β†’ βˆ€ x, Ο€ x}{x : Ξ±} (hf : summable f) : (βˆ‘' i, f i) x = βˆ‘' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group Ξ±] [topological_space Ξ±] [topological_add_group Ξ±] variables {f g : Ξ² β†’ Ξ±} {a a₁ aβ‚‚ : Ξ±} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (Ξ»b, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id Ξ±) continuous_neg lemma summable.neg (hf : summable f) : summable (Ξ»b, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (Ξ»b, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (Ξ» b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g aβ‚‚) : has_sum (Ξ»b, f b - g b) (a₁ - aβ‚‚) := by { simp [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (Ξ»b, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma has_sum.has_sum_compl_iff {s : set Ξ²} (hf : has_sum (f ∘ coe : s β†’ Ξ±) a₁) : has_sum (f ∘ coe : sᢜ β†’ Ξ±) aβ‚‚ ↔ has_sum f (a₁ + aβ‚‚) := begin refine ⟨λ h, hf.add_compl h, Ξ» h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊒, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set Ξ²} (hf : has_sum (f ∘ coe : s β†’ Ξ±) a₁) : has_sum f aβ‚‚ ↔ has_sum (f ∘ coe : sᢜ β†’ Ξ±) (aβ‚‚ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set Ξ²} (hf : summable (f ∘ coe : s β†’ Ξ±)) : summable (f ∘ coe : sᢜ β†’ Ξ±) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, Ξ» ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset Ξ²) : has_sum (Ξ» x : {x // x βˆ‰ s}, f x) a ↔ has_sum f (a + βˆ‘ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset Ξ²) : has_sum f a ↔ has_sum (Ξ» x : {x // x βˆ‰ s}, f x) (a - βˆ‘ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset Ξ²) : summable (Ξ» x : {x // x βˆ‰ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set Ξ²} (hs : s.finite) : summable (f ∘ coe : sᢜ β†’ Ξ±) ↔ summable f := (hs.summable f).summable_compl_iff section tsum variables [t2_space Ξ±] lemma tsum_neg (hf : summable f) : (βˆ‘'b, - f b) = - (βˆ‘'b, f b) := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : (βˆ‘'b, f b - g b) = (βˆ‘'b, f b) - (βˆ‘'b, g b) := (hf.has_sum.sub hg.has_sum).tsum_eq lemma tsum_add_tsum_compl {s : set Ξ²} (hs : summable (f ∘ coe : s β†’ Ξ±)) (hsc : summable (f ∘ coe : sᢜ β†’ Ξ±)) : (βˆ‘' x : s, f x) + (βˆ‘' x : sᢜ, f x) = βˆ‘' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma sum_add_tsum_compl {s : finset Ξ²} (hf : summable f) : (βˆ‘ x in s, f x) + (βˆ‘' x : (↑s : set Ξ²)ᢜ, f x) = βˆ‘' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm end tsum /-! ### Sums on subtypes If `s` is a finset of `Ξ±`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `β„•`, we deduce the formula `(βˆ‘ i in range k, f i) + (βˆ‘' i, f (i + k)) = (βˆ‘' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype variables {s : finset Ξ²} lemma has_sum_nat_add_iff {f : β„• β†’ Ξ±} (k : β„•) {a : Ξ±} : has_sum (Ξ» n, f (n + k)) a ↔ has_sum f (a + βˆ‘ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : β„• β†’ Ξ±} (k : β„•) : summable (Ξ» n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (βˆ‘ i in range k, f i)).summable_iff_of_has_sum_iff $ Ξ» a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : β„• β†’ Ξ±} (k : β„•) {a : Ξ±} : has_sum (Ξ» n, f (n + k)) (a - βˆ‘ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space Ξ±] {f : β„• β†’ Ξ±} (k : β„•) (h : summable f) : (βˆ‘ i in range k, f i) + (βˆ‘' i, f (i + k)) = (βˆ‘' i, f i) := by simpa [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space Ξ±] {f : β„• β†’ Ξ±} (hf : summable f) : (βˆ‘'b, f b) = f 0 + (βˆ‘'b, f (b + 1)) := by simpa only [range_one, sum_singleton] using (sum_add_tsum_nat_add 1 hf).symm end subtype end topological_group section topological_semiring variables [semiring Ξ±] [topological_space Ξ±] [topological_semiring Ξ±] variables {f g : Ξ² β†’ Ξ±} {a a₁ aβ‚‚ : Ξ±} lemma has_sum.mul_left (aβ‚‚) (h : has_sum f a₁) : has_sum (Ξ»b, aβ‚‚ * f b) (aβ‚‚ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left aβ‚‚) (continuous_const.mul continuous_id) lemma has_sum.mul_right (aβ‚‚) (hf : has_sum f a₁) : has_sum (Ξ»b, f b * aβ‚‚) (a₁ * aβ‚‚) := by simpa only using hf.map (add_monoid_hom.mul_right aβ‚‚) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (Ξ»b, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (Ξ»b, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space Ξ±] lemma tsum_mul_left (a) (hf : summable f) : (βˆ‘'b, a * f b) = a * (βˆ‘'b, f b) := (hf.has_sum.mul_left _).tsum_eq lemma tsum_mul_right (a) (hf : summable f) : (βˆ‘'b, f b * a) = (βˆ‘'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_semiring section division_ring variables [division_ring Ξ±] [topological_space Ξ±] [topological_semiring Ξ±] {f g : Ξ² β†’ Ξ±} {a a₁ aβ‚‚ : Ξ±} lemma has_sum_mul_left_iff (h : aβ‚‚ β‰  0) : has_sum f a₁ ↔ has_sum (Ξ»b, aβ‚‚ * f b) (aβ‚‚ * a₁) := ⟨has_sum.mul_left _, Ξ» H, by simpa only [inv_mul_cancel_left' h] using H.mul_left aβ‚‚β»ΒΉβŸ© lemma has_sum_mul_right_iff (h : aβ‚‚ β‰  0) : has_sum f a₁ ↔ has_sum (Ξ»b, f b * aβ‚‚) (a₁ * aβ‚‚) := ⟨has_sum.mul_right _, Ξ» H, by simpa only [mul_inv_cancel_right' h] using H.mul_right aβ‚‚β»ΒΉβŸ© lemma summable_mul_left_iff (h : a β‰  0) : summable f ↔ summable (Ξ»b, a * f b) := ⟨λ H, H.mul_left _, Ξ» H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a β‰  0) : summable f ↔ summable (Ξ»b, f b * a) := ⟨λ H, H.mul_right _, Ξ» H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a⁻¹⟩ end division_ring section order_topology variables [ordered_add_comm_monoid Ξ±] [topological_space Ξ±] [order_closed_topology Ξ±] variables {f g : Ξ² β†’ Ξ±} {a a₁ aβ‚‚ : Ξ±} lemma has_sum_le (h : βˆ€b, f b ≀ g b) (hf : has_sum f a₁) (hg : has_sum g aβ‚‚) : a₁ ≀ aβ‚‚ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : Ξ³ β†’ Ξ±} (i : Ξ² β†’ Ξ³) (hi : injective i) (hs : βˆ€cβˆ‰set.range i, 0 ≀ g c) (h : βˆ€b, f b ≀ g (i b)) (hf : has_sum f a₁) (hg : has_sum g aβ‚‚) : a₁ ≀ aβ‚‚ := have has_sum (Ξ»c, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ cβ‚‚ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : Ξ³ β†’ Ξ±} (i : Ξ² β†’ Ξ³) (hi : injective i) (hs : βˆ€cβˆ‰set.range i, 0 ≀ g c) (h : βˆ€b, f b ≀ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≀ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum {f : Ξ² β†’ Ξ±} (s : finset Ξ²) (hs : βˆ€ bβˆ‰s, 0 ≀ f b) (hf : has_sum f a) : βˆ‘ b in s, f b ≀ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, Ξ» t hst, sum_le_sum_of_subset_of_nonneg hst $ Ξ» b hbt hbs, hs b hbs⟩) lemma le_has_sum (hf : has_sum f a) (b : Ξ²) (hb : βˆ€ b' β‰  b, 0 ≀ f b') : f b ≀ a := calc f b = βˆ‘ b in {b}, f b : finset.sum_singleton.symm ... ≀ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : Ξ² β†’ Ξ±} (s : finset Ξ²) (hs : βˆ€ bβˆ‰s, 0 ≀ f b) (hf : summable f) : βˆ‘ b in s, f b ≀ tsum f := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : Ξ²) (hb : βˆ€ b' β‰  b, 0 ≀ f b') : f b ≀ βˆ‘' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : βˆ€b, f b ≀ g b) (hf : summable f) (hg : summable g) : (βˆ‘'b, f b) ≀ (βˆ‘'b, g b) := has_sum_le h hf.has_sum hg.has_sum lemma tsum_nonneg (h : βˆ€ b, 0 ≀ g b) : 0 ≀ (βˆ‘'b, g b) := begin by_cases hg : summable g, { simpa using tsum_le_tsum h summable_zero hg }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : βˆ€ b, f b ≀ 0) : (βˆ‘'b, f b) ≀ 0 := begin by_cases hf : summable f, { simpa using tsum_le_tsum h hf summable_zero}, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section canonically_ordered variables [canonically_ordered_add_monoid Ξ±] [topological_space Ξ±] [order_closed_topology Ξ±] variables {f : Ξ² β†’ Ξ±} {a : Ξ±} lemma le_has_sum' (hf : has_sum f a) (b : Ξ²) : f b ≀ a := le_has_sum hf b $ Ξ» _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : Ξ²) : f b ≀ βˆ‘' b, f b := le_tsum hf b $ Ξ» _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ βˆ€ x, f x = 0 := begin refine ⟨_, Ξ» h, _⟩, { contrapose!, exact Ξ» ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : (βˆ‘' i, f i) = 0 ↔ βˆ€ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] end canonically_ordered section uniform_group variables [add_comm_group Ξ±] [uniform_space Ξ±] lemma summable_iff_cauchy_seq_finset [complete_space Ξ±] {f : Ξ² β†’ Ξ±} : summable f ↔ cauchy_seq (Ξ» (s : finset Ξ²), βˆ‘ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group Ξ±] {f g : Ξ² β†’ Ξ±} {a a₁ aβ‚‚ : Ξ±} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (Ξ» (s : finset Ξ²), βˆ‘ b in s, f b) ↔ βˆ€ e ∈ 𝓝 (0:Ξ±), (βˆƒs:finset Ξ², βˆ€t, disjoint t s β†’ βˆ‘ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero Ξ±, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, sβ‚‚βŸ©, h⟩, use [s₁ βˆͺ sβ‚‚], assume t ht, specialize h (s₁ βˆͺ sβ‚‚, (s₁ βˆͺ sβ‚‚) βˆͺ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, tβ‚‚βŸ© ⟨ht₁, htβ‚‚βŸ©, have : βˆ‘ b in tβ‚‚, f b - βˆ‘ b in t₁, f b = βˆ‘ b in tβ‚‚ \ s, f b - βˆ‘ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff htβ‚‚).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end variable [complete_space Ξ±] lemma summable_iff_vanishing : summable f ↔ βˆ€ e ∈ 𝓝 (0:Ξ±), (βˆƒs:finset Ξ², βˆ€t, disjoint t s β†’ βˆ‘ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : βˆ€b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : βˆ‘ b in t.filter (Ξ»b, g b = f b), f b = βˆ‘ b in t, g b := calc βˆ‘ b in t.filter (Ξ»b, g b = f b), f b = βˆ‘ b in t.filter (Ξ»b, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = βˆ‘ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(βˆ‰), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq β–Έ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set Ξ²) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : Ξ³ β†’ Ξ²} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact Ξ» x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set Ξ²) : summable (f ∘ coe : s β†’ Ξ±) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set Ξ²} : summable (Ξ» x : s, f x) ∧ summable (Ξ» x : sᢜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, Ξ» h, ⟨h.subtype s, h.subtype sᢜ⟩⟩ lemma summable.sigma_factor {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£b:Ξ², Ξ³ b) β†’ Ξ±} (ha : summable f) (b : Ξ²) : summable (Ξ»c, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [regular_space Ξ±] {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£b:Ξ², Ξ³ b) β†’ Ξ±} (ha : summable f) : summable (Ξ»b, βˆ‘'c, f ⟨b, c⟩) := ha.sigma' (Ξ» b, ha.sigma_factor b) lemma summable.prod_factor {f : Ξ² Γ— Ξ³ β†’ Ξ±} (h : summable f) (b : Ξ²) : summable (Ξ» c, f (b, c)) := h.comp_injective $ Ξ» c₁ cβ‚‚ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [regular_space Ξ±] {Ξ³ : Ξ² β†’ Type*} {f : (Ξ£b:Ξ², Ξ³ b) β†’ Ξ±} (ha : summable f) : (βˆ‘'p, f p) = (βˆ‘'b c, f ⟨b, c⟩) := tsum_sigma' (Ξ» b, ha.sigma_factor b) ha lemma tsum_prod [regular_space Ξ±] {f : Ξ² Γ— Ξ³ β†’ Ξ±} (h : summable f) : (βˆ‘'p, f p) = (βˆ‘'b c, f ⟨b, c⟩) := tsum_prod' h h.prod_factor lemma tsum_comm [regular_space Ξ±] {f : Ξ² β†’ Ξ³ β†’ Ξ±} (h : summable (function.uncurry f)) : (βˆ‘' c b, f b c) = (βˆ‘' b c, f b c) := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : Ξ± β†’ G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : βˆƒ s : finset Ξ±, βˆ€ t, disjoint t s β†’ βˆ‘ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (Ξ» x hx, _), by simpa using hs {x} (singleton_disjoint.2 hx) end end topological_group lemma summable_abs_iff [linear_ordered_add_comm_group Ξ²] [uniform_space Ξ²] [uniform_add_group Ξ²] [complete_space Ξ²] {f : Ξ± β†’ Ξ²} : summable (Ξ» x, abs (f x)) ↔ summable f := have h1 : βˆ€ x : {x | 0 ≀ f x}, abs (f x) = f x := Ξ» x, abs_of_nonneg x.2, have h2 : βˆ€ x : {x | 0 ≀ f x}ᢜ, abs (f x) = -f x := Ξ» x, abs_of_neg (not_le.1 x.2), calc summable (Ξ» x, abs (f x)) ↔ summable (Ξ» x : {x | 0 ≀ f x}, abs (f x)) ∧ summable (Ξ» x : {x | 0 ≀ f x}ᢜ, abs (f x)) : summable_subtype_and_compl.symm ... ↔ summable (Ξ» x : {x | 0 ≀ f x}, f x) ∧ summable (Ξ» x : {x | 0 ≀ f x}ᢜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space Ξ±] {f : β„• β†’ Ξ±} (d : β„• β†’ nnreal) (hf : βˆ€ n, edist (f n) (f n.succ) ≀ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (Ξ» Ξ΅ Ξ΅pos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (Ξ» (n : β„•), βˆ‘ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd Ξ΅ (nnreal.coe_pos.2 Ξ΅pos)).imp (Ξ» N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (Ξ» k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space Ξ±] {f : β„• β†’ Ξ±} (d : β„• β†’ ℝ) (hf : βˆ€ n, dist (f n) (f n.succ) ≀ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λΡ Ξ΅pos, _), replace hd : cauchy_seq (Ξ» (n : β„•), βˆ‘ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd Ξ΅ Ξ΅pos).imp (Ξ» N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≀ βˆ‘ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (Ξ» k _ _, hf k) ... ≀ abs (βˆ‘ x in Ico N n, d x) : le_abs_self _ ... < Ξ΅ : hsum end lemma cauchy_seq_of_summable_dist [metric_space Ξ±] {f : β„• β†’ Ξ±} (h : summable (Ξ»n, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (Ξ» _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space Ξ±] {f : β„• β†’ Ξ±} (d : β„• β†’ ℝ) (hf : βˆ€ n, dist (f n) (f n.succ) ≀ d n) (hd : summable d) {a : Ξ±} (ha : tendsto f at_top (𝓝 a)) (n : β„•) : dist (f n) a ≀ βˆ‘' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, Ξ» m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (Ξ» k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (Ξ» _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendstoβ‚€ [metric_space Ξ±] {f : β„• β†’ Ξ±} (d : β„• β†’ ℝ) (hf : βˆ€ n, dist (f n) (f n.succ) ≀ d n) (hd : summable d) {a : Ξ±} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≀ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space Ξ±] {f : β„• β†’ Ξ±} (h : summable (Ξ»n, dist (f n) (f n.succ))) {a : Ξ±} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≀ βˆ‘' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≀ βˆ‘' m, (Ξ»x, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (Ξ» n, dist (f n) (f n.succ)) (Ξ» _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendstoβ‚€ [metric_space Ξ±] {f : β„• β†’ Ξ±} (h : summable (Ξ»n, dist (f n) (f n.succ))) {a : Ξ±} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≀ βˆ‘' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
2d45b29f086af0e0e8d2e1966b5c29573d3d0f0d
a45212b1526d532e6e83c44ddca6a05795113ddc
/test/library_search/ring_theory.lean
b8e473d78669a0262c700b5e392a080374b4007e
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
540
lean
import tactic.library_search import ring_theory.principal_ideal_domain import ring_theory.polynomial set_option trace.silence_library_search true example {Ξ± : Type} [euclidean_domain Ξ±] {S : ideal Ξ±} {x y : Ξ±} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := by library_search -- exact mod_mem_iff hy variables {R : Type} [comm_ring R] [decidable_eq R] variables {I : ideal (polynomial R)} example {m n : β„•} (H : m ≀ n) : I.leading_coeff_nth m ≀ I.leading_coeff_nth n := by library_search -- exact ideal.leading_coeff_nth_mono I H
73189e9b208a94862bee9cb8228dbc6770aa85a3
f57749ca63d6416f807b770f67559503fdb21001
/hott/hit/two_quotient.hlean
11e84995cef0611d01688fd3378fadec72ea9638
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,286
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import hit.circle types.eq2 algebra.e_closure types.cubical.cube open quotient eq circle sum sigma equiv function relation namespace simple_two_quotient section parameters {A : Type} (R : A β†’ A β†’ Type) local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R parameter (Q : Π⦃a⦄, T a a β†’ Type) variables ⦃a a' : A⦄ {s : R a a'} {r : T a a} local abbreviation B := A ⊎ Ξ£(a : A) (r : T a a), Q r inductive pre_two_quotient_rel : B β†’ B β†’ Type := | pre_Rmk {} : Π⦃a a'⦄ (r : R a a'), pre_two_quotient_rel (inl a) (inl a') --BUG: if {} not provided, the alias for pre_Rmk is wrong definition pre_two_quotient := quotient pre_two_quotient_rel open pre_two_quotient_rel local abbreviation C := quotient pre_two_quotient_rel protected definition j [constructor] (a : A) : C := class_of pre_two_quotient_rel (inl a) protected definition pre_aux [constructor] (q : Q r) : C := class_of pre_two_quotient_rel (inr ⟨a, r, q⟩) protected definition e (s : R a a') : j a = j a' := eq_of_rel _ (pre_Rmk s) protected definition et (t : T a a') : j a = j a' := e_closure.elim e t protected definition f [unfold 7] (q : Q r) : SΒΉ β†’ C := circle.elim (j a) (et r) protected definition pre_rec [unfold 8] {P : C β†’ Type} (Pj : Ξ a, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') (x : C) : P x := begin induction x with p, { induction p, { apply Pj}, { induction a with a1 a2, induction a2, apply Pa}}, { induction H, esimp, apply Pe}, end protected definition pre_elim [unfold 8] {P : Type} (Pj : A β†’ P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r β†’ P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') (x : C) : P := pre_rec Pj Pa (Ξ»a a' s, pathover_of_eq (Pe s)) x protected theorem rec_e {P : C β†’ Type} (Pj : Ξ a, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (s : R a a') : apdo (pre_rec Pj Pa Pe) (e s) = Pe s := !rec_eq_of_rel protected theorem elim_e {P : Type} (Pj : A β†’ P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r β†’ P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (s : R a a') : ap (pre_elim Pj Pa Pe) (e s) = Pe s := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (e s)), rewrite [β–Έ*,-apdo_eq_pathover_of_eq_ap,↑pre_elim,rec_e], end protected definition elim_et {P : Type} (Pj : A β†’ P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r β†’ P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (t : T a a') : ap (pre_elim Pj Pa Pe) (et t) = e_closure.elim Pe t := ap_e_closure_elim_h e (elim_e Pj Pa Pe) t inductive simple_two_quotient_rel : C β†’ C β†’ Type := | Rmk {} : Ξ {a : A} {r : T a a} (q : Q r) (x : circle), simple_two_quotient_rel (f q x) (pre_aux q) open simple_two_quotient_rel definition simple_two_quotient := quotient simple_two_quotient_rel local abbreviation D := simple_two_quotient local abbreviation i := class_of simple_two_quotient_rel definition incl0 (a : A) : D := i (j a) protected definition aux (q : Q r) : D := i (pre_aux q) definition incl1 (s : R a a') : incl0 a = incl0 a' := ap i (e s) definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t -- "wrong" version inclt, which is ap i (p ⬝ q) instead of ap i p ⬝ ap i q -- it is used in the proof, because inclt is easier to work with protected definition incltw (t : T a a') : incl0 a = incl0 a' := ap i (et t) protected definition inclt_eq_incltw (t : T a a') : inclt t = incltw t := (ap_e_closure_elim i e t)⁻¹ definition incl2' (q : Q r) (x : SΒΉ) : i (f q x) = aux q := eq_of_rel simple_two_quotient_rel (Rmk q x) protected definition incl2w (q : Q r) : incltw r = idp := (ap02 i (elim_loop (j a) (et r))⁻¹) ⬝ (ap_compose i (f q) loop)⁻¹ ⬝ ap_weakly_constant (incl2' q) loop ⬝ !con.right_inv definition incl2 (q : Q r) : inclt r = idp := inclt_eq_incltw r ⬝ incl2w q local attribute simple_two_quotient f i D incl0 aux incl1 incl2' inclt [reducible] local attribute i aux incl0 [constructor] protected definition elim {P : Type} (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) (x : D) : P := begin induction x, { refine (pre_elim _ _ _ a), { exact P0}, { intro a r q, exact P0 a}, { exact P1}}, { exact abstract begin induction H, induction x, { exact idpath (P0 a)}, { unfold f, apply eq_pathover, apply hdeg_square, exact abstract ap_compose (pre_elim P0 _ P1) (f q) loop ⬝ ap _ !elim_loop ⬝ !elim_et ⬝ P2 q ⬝ !ap_constant⁻¹ end } end end}, end local attribute elim [unfold 8] protected definition elim_on {P : Type} (x : D) (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) : P := elim P0 P1 P2 x definition elim_incl1 {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s := (ap_compose (elim P0 P1 P2) i (e s))⁻¹ ⬝ !elim_e definition elim_inclt {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t := ap_e_closure_elim_h incl1 (elim_incl1 P2) t protected definition elim_incltw {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (incltw t) = e_closure.elim P1 t := (ap_compose (elim P0 P1 P2) i (et t))⁻¹ ⬝ !elim_et protected theorem elim_inclt_eq_elim_incltw {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (t : T a a') : elim_inclt P2 t = ap (ap (elim P0 P1 P2)) (inclt_eq_incltw t) ⬝ elim_incltw P2 t := begin unfold [elim_inclt,elim_incltw,inclt_eq_incltw,et], refine !ap_e_closure_elim_h_eq ⬝ _, rewrite [ap_inv,-con.assoc], xrewrite [eq_of_square (ap_ap_e_closure_elim i (elim P0 P1 P2) e t)⁻¹ʰ], rewrite [↓incl1,con.assoc], apply whisker_left, rewrite [↑[elim_et,elim_incl1],+ap_e_closure_elim_h_eq,con_inv,↑[i,function.compose]], rewrite [-con.assoc (_ ⬝ _),con.assoc _⁻¹,con.left_inv,β–Έ*,-ap_inv,-ap_con], apply ap (ap _), krewrite [-eq_of_homotopy3_inv,-eq_of_homotopy3_con] end definition elim_incl2' {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : ap (elim P0 P1 P2) (incl2' q base) = idpath (P0 a) := !elim_eq_of_rel -- set_option pp.implicit true protected theorem elim_incl2w {P : Type} (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : square (ap02 (elim P0 P1 P2) (incl2w q)) (P2 q) (elim_incltw P2 r) idp := begin esimp [incl2w,ap02], rewrite [+ap_con (ap _),β–Έ*], xrewrite [-ap_compose (ap _) (ap i)], rewrite [+ap_inv], xrewrite [eq_top_of_square ((ap_compose_natural (elim P0 P1 P2) i (elim_loop (j a) (et r)))⁻¹ʰ⁻¹ᡛ ⬝h (ap_ap_compose (elim P0 P1 P2) i (f q) loop)⁻¹ʰ⁻¹ᡛ ⬝h ap_ap_weakly_constant (elim P0 P1 P2) (incl2' q) loop ⬝h ap_con_right_inv_sq (elim P0 P1 P2) (incl2' q base)), ↑[elim_incltw]], apply whisker_tl, rewrite [ap_weakly_constant_eq], xrewrite [naturality_apdo_eq (Ξ»x, !elim_eq_of_rel) loop], rewrite [↑elim_2,rec_loop,square_of_pathover_concato_eq,square_of_pathover_eq_concato, eq_of_square_vconcat_eq,eq_of_square_eq_vconcat], apply eq_vconcat, { apply ap (Ξ»x, _ ⬝ eq_con_inv_of_con_eq ((_ ⬝ x ⬝ _)⁻¹ ⬝ _) ⬝ _), transitivity _, apply ap eq_of_square, apply to_right_inv !eq_pathover_equiv_square (hdeg_square (elim_1 P A R Q P0 P1 a r q P2)), transitivity _, apply eq_of_square_hdeg_square, unfold elim_1, reflexivity}, rewrite [+con_inv,whisker_left_inv,+inv_inv,-whisker_right_inv, con.assoc (whisker_left _ _),con.assoc _ (whisker_right _ _),β–Έ*, whisker_right_con_whisker_left _ !ap_constant], xrewrite [-con.assoc _ _ (whisker_right _ _)], rewrite [con.assoc _ _ (whisker_left _ _),idp_con_whisker_left,β–Έ*, con.assoc _ !ap_constant⁻¹,con.left_inv], xrewrite [eq_con_inv_of_con_eq_whisker_left,β–Έ*], rewrite [+con.assoc _ _ !con.right_inv, right_inv_eq_idp ( (Ξ»(x : ap (elim P0 P1 P2) (incl2' q base) = idpath (elim P0 P1 P2 (class_of simple_two_quotient_rel (f q base)))), x) (elim_incl2' P2 q)), ↑[whisker_left]], xrewrite [con2_con_con2], rewrite [idp_con,↑elim_incl2',con.left_inv,whisker_right_inv,↑whisker_right], xrewrite [con.assoc _ _ (_ β—Ύ _)], rewrite [con.left_inv,β–Έ*,-+con.assoc,con.assoc _⁻¹,↑[elim,function.compose],con.left_inv, β–Έ*,↑j,con.left_inv,idp_con], apply square_of_eq, reflexivity end theorem elim_incl2 {P : Type} (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 r) idp := begin rewrite [↑incl2,↑ap02,ap_con,elim_inclt_eq_elim_incltw], apply whisker_tl, apply elim_incl2w end end end simple_two_quotient --attribute simple_two_quotient.j [constructor] --TODO attribute /-simple_two_quotient.rec-/ simple_two_quotient.elim [unfold 8] [recursor 8] --attribute simple_two_quotient.elim_type [unfold 9] attribute /-simple_two_quotient.rec_on-/ simple_two_quotient.elim_on [unfold 5] --attribute simple_two_quotient.elim_type_on [unfold 6] namespace two_quotient open e_closure simple_two_quotient section parameters {A : Type} (R : A β†’ A β†’ Type) local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R parameter (Q : Π⦃a a'⦄, T a a' β†’ T a a' β†’ Type) variables ⦃a a' : A⦄ {s : R a a'} {t t' : T a a'} inductive two_quotient_Q : Π⦃a : A⦄, e_closure R a a β†’ Type := | Qmk : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄, Q t t' β†’ two_quotient_Q (t ⬝r t'⁻¹ʳ) open two_quotient_Q local abbreviation Q2 := two_quotient_Q definition two_quotient := simple_two_quotient R Q2 definition incl0 (a : A) : two_quotient := incl0 _ _ a definition incl1 (s : R a a') : incl0 a = incl0 a' := incl1 _ _ s definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t definition incl2 (q : Q t t') : inclt t = inclt t' := eq_of_con_inv_eq_idp (incl2 _ _ (Qmk R q)) protected definition elim {P : Type} (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') (x : two_quotient) : P := begin induction x, { exact P0 a}, { exact P1 s}, { exact abstract [unfold 10] begin induction q with a a' t t' q, rewrite [↑e_closure.elim], apply con_inv_eq_idp, exact P2 q end end}, end local attribute elim [unfold 8] protected definition elim_on {P : Type} (x : two_quotient) (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') : P := elim P0 P1 P2 x definition elim_incl1 {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s := !elim_incl1 definition elim_inclt {P : Type} {P0 : A β†’ P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t := !elim_inclt --ap_e_closure_elim_h incl1 (elim_incl1 P2) t /- --print elim theorem elim_incl2 {P : Type} (P0 : A β†’ P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t') : square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 t) (elim_inclt P2 t') := begin -- let H := elim_incl2 R Q2 P0 P1 (two_quotient_Q.rec (Ξ» (a a' : A) (t t' : T a a') (q : Q t t'), con_inv_eq_idp (P2 q))) (Qmk R q), -- esimp at H, rewrite [↑[incl2,elim],ap_eq_of_con_inv_eq_idp], xrewrite [eq_top_of_square (elim_incl2 R Q2 P0 P1 (elim_1 A R Q P P0 P1 P2) (Qmk R q)),β–Έ*], exact sorry end -/ end end two_quotient --attribute two_quotient.j [constructor] --TODO attribute /-two_quotient.rec-/ two_quotient.elim [unfold 8] [recursor 8] --attribute two_quotient.elim_type [unfold 9] attribute /-two_quotient.rec_on-/ two_quotient.elim_on [unfold 5] --attribute two_quotient.elim_type_on [unfold 6]
0f4e0f8ed10b99ccc37374450eadda2ba0809b04
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/run/coroutine.lean
3516bb57875a11e91f1dd6973930ccb8fac1a3fc
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,600
lean
universes u v w r s inductive coroutineResultCore (coroutine : Type (max u v w)) (Ξ± : Type u) (Ξ΄ : Type v) (Ξ² : Type w) : Type (max u v w) | done : Ξ² β†’ coroutineResultCore | yielded : Ξ΄ β†’ coroutine β†’ coroutineResultCore /-- Asymmetric coroutines `coroutine Ξ± Ξ΄ Ξ²` takes inputs of Type `Ξ±`, yields elements of Type `Ξ΄`, and produces an element of Type `Ξ²`. Asymmetric coroutines are so called because they involve two types of control transfer operations: one for resuming/invoking a coroutine and one for suspending it, the latter returning control to the coroutine invoker. An asymmetric coroutine can be regarded as subordinate to its caller, the relationship between them being similar to that between a called and a calling routine. -/ inductive coroutine (Ξ± : Type u) (Ξ΄ : Type v) (Ξ² : Type w) : Type (max u v w) | mk : (Ξ± β†’ coroutineResultCore coroutine Ξ± Ξ΄ Ξ²) β†’ coroutine abbrev coroutineResult (Ξ± : Type u) (Ξ΄ : Type v) (Ξ² : Type w) : Type (max u v w) := coroutineResultCore (coroutine Ξ± Ξ΄ Ξ²) Ξ± Ξ΄ Ξ² namespace coroutine variables {Ξ± : Type u} {Ξ΄ : Type v} {Ξ² Ξ³ : Type w} export coroutineResultCore (done yielded) /-- `resume c a` resumes/invokes the coroutine `c` with input `a`. -/ @[inline] def resume : coroutine Ξ± Ξ΄ Ξ² β†’ Ξ± β†’ coroutineResult Ξ± Ξ΄ Ξ² | mk k, a => k a @[inline] protected def pure (b : Ξ²) : coroutine Ξ± Ξ΄ Ξ² := mk $ fun _ => done b /-- Read the input argument passed to the coroutine. Remark: should we use a different Name? I added an instance [MonadReader] later. -/ @[inline] protected def read : coroutine Ξ± Ξ΄ Ξ± := mk $ fun a => done a /-- Run nested coroutine with transformed input argument. Like `ReaderT.adapt`, but cannot change the input Type. -/ @[inline] protected def adapt (f : Ξ± β†’ Ξ±) (c : coroutine Ξ± Ξ΄ Ξ²) : coroutine Ξ± Ξ΄ Ξ² := mk $ fun a => c.resume (f a) /-- Return the control to the invoker with Result `d` -/ @[inline] protected def yield (d : Ξ΄) : coroutine Ξ± Ξ΄ PUnit := mk $ fun a => yielded d (coroutine.pure ⟨⟩) /- TODO(Leo): following relations have been commented because Lean4 is currently accepting non-terminating programs. /-- Auxiliary relation for showing that bind/pipe terminate -/ inductive directSubcoroutine : coroutine Ξ± Ξ΄ Ξ² β†’ coroutine Ξ± Ξ΄ Ξ² β†’ Prop | mk : βˆ€ (k : Ξ± β†’ coroutineResult Ξ± Ξ΄ Ξ²) (a : Ξ±) (d : Ξ΄) (c : coroutine Ξ± Ξ΄ Ξ²), k a = yielded d c β†’ directSubcoroutine c (mk k) theorem directSubcoroutineWf : WellFounded (@directSubcoroutine Ξ± Ξ΄ Ξ²) := begin Constructor, intro c, apply @coroutine.ind _ _ _ (fun c => Acc directSubcoroutine c) (fun r => βˆ€ (d : Ξ΄) (c : coroutine Ξ± Ξ΄ Ξ²), r = yielded d c β†’ Acc directSubcoroutine c), { intros k ih, dsimp at ih, Constructor, intros c' h, cases h, apply ih hA hD, assumption }, { intros, contradiction }, { intros d c ih d₁ c₁ Heq, injection Heq, subst c, assumption } end /-- Transitive closure of directSubcoroutine. It is not used here, but may be useful when defining more complex procedures. -/ def subcoroutine : coroutine Ξ± Ξ΄ Ξ² β†’ coroutine Ξ± Ξ΄ Ξ² β†’ Prop := Tc directSubcoroutine theorem subcoroutineWf : WellFounded (@subcoroutine Ξ± Ξ΄ Ξ²) := Tc.wf directSubcoroutineWf -- Local instances for proving termination by well founded relation def bindWfInst : HasWellFounded (Ξ£' a : coroutine Ξ± Ξ΄ Ξ², (Ξ² β†’ coroutine Ξ± Ξ΄ Ξ³)) := { r := Psigma.Lex directSubcoroutine (fun _ => emptyRelation), wf := Psigma.lexWf directSubcoroutineWf (fun _ => emptyWf) } def pipeWfInst : HasWellFounded (Ξ£' a : coroutine Ξ± Ξ΄ Ξ², coroutine Ξ΄ Ξ³ Ξ²) := { r := Psigma.Lex directSubcoroutine (fun _ => emptyRelation), wf := Psigma.lexWf directSubcoroutineWf (fun _ => emptyWf) } local attribute [instance] wfInst₁ wfInstβ‚‚ open wellFoundedTactics -/ /- TODO: remove `unsafe` keyword after we restore well-founded recursion -/ @[inlineIfReduce] protected unsafe def bind : coroutine Ξ± Ξ΄ Ξ² β†’ (Ξ² β†’ coroutine Ξ± Ξ΄ Ξ³) β†’ coroutine Ξ± Ξ΄ Ξ³ | mk k, f => mk $ fun a => match k a, rfl : βˆ€ (n : _), n = k a β†’ _ with | done b, _ => coroutine.resume (f b) a | yielded d c, h => -- have directSubcoroutine c (mk k), { apply directSubcoroutine.mk k a d, rw h }, yielded d (bind c f) -- usingWellFounded { decTac := unfoldWfRel >> processLex (tactic.assumption) } unsafe def pipe : coroutine Ξ± Ξ΄ Ξ² β†’ coroutine Ξ΄ Ξ³ Ξ² β†’ coroutine Ξ± Ξ³ Ξ² | mk k₁, mk kβ‚‚ => mk $ fun a => match k₁ a, rfl : βˆ€ (n : _), n = k₁ a β†’ _ with | done b, h => done b | yielded d k₁', h => match kβ‚‚ d with | done b => done b | yielded r kβ‚‚' => -- have directSubcoroutine k₁' (mk k₁), { apply directSubcoroutine.mk k₁ a d, rw h }, yielded r (pipe k₁' kβ‚‚') -- usingWellFounded { decTac := unfoldWfRel >> processLex (tactic.assumption) } private unsafe def finishAux (f : Ξ΄ β†’ Ξ±) : coroutine Ξ± Ξ΄ Ξ² β†’ Ξ± β†’ List Ξ΄ β†’ List Ξ΄ Γ— Ξ² | mk k, a, ds => match k a with | done b => (ds.reverse, b) | yielded d k' => finishAux k' (f d) (d::ds) /-- Run a coroutine to completion, feeding back yielded items after transforming them with `f`. -/ unsafe def finish (f : Ξ΄ β†’ Ξ±) : coroutine Ξ± Ξ΄ Ξ² β†’ Ξ± β†’ List Ξ΄ Γ— Ξ² := fun k a => finishAux f k a [] unsafe instance : Monad (coroutine Ξ± Ξ΄) := { pure := @coroutine.pure _ _, bind := @coroutine.bind _ _ } unsafe instance : MonadReader Ξ± (coroutine Ξ± Ξ΄) := { read := @coroutine.read _ _ } end coroutine /-- Auxiliary class for lifiting `yield` -/ class monadCoroutine (Ξ± : outParam (Type u)) (Ξ΄ : outParam (Type v)) (m : Type w β†’ Type r) := (yield : Ξ΄ β†’ m PUnit) instance (Ξ± : Type u) (Ξ΄ : Type v) : monadCoroutine Ξ± Ξ΄ (coroutine Ξ± Ξ΄) := { yield := coroutine.yield } instance monadCoroutineTrans (Ξ± : Type u) (Ξ΄ : Type v) (m : Type w β†’ Type r) (n : Type w β†’ Type s) [monadCoroutine Ξ± Ξ΄ m] [HasMonadLift m n] : monadCoroutine Ξ± Ξ΄ n := { yield := fun d => monadLift (monadCoroutine.yield d : m _) } export monadCoroutine (yield) open coroutine namespace ex1 inductive tree (Ξ± : Type u) | leaf : tree | Node : tree β†’ Ξ± β†’ tree β†’ tree /-- Coroutine as generators/iterators -/ unsafe def visit {Ξ± : Type v} : tree Ξ± β†’ coroutine Unit Ξ± Unit | tree.leaf => pure () | tree.Node l a r => do visit l; yield a; visit r unsafe def tst {Ξ± : Type} [HasToString Ξ±] (t : tree Ξ±) : ExceptT String IO Unit := do c ← pure $ visit t; (yielded v₁ c) ← pure (resume c ()) | throw "failed"; (yielded vβ‚‚ c) ← pure (resume c ()) | throw "failed"; IO.println $ toString v₁; IO.println $ toString vβ‚‚; pure () -- #eval tst (tree.Node (tree.Node (tree.Node tree.leaf 5 tree.leaf) 10 (tree.Node tree.leaf 20 tree.leaf)) 30 tree.leaf) end ex1 namespace ex2 unsafe def ex : StateT Nat (coroutine Nat String) Unit := do x ← read; y ← get; set (y+5); yield ("1) val: " ++ toString (x+y)); x ← read; y ← get; yield ("2) val: " ++ toString (x+y)); pure () unsafe def tst2 : ExceptT String IO Unit := do let c := StateT.run ex 5; (yielded r c₁) ← pure $ resume c 10 | throw "failed"; IO.println r; (yielded r cβ‚‚) ← pure $ resume c₁ 20 | throw "failed"; IO.println r; (done _) ← pure $ resume cβ‚‚ 30 | throw "failed"; (yielded r c₃) ← pure $ resume c₁ 100 | throw "failed"; IO.println r; IO.println "done"; pure () -- #eval tst2 end ex2
f54c5690cf8f2711fc699ad8ea4d4b986b001a85
94e33a31faa76775069b071adea97e86e218a8ee
/counterexamples/phillips.lean
cc507660d0c2bc526985eea83eb2b216b39f06b9
[ "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
28,632
lean
/- Copyright (c) 2021 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import analysis.normed_space.hahn_banach.extension import measure_theory.measure.lebesgue /-! # A counterexample on Pettis integrability There are several theories of integration for functions taking values in Banach spaces. Bochner integration, requiring approximation by simple functions, is the analogue of the one-dimensional theory. It is very well behaved, but only works for functions with second-countable range. For functions `f` taking values in a larger Banach space `B`, one can define the Dunford integral as follows. Assume that, for all continuous linear functional `Ο†`, the function `Ο† ∘ f` is measurable (we say that `f` is weakly measurable, or scalarly measurable) and integrable. Then `Ο† ↦ ∫ Ο† ∘ f` is continuous (by the closed graph theorem), and therefore defines an element of the bidual `B**`. This is the Dunford integral of `f`. This Dunford integral is not usable in practice as it does not belong to the right space. Let us say that a function is Pettis integrable if its Dunford integral belongs to the canonical image of `B` in `B**`. In this case, we define the Pettis integral as the Dunford integral inside `B`. This integral is very general, but not really usable to do analysis. This file illustrates this, by giving an example of a function with nice properties but which is *not* Pettis-integrable. This function: - is defined from `[0, 1]` to a complete Banach space; - is weakly measurable; - has norm everywhere bounded by `1` (in particular, its norm is integrable); - and yet it is not Pettis-integrable with respect to Lebesgue measure. This construction is due to [Ralph S. Phillips, *Integration in a convex linear topological space*][phillips1940], in Example 10.8. It requires the continuum hypothesis. The example is the following. Under the continuum hypothesis, one can find a subset of `ℝ²` which, along each vertical line, only misses a countable set of points, while it is countable along each horizontal line. This is due to Sierpinski, and formalized in `sierpinski_pathological_family`. (In fact, Sierpinski proves that the existence of such a set is equivalent to the continuum hypothesis). Let `B` be the set of all bounded functions on `ℝ` (we are really talking about everywhere defined functions here). Define `f : ℝ β†’ B` by taking `f x` to be the characteristic function of the vertical slice at position `x` of Sierpinski's set. It is our counterexample. To show that it is weakly measurable, we should consider `Ο† ∘ f` where `Ο†` is an arbitrary continuous linear form on `B`. There is no reasonable classification of such linear forms (they can be very wild). But if one restricts such a linear form to characteristic functions, one gets a finitely additive signed "measure". Such a "measure" can be decomposed into a discrete part (supported on a countable set) and a continuous part (giving zero mass to countable sets). For all but countably many points, `f x` will not intersect the discrete support of `Ο†` thanks to the definition of the Sierpinski set. This implies that `Ο† ∘ f` is constant outside of a countable set, and equal to the total mass of the continuous part of `Ο†` there. In particular, it is measurable (and its integral is the total mass of the continuous part of `Ο†`). Assume that `f` has a Pettis integral `g`. For all continuous linear form `Ο†`, then `Ο† g` should be the total mass of the continuous part of `Ο†`. Taking for `Ο†` the evaluation at the point `x` (which has no continuous part), one gets `g x = 0`. Take then for `Ο†` the Lebesgue integral on `[0, 1]` (or rather an arbitrary extension of Lebesgue integration to all bounded functions, thanks to Hahn-Banach). Then `Ο† g` should be the total mass of the continuous part of `Ο†`, which is `1`. This contradicts the fact that `g = 0`, and concludes the proof that `f` has no Pettis integral. ## Implementation notes The space of all bounded functions is defined as the space of all bounded continuous functions on a discrete copy of the original type, as mathlib only contains the space of all bounded continuous functions (which is the useful one). -/ universe u variables {Ξ± : Type u} open set bounded_continuous_function measure_theory open cardinal (aleph) open_locale cardinal bounded_continuous_function noncomputable theory /-- A copy of a type, endowed with the discrete topology -/ def discrete_copy (Ξ± : Type u) : Type u := Ξ± instance : topological_space (discrete_copy Ξ±) := βŠ₯ instance : discrete_topology (discrete_copy Ξ±) := ⟨rfl⟩ instance [inhabited Ξ±] : inhabited (discrete_copy Ξ±) := ⟨show Ξ±, from default⟩ namespace phillips_1940 /-! ### Extending the integral Thanks to Hahn-Banach, one can define a (non-canonical) continuous linear functional on the space of all bounded functions, coinciding with the integral on the integrable ones. -/ /-- The subspace of integrable functions in the space of all bounded functions on a type. This is a technical device, used to apply Hahn-Banach theorem to construct an extension of the integral to all bounded functions. -/ def bounded_integrable_functions [measurable_space Ξ±] (ΞΌ : measure Ξ±) : subspace ℝ (discrete_copy Ξ± →ᡇ ℝ) := { carrier := {f | integrable f ΞΌ}, zero_mem' := integrable_zero _ _ _, add_mem' := Ξ» f g hf hg, integrable.add hf hg, smul_mem' := Ξ» c f hf, integrable.smul c hf } /-- The integral, as a continuous linear map on the subspace of integrable functions in the space of all bounded functions on a type. This is a technical device, that we will extend through Hahn-Banach. -/ def bounded_integrable_functions_integral_clm [measurable_space Ξ±] (ΞΌ : measure Ξ±) [is_finite_measure ΞΌ] : bounded_integrable_functions ΞΌ β†’L[ℝ] ℝ := linear_map.mk_continuous { to_fun := Ξ» f, ∫ x, f x βˆ‚ΞΌ, map_add' := Ξ» f g, integral_add f.2 g.2, map_smul' := Ξ» c f, integral_smul _ _ } (ΞΌ univ).to_real begin assume f, rw mul_comm, apply norm_integral_le_of_norm_le_const, apply filter.eventually_of_forall, assume x, exact bounded_continuous_function.norm_coe_le_norm f x, end /-- Given a measure, there exists a continuous linear form on the space of all bounded functions (not necessarily measurable) that coincides with the integral on bounded measurable functions. -/ lemma exists_linear_extension_to_bounded_functions [measurable_space Ξ±] (ΞΌ : measure Ξ±) [is_finite_measure ΞΌ] : βˆƒ Ο† : (discrete_copy Ξ± →ᡇ ℝ) β†’L[ℝ] ℝ, βˆ€ (f : discrete_copy Ξ± →ᡇ ℝ), integrable f ΞΌ β†’ Ο† f = ∫ x, f x βˆ‚ΞΌ := begin rcases exists_extension_norm_eq _ (bounded_integrable_functions_integral_clm ΞΌ) with βŸ¨Ο†, hΟ†βŸ©, exact βŸ¨Ο†, Ξ» f hf, hΟ†.1 ⟨f, hf⟩⟩, end /-- An arbitrary extension of the integral to all bounded functions, as a continuous linear map. It is not at all canonical, and constructed using Hahn-Banach. -/ def _root_.measure_theory.measure.extension_to_bounded_functions [measurable_space Ξ±] (ΞΌ : measure Ξ±) [is_finite_measure ΞΌ] : (discrete_copy Ξ± →ᡇ ℝ) β†’L[ℝ] ℝ := (exists_linear_extension_to_bounded_functions ΞΌ).some lemma extension_to_bounded_functions_apply [measurable_space Ξ±] (ΞΌ : measure Ξ±) [is_finite_measure ΞΌ] (f : discrete_copy Ξ± →ᡇ ℝ) (hf : integrable f ΞΌ) : ΞΌ.extension_to_bounded_functions f = ∫ x, f x βˆ‚ΞΌ := (exists_linear_extension_to_bounded_functions ΞΌ).some_spec f hf /-! ### Additive measures on the space of all sets We define bounded finitely additive signed measures on the space of all subsets of a type `Ξ±`, and show that such an object can be split into a discrete part and a continuous part. -/ /-- A bounded signed finitely additive measure defined on *all* subsets of a type. -/ structure bounded_additive_measure (Ξ± : Type u) := (to_fun : set Ξ± β†’ ℝ) (additive' : βˆ€ s t, disjoint s t β†’ to_fun (s βˆͺ t) = to_fun s + to_fun t) (exists_bound : βˆƒ (C : ℝ), βˆ€ s, |to_fun s| ≀ C) instance : inhabited (bounded_additive_measure Ξ±) := ⟨{ to_fun := Ξ» s, 0, additive' := Ξ» s t hst, by simp, exists_bound := ⟨0, Ξ» s, by simp⟩ }⟩ instance : has_coe_to_fun (bounded_additive_measure Ξ±) (Ξ» _, set Ξ± β†’ ℝ) := ⟨λ f, f.to_fun⟩ namespace bounded_additive_measure /-- A constant bounding the mass of any set for `f`. -/ def C (f : bounded_additive_measure Ξ±) := f.exists_bound.some lemma additive (f : bounded_additive_measure Ξ±) (s t : set Ξ±) (h : disjoint s t) : f (s βˆͺ t) = f s + f t := f.additive' s t h lemma abs_le_bound (f : bounded_additive_measure Ξ±) (s : set Ξ±) : |f s| ≀ f.C := f.exists_bound.some_spec s lemma le_bound (f : bounded_additive_measure Ξ±) (s : set Ξ±) : f s ≀ f.C := le_trans (le_abs_self _) (f.abs_le_bound s) @[simp] lemma empty (f : bounded_additive_measure Ξ±) : f βˆ… = 0 := begin have : (βˆ… : set Ξ±) = βˆ… βˆͺ βˆ…, by simp only [empty_union], apply_fun f at this, rwa [f.additive _ _ (empty_disjoint _), self_eq_add_left] at this, end instance : has_neg (bounded_additive_measure Ξ±) := ⟨λ f, { to_fun := Ξ» s, - f s, additive' := Ξ» s t hst, by simp only [f.additive s t hst, add_comm, neg_add_rev], exists_bound := ⟨f.C, Ξ» s, by simp [f.abs_le_bound]⟩ }⟩ @[simp] lemma neg_apply (f : bounded_additive_measure Ξ±) (s : set Ξ±) : (-f) s = - (f s) := rfl /-- Restricting a bounded additive measure to a subset still gives a bounded additive measure. -/ def restrict (f : bounded_additive_measure Ξ±) (t : set Ξ±) : bounded_additive_measure Ξ± := { to_fun := Ξ» s, f (t ∩ s), additive' := Ξ» s s' h, begin rw [← f.additive (t ∩ s) (t ∩ s'), inter_union_distrib_left], exact h.mono (inter_subset_right _ _) (inter_subset_right _ _), end, exists_bound := ⟨f.C, Ξ» s, f.abs_le_bound _⟩ } @[simp] lemma restrict_apply (f : bounded_additive_measure Ξ±) (s t : set Ξ±) : f.restrict s t = f (s ∩ t) := rfl /-- There is a maximal countable set of positive measure, in the sense that any countable set not intersecting it has nonpositive measure. Auxiliary lemma to prove `exists_discrete_support`. -/ lemma exists_discrete_support_nonpos (f : bounded_additive_measure Ξ±) : βˆƒ (s : set Ξ±), s.countable ∧ (βˆ€ t : set Ξ±, t.countable β†’ f (t \ s) ≀ 0) := begin /- The idea of the proof is to construct the desired set inductively, adding at each step a countable set with close to maximal measure among those points that have not already been chosen. Doing this countably many steps will be enough. Indeed, otherwise, a remaining set would have positive measure `Ξ΅`. This means that at each step the set we have added also had a large measure, say at least `Ξ΅ / 2`. After `n` steps, the set we have constructed has therefore measure at least `n * Ξ΅ / 2`. This is a contradiction since the measures have to remain uniformly bounded. We argue from the start by contradiction, as this means that our inductive construction will never be stuck, so we won't have to consider this case separately. -/ by_contra' h, -- We will formulate things in terms of the type of countable subsets of `Ξ±`, as this is more -- convenient to formalize the inductive construction. let A : set (set Ξ±) := {t | t.countable}, let empty : A := βŸ¨βˆ…, countable_empty⟩, haveI : nonempty A := ⟨empty⟩, -- given a countable set `s`, one can find a set `t` in its complement with measure close to -- maximal. have : βˆ€ (s : A), βˆƒ (t : A), (βˆ€ (u : A), f (u \ s) ≀ 2 * f (t \ s)), { assume s, have B : bdd_above (range (Ξ» (u : A), f (u \ s))), { refine ⟨f.C, Ξ» x hx, _⟩, rcases hx with ⟨u, hu⟩, rw ← hu, exact f.le_bound _ }, let S := supr (Ξ» (t : A), f (t \ s)), have S_pos : 0 < S, { rcases h s.1 s.2 with ⟨t, t_count, ht⟩, apply ht.trans_le, let t' : A := ⟨t, t_count⟩, change f (t' \ s) ≀ S, exact le_csupr B t' }, rcases exists_lt_of_lt_csupr (half_lt_self S_pos) with ⟨t, ht⟩, refine ⟨t, Ξ» u, _⟩, calc f (u \ s) ≀ S : le_csupr B _ ... = 2 * (S / 2) : by ring ... ≀ 2 * f (t \ s) : mul_le_mul_of_nonneg_left ht.le (by norm_num) }, choose! F hF using this, -- iterate the above construction, by adding at each step a set with measure close to maximal in -- the complement of already chosen points. This is the set `s n` at step `n`. let G : A β†’ A := Ξ» u, ⟨u βˆͺ F u, u.2.union (F u).2⟩, let s : β„• β†’ A := Ξ» n, G^[n] empty, -- We will get a contradiction from the fact that there is a countable set `u` with positive -- measure in the complement of `⋃ n, s n`. rcases h (⋃ n, s n) (countable_Union (Ξ» n, (s n).2)) with ⟨t, t_count, ht⟩, let u : A := ⟨t \ ⋃ n, s n, t_count.mono (diff_subset _ _)⟩, set Ξ΅ := f u with hΞ΅, have Ξ΅_pos : 0 < Ξ΅ := ht, have I1 : βˆ€ n, Ξ΅ / 2 ≀ f (s (n+1) \ s n), { assume n, rw [div_le_iff' (show (0 : ℝ) < 2, by norm_num), hΞ΅], convert hF (s n) u using 3, { dsimp [u], ext x, simp only [not_exists, mem_Union, mem_diff], tauto }, { simp only [s, function.iterate_succ', subtype.coe_mk, union_diff_left] } }, have I2 : βˆ€ (n : β„•), (n : ℝ) * (Ξ΅ / 2) ≀ f (s n), { assume n, induction n with n IH, { simp only [s, bounded_additive_measure.empty, id.def, nat.cast_zero, zero_mul, function.iterate_zero, subtype.coe_mk], }, { have : (s (n+1) : set Ξ±) = (s (n+1) \ s n) βˆͺ s n, by simp only [s, function.iterate_succ', union_comm, union_diff_self, subtype.coe_mk, union_diff_left], rw [nat.succ_eq_add_one, this, f.additive], swap, { rw disjoint.comm, apply disjoint_diff }, calc ((n + 1 : β„•) : ℝ) * (Ξ΅ / 2) = Ξ΅ / 2 + n * (Ξ΅ / 2) : by simp only [nat.cast_succ]; ring ... ≀ f ((s (n + 1 : β„•)) \ (s n)) + f (s n) : add_le_add (I1 n) IH } }, rcases exists_nat_gt (f.C / (Ξ΅ / 2)) with ⟨n, hn⟩, have : (n : ℝ) ≀ f.C / (Ξ΅ / 2), by { rw le_div_iff (half_pos Ξ΅_pos), exact (I2 n).trans (f.le_bound _) }, exact lt_irrefl _ (this.trans_lt hn), end lemma exists_discrete_support (f : bounded_additive_measure Ξ±) : βˆƒ s : set Ξ±, s.countable ∧ (βˆ€ t : set Ξ±, t.countable β†’ f (t \ s) = 0) := begin rcases f.exists_discrete_support_nonpos with ⟨s₁, s₁_count, hβ‚βŸ©, rcases (-f).exists_discrete_support_nonpos with ⟨sβ‚‚, sβ‚‚_count, hβ‚‚βŸ©, refine ⟨s₁ βˆͺ sβ‚‚, s₁_count.union sβ‚‚_count, Ξ» t ht, le_antisymm _ _⟩, { have : t \ (s₁ βˆͺ sβ‚‚) = (t \ (s₁ βˆͺ sβ‚‚)) \ s₁, by rw [diff_diff, union_comm, union_assoc, union_self], rw this, exact h₁ _ (ht.mono (diff_subset _ _)) }, { have : t \ (s₁ βˆͺ sβ‚‚) = (t \ (s₁ βˆͺ sβ‚‚)) \ sβ‚‚, by rw [diff_diff, union_assoc, union_self], rw this, simp only [neg_nonpos, neg_apply] at hβ‚‚, exact hβ‚‚ _ (ht.mono (diff_subset _ _)) }, end /-- A countable set outside of which the measure gives zero mass to countable sets. We are not claiming this set is unique, but we make an arbitrary choice of such a set. -/ def discrete_support (f : bounded_additive_measure Ξ±) : set Ξ± := (exists_discrete_support f).some lemma countable_discrete_support (f : bounded_additive_measure Ξ±) : f.discrete_support.countable := (exists_discrete_support f).some_spec.1 lemma apply_countable (f : bounded_additive_measure Ξ±) (t : set Ξ±) (ht : t.countable) : f (t \ f.discrete_support) = 0 := (exists_discrete_support f).some_spec.2 t ht /-- The discrete part of a bounded additive measure, obtained by restricting the measure to its countable support. -/ def discrete_part (f : bounded_additive_measure Ξ±) : bounded_additive_measure Ξ± := f.restrict f.discrete_support /-- The continuous part of a bounded additive measure, giving zero measure to every countable set. -/ def continuous_part (f : bounded_additive_measure Ξ±) : bounded_additive_measure Ξ± := f.restrict (univ \ f.discrete_support) lemma eq_add_parts (f : bounded_additive_measure Ξ±) (s : set Ξ±) : f s = f.discrete_part s + f.continuous_part s := begin simp only [discrete_part, continuous_part, restrict_apply], rw [← f.additive, ← inter_distrib_right], { simp only [union_univ, union_diff_self, univ_inter] }, { have : disjoint f.discrete_support (univ \ f.discrete_support) := disjoint_diff, exact this.mono (inter_subset_left _ _) (inter_subset_left _ _) } end lemma discrete_part_apply (f : bounded_additive_measure Ξ±) (s : set Ξ±) : f.discrete_part s = f (f.discrete_support ∩ s) := rfl lemma continuous_part_apply_eq_zero_of_countable (f : bounded_additive_measure Ξ±) (s : set Ξ±) (hs : s.countable) : f.continuous_part s = 0 := begin simp [continuous_part], convert f.apply_countable s hs using 2, ext x, simp [and_comm] end lemma continuous_part_apply_diff (f : bounded_additive_measure Ξ±) (s t : set Ξ±) (hs : s.countable) : f.continuous_part (t \ s) = f.continuous_part t := begin conv_rhs { rw ← diff_union_inter t s }, rw [additive, self_eq_add_right], { exact continuous_part_apply_eq_zero_of_countable _ _ (hs.mono (inter_subset_right _ _)) }, { exact disjoint.mono_right (inter_subset_right _ _) (disjoint.comm.1 disjoint_diff) }, end end bounded_additive_measure open bounded_additive_measure section /-! ### Relationship between continuous functionals and finitely additive measures. -/ lemma norm_indicator_le_one (s : set Ξ±) (x : Ξ±) : βˆ₯(indicator s (1 : Ξ± β†’ ℝ)) xβˆ₯ ≀ 1 := by { simp only [indicator, pi.one_apply], split_ifs; norm_num } /-- A functional in the dual space of bounded functions gives rise to a bounded additive measure, by applying the functional to the indicator functions. -/ def _root_.continuous_linear_map.to_bounded_additive_measure [topological_space Ξ±] [discrete_topology Ξ±] (f : (Ξ± →ᡇ ℝ) β†’L[ℝ] ℝ) : bounded_additive_measure Ξ± := { to_fun := Ξ» s, f (of_normed_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)), additive' := Ξ» s t hst, begin have : of_normed_group_discrete (indicator (s βˆͺ t) 1) 1 (norm_indicator_le_one (s βˆͺ t)) = of_normed_group_discrete (indicator s 1) 1 (norm_indicator_le_one s) + of_normed_group_discrete (indicator t 1) 1 (norm_indicator_le_one t), by { ext x, simp [indicator_union_of_disjoint hst], }, rw [this, f.map_add], end, exists_bound := ⟨βˆ₯fβˆ₯, Ξ» s, begin have I : βˆ₯of_normed_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)βˆ₯ ≀ 1, by apply norm_of_normed_group_le _ zero_le_one, apply le_trans (f.le_op_norm _), simpa using mul_le_mul_of_nonneg_left I (norm_nonneg f), end⟩ } @[simp] lemma continuous_part_eval_clm_eq_zero [topological_space Ξ±] [discrete_topology Ξ±] (s : set Ξ±) (x : Ξ±) : (eval_clm ℝ x).to_bounded_additive_measure.continuous_part s = 0 := let f := (eval_clm ℝ x).to_bounded_additive_measure in calc f.continuous_part s = f.continuous_part (s \ {x}) : (continuous_part_apply_diff _ _ _ (countable_singleton x)).symm ... = f ((univ \ f.discrete_support) ∩ (s \ {x})) : rfl ... = indicator ((univ \ f.discrete_support) ∩ (s \ {x})) 1 x : rfl ... = 0 : by simp lemma to_functions_to_measure [measurable_space Ξ±] (ΞΌ : measure Ξ±) [is_finite_measure ΞΌ] (s : set Ξ±) (hs : measurable_set s) : ΞΌ.extension_to_bounded_functions.to_bounded_additive_measure s = (ΞΌ s).to_real := begin change ΞΌ.extension_to_bounded_functions (of_normed_group_discrete (indicator s (Ξ» x, 1)) 1 (norm_indicator_le_one s)) = (ΞΌ s).to_real, rw extension_to_bounded_functions_apply, { change ∫ x, s.indicator (Ξ» y, (1 : ℝ)) x βˆ‚ΞΌ = _, simp [integral_indicator hs] }, { change integrable (indicator s 1) ΞΌ, have : integrable (Ξ» x, (1 : ℝ)) ΞΌ := integrable_const (1 : ℝ), apply this.mono' (measurable.indicator (@measurable_const _ _ _ _ (1 : ℝ)) hs).ae_strongly_measurable, apply filter.eventually_of_forall, exact norm_indicator_le_one _ } end lemma to_functions_to_measure_continuous_part [measurable_space Ξ±] [measurable_singleton_class Ξ±] (ΞΌ : measure Ξ±) [is_finite_measure ΞΌ] [has_no_atoms ΞΌ] (s : set Ξ±) (hs : measurable_set s) : ΞΌ.extension_to_bounded_functions.to_bounded_additive_measure.continuous_part s = (ΞΌ s).to_real := begin let f := ΞΌ.extension_to_bounded_functions.to_bounded_additive_measure, change f ((univ \ f.discrete_support) ∩ s) = (ΞΌ s).to_real, rw to_functions_to_measure, swap, { exact measurable_set.inter (measurable_set.univ.diff (countable.measurable_set f.countable_discrete_support)) hs }, congr' 1, rw [inter_comm, ← inter_diff_assoc, inter_univ], exact measure_diff_null (f.countable_discrete_support.measure_zero _) end end /-! ### A set in `ℝ²` large along verticals, small along horizontals We construct a subset of `ℝ²`, given as a family of sets, which is large along verticals (i.e., it only misses a countable set along each vertical) but small along horizontals (it is countable along horizontals). Such a set can not be measurable as it would contradict Fubini theorem. We need the continuum hypothesis to construct it. -/ theorem sierpinski_pathological_family (Hcont : #ℝ = aleph 1) : βˆƒ (f : ℝ β†’ set ℝ), (βˆ€ x, (univ \ f x).countable) ∧ (βˆ€ y, {x : ℝ | y ∈ f x}.countable) := begin rcases cardinal.ord_eq ℝ with ⟨r, hr, H⟩, resetI, refine ⟨λ x, {y | r x y}, Ξ» x, _, Ξ» y, _⟩, { have : univ \ {y | r x y} = {y | r y x} βˆͺ {x}, { ext y, simp only [true_and, mem_univ, mem_set_of_eq, mem_insert_iff, union_singleton, mem_diff], rcases trichotomous_of r x y with h|rfl|h, { simp only [h, not_or_distrib, false_iff, not_true], split, { rintros rfl, exact irrefl_of r y h }, { exact asymm h } }, { simp only [true_or, eq_self_iff_true, iff_true], exact irrefl x }, { simp only [h, iff_true, or_true], exact asymm h } }, rw this, apply countable.union _ (countable_singleton _), rw [cardinal.countable_iff_lt_aleph_one, ← Hcont], exact cardinal.card_typein_lt r x H }, { rw [cardinal.countable_iff_lt_aleph_one, ← Hcont], exact cardinal.card_typein_lt r y H } end /-- A family of sets in `ℝ` which only miss countably many points, but such that any point is contained in only countably many of them. -/ def spf (Hcont : #ℝ = aleph 1) (x : ℝ) : set ℝ := (sierpinski_pathological_family Hcont).some x lemma countable_compl_spf (Hcont : #ℝ = aleph 1) (x : ℝ) : (univ \ spf Hcont x).countable := (sierpinski_pathological_family Hcont).some_spec.1 x lemma countable_spf_mem (Hcont : #ℝ = aleph 1) (y : ℝ) : {x | y ∈ spf Hcont x}.countable := (sierpinski_pathological_family Hcont).some_spec.2 y /-! ### A counterexample for the Pettis integral We construct a function `f` from `[0,1]` to a complete Banach space `B`, which is weakly measurable (i.e., for any continuous linear form `Ο†` on `B` the function `Ο† ∘ f` is measurable), bounded in norm (i.e., for all `x`, one has `βˆ₯f xβˆ₯ ≀ 1`), and still `f` has no Pettis integral. This construction, due to Phillips, requires the continuum hypothesis. We will take for `B` the space of all bounded functions on `ℝ`, with the supremum norm (no measure here, we are really talking of everywhere defined functions). And `f x` will be the characteristic function of a set which is large (it has countable complement), as in the Sierpinski pathological family. -/ /-- A family of bounded functions `f_x` from `ℝ` (seen with the discrete topology) to `ℝ` (in fact taking values in `{0, 1}`), indexed by a real parameter `x`, corresponding to the characteristic functions of the different fibers of the Sierpinski pathological family -/ def f (Hcont : #ℝ = aleph 1) (x : ℝ) : (discrete_copy ℝ →ᡇ ℝ) := of_normed_group_discrete (indicator (spf Hcont x) 1) 1 (norm_indicator_le_one _) lemma apply_f_eq_continuous_part (Hcont : #ℝ = aleph 1) (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ) (x : ℝ) (hx : Ο†.to_bounded_additive_measure.discrete_support ∩ spf Hcont x = βˆ…) : Ο† (f Hcont x) = Ο†.to_bounded_additive_measure.continuous_part univ := begin set ψ := Ο†.to_bounded_additive_measure with hψ, have : Ο† (f Hcont x) = ψ (spf Hcont x) := rfl, have U : univ = spf Hcont x βˆͺ (univ \ spf Hcont x), by simp only [union_univ, union_diff_self], rw [this, eq_add_parts, discrete_part_apply, hx, ψ.empty, zero_add, U, ψ.continuous_part.additive _ _ (disjoint_diff), ψ.continuous_part_apply_eq_zero_of_countable _ (countable_compl_spf Hcont x), add_zero], end lemma countable_ne (Hcont : #ℝ = aleph 1) (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ) : {x | Ο†.to_bounded_additive_measure.continuous_part univ β‰  Ο† (f Hcont x)}.countable := begin have A : {x | Ο†.to_bounded_additive_measure.continuous_part univ β‰  Ο† (f Hcont x)} βŠ† {x | Ο†.to_bounded_additive_measure.discrete_support ∩ spf Hcont x β‰  βˆ…}, { assume x hx, contrapose! hx, simp only [not_not, mem_set_of_eq] at hx, simp [apply_f_eq_continuous_part Hcont Ο† x hx], }, have B : {x | Ο†.to_bounded_additive_measure.discrete_support ∩ spf Hcont x β‰  βˆ…} βŠ† ⋃ y ∈ Ο†.to_bounded_additive_measure.discrete_support, {x | y ∈ spf Hcont x}, { assume x hx, dsimp at hx, rw [← ne.def, ne_empty_iff_nonempty] at hx, simp only [exists_prop, mem_Union, mem_set_of_eq], exact hx }, apply countable.mono (subset.trans A B), exact countable.bUnion (countable_discrete_support _) (Ξ» a ha, countable_spf_mem Hcont a), end lemma comp_ae_eq_const (Hcont : #ℝ = aleph 1) (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ) : βˆ€α΅ x βˆ‚(volume.restrict (Icc (0 : ℝ) 1)), Ο†.to_bounded_additive_measure.continuous_part univ = Ο† (f Hcont x) := begin apply ae_restrict_of_ae, refine measure_mono_null _ ((countable_ne Hcont Ο†).measure_zero _), assume x, simp only [imp_self, mem_set_of_eq, mem_compl_eq], end lemma integrable_comp (Hcont : #ℝ = aleph 1) (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ) : integrable_on (Ξ» x, Ο† (f Hcont x)) (Icc 0 1) := begin have : integrable_on (Ξ» x, Ο†.to_bounded_additive_measure.continuous_part univ) (Icc (0 : ℝ) 1) volume, by simp [integrable_on_const], apply integrable.congr this (comp_ae_eq_const Hcont Ο†), end lemma integral_comp (Hcont : #ℝ = aleph 1) (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ) : ∫ x in Icc 0 1, Ο† (f Hcont x) = Ο†.to_bounded_additive_measure.continuous_part univ := begin rw ← integral_congr_ae (comp_ae_eq_const Hcont Ο†), simp, end /-! The next few statements show that the function `f Hcont : ℝ β†’ (discrete_copy ℝ →ᡇ ℝ)` takes its values in a complete space, is scalarly measurable, is everywhere bounded by `1`, and still has no Pettis integral. -/ example : complete_space (discrete_copy ℝ →ᡇ ℝ) := by apply_instance /-- The function `f Hcont : ℝ β†’ (discrete_copy ℝ →ᡇ ℝ)` is scalarly measurable. -/ lemma measurable_comp (Hcont : #ℝ = aleph 1) (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ) : measurable (Ξ» x, Ο† (f Hcont x)) := begin have : measurable (Ξ» x, Ο†.to_bounded_additive_measure.continuous_part univ) := measurable_const, refine this.measurable_of_countable_ne _, exact countable_ne Hcont Ο†, end /-- The function `f Hcont : ℝ β†’ (discrete_copy ℝ →ᡇ ℝ)` is uniformly bounded by `1` in norm. -/ lemma norm_bound (Hcont : #ℝ = aleph 1) (x : ℝ) : βˆ₯f Hcont xβˆ₯ ≀ 1 := norm_of_normed_group_le _ zero_le_one _ /-- The function `f Hcont : ℝ β†’ (discrete_copy ℝ →ᡇ ℝ)` has no Pettis integral. -/ theorem no_pettis_integral (Hcont : #ℝ = aleph 1) : Β¬ βˆƒ (g : discrete_copy ℝ →ᡇ ℝ), βˆ€ (Ο† : (discrete_copy ℝ →ᡇ ℝ) β†’L[ℝ] ℝ), ∫ x in Icc 0 1, Ο† (f Hcont x) = Ο† g := begin rintros ⟨g, h⟩, simp only [integral_comp] at h, have : g = 0, { ext x, have : g x = eval_clm ℝ x g := rfl, rw [this, ← h], simp }, simp only [this, continuous_linear_map.map_zero] at h, specialize h (volume.restrict (Icc (0 : ℝ) 1)).extension_to_bounded_functions, simp_rw [to_functions_to_measure_continuous_part _ _ measurable_set.univ] at h, simpa using h, end end phillips_1940
a0fd17cff1500a5ae643ca36dc2473f0c5cdef40
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/e5.lean
32b97e4b65fff7dfd011584f946835e8d6f839b6
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,522
lean
definition Prop := Type.{0} definition false : Prop := βˆ€x : Prop, x check false theorem false_elim (C : Prop) (H : false) : C := H C definition eq {A : Type} (a b : A) := βˆ€ P : A β†’ Prop, P a β†’ P b check eq infix `=`:50 := eq theorem refl {A : Type} (a : A) : a = a := Ξ» P H, H definition true : Prop := false = false theorem trivial : true := refl false theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b := H1 _ H2 theorem symm {A : Type} {a b : A} (H : a = b) : b = a := subst H (refl a) theorem trans {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H2 H1 inductive nat : Type := zero : nat, succ : nat β†’ nat namespace nat end nat open nat print "using strict implicit arguments" definition symmetric {A : Type} (R : A β†’ A β†’ Prop) := βˆ€ ⦃a b⦄, R a b β†’ R b a check symmetric constant p : nat β†’ nat β†’ Prop check symmetric p axiom H1 : symmetric p axiom H2 : p zero (succ zero) check H1 check H1 H2 print "------------" print "using implicit arguments" definition symmetric2 {A : Type} (R : A β†’ A β†’ Prop) := βˆ€ {a b}, R a b β†’ R b a check symmetric2 check symmetric2 p axiom H3 : symmetric2 p axiom H4 : p zero (succ zero) check H3 check H3 H4 print "-----------------" print "using strict implicit arguments (ASCII notation)" definition symmetric3 {A : Type} (R : A β†’ A β†’ Prop) := βˆ€ {{a b}}, R a b β†’ R b a check symmetric3 check symmetric3 p axiom H5 : symmetric3 p axiom H6 : p zero (succ zero) check H5 check H5 H6
598621521c805d56275ca294d5891bb435089106
5719a16e23dfc08cdea7a5bf035b81690f307965
/src/Init/Lean/Data/Json/FromToJson.lean
bc61c0f58254e3794cdb091518bc4b9a9aa4cc74
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,710
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ prelude import Init.Lean.Data.Json.Basic import Init.Data.List.Control namespace Lean universes u class HasFromJson (Ξ± : Type u) := (fromJson? {} : Json β†’ Option Ξ±) export HasFromJson (fromJson?) class HasToJson (Ξ± : Type u) := (toJson : Ξ± β†’ Json) export HasToJson (toJson) instance Json.hasFromJson : HasFromJson Json := ⟨some⟩ instance Json.HasToJson : HasToJson Json := ⟨id⟩ instance JsonNumber.hasFromJson : HasFromJson JsonNumber := ⟨Json.getNum?⟩ instance JsonNumber.hasToJson : HasToJson JsonNumber := ⟨Json.num⟩ -- looks like id, but there are coercions happening instance Bool.hasFromJson : HasFromJson Bool := ⟨Json.getBool?⟩ instance Bool.hasToJson : HasToJson Bool := ⟨fun b => b⟩ instance Nat.hasFromJson : HasFromJson Nat := ⟨Json.getNat?⟩ instance Nat.hasToJson : HasToJson Nat := ⟨fun n => n⟩ instance Int.hasFromJson : HasFromJson Int := ⟨Json.getInt?⟩ instance Int.hasToJson : HasToJson Int := ⟨fun n => Json.num n⟩ instance String.hasFromJson : HasFromJson String := ⟨Json.getStr?⟩ instance String.hasToJson : HasToJson String := ⟨fun s => s⟩ instance Array.hasFromJson {Ξ± : Type u} [HasFromJson Ξ±] : HasFromJson (Array Ξ±) := ⟨fun j => match j with | Json.arr a => a.mapM fromJson? | _ => none⟩ instance List.hasToJson {Ξ± : Type u} [HasToJson Ξ±] : HasToJson (Array Ξ±) := ⟨fun a => Json.arr (a.map toJson)⟩ def Json.getObjValAs? (j : Json) (Ξ± : Type u) [HasFromJson Ξ±] (k : String) : Option Ξ± := (j.getObjVal? k).bind fromJson? end Lean
dd3b454ccdaf40224e95ba956b32505b3f2fb798
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/analysis/complex/polynomial.lean
367393ed6aee17fa2d2ce1b35d0b2f6805154661
[ "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
5,378
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import topology.algebra.polynomial import analysis.special_functions.pow /-! # The fundamental theorem of algebra This file proves that every nonconstant complex polynomial has a root. -/ open complex polynomial metric filter is_absolute_value set open_locale classical namespace complex /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- The fundamental theorem of algebra. Every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial β„‚} (hf : 0 < degree f) : βˆƒ z : β„‚, is_root f z := let ⟨zβ‚€, hzβ‚€βŸ© := f.exists_forall_norm_le in exists.intro zβ‚€ $ classical.by_contradiction $ Ξ» hf0, have hfX : f - C (f.eval zβ‚€) β‰  0, from mt sub_eq_zero.1 (Ξ» h, not_le_of_gt hf (h.symm β–Έ degree_C_le)), let n := root_multiplicity zβ‚€ (f - C (f.eval zβ‚€)) in let g := (f - C (f.eval zβ‚€)) /β‚˜ ((X - C zβ‚€) ^ n) in have hg0 : g.eval zβ‚€ β‰  0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C zβ‚€) ^ n = f - C (f.eval zβ‚€), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ Ξ» hn0, by simpa [g, hn0] using hg0, let ⟨δ', hΞ΄'₁, hΞ΄'β‚‚βŸ© := continuous_iff.1 (polynomial.continuous g) zβ‚€ ((g.eval zβ‚€).abs) (complex.abs_pos.2 hg0) in let Ξ΄ := min (min (Ξ΄' / 2) 1) (((f.eval zβ‚€).abs / (g.eval zβ‚€).abs) / 2) in have hf0' : 0 < (f.eval zβ‚€).abs, from complex.abs_pos.2 hf0, have hg0' : 0 < abs (eval zβ‚€ g), from complex.abs_pos.2 hg0, have hfg0 : 0 < (f.eval zβ‚€).abs / abs (eval zβ‚€ g), from div_pos hf0' hg0', have hΞ΄0 : 0 < Ξ΄, from lt_min (lt_min (half_pos hΞ΄'₁) (by norm_num)) (half_pos hfg0), have hΞ΄ : βˆ€ z : β„‚, abs (z - zβ‚€) = Ξ΄ β†’ abs (g.eval z - g.eval zβ‚€) < (g.eval zβ‚€).abs, from Ξ» z hz, hΞ΄'β‚‚ z (by rw [complex.dist_eq, hz]; exact ((min_le_left _ _).trans (min_le_left _ _)).trans_lt (half_lt_self hΞ΄'₁)), have hΞ΄1 : Ξ΄ ≀ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial β„‚ := C (f.eval zβ‚€) + C (g.eval zβ‚€) * (X - C zβ‚€) ^ n in let z' := (-f.eval zβ‚€ * (g.eval zβ‚€).abs * Ξ΄ ^ n / ((f.eval zβ‚€).abs * g.eval zβ‚€)) ^ (n⁻¹ : β„‚) + zβ‚€ in have hF₁ : F.eval z' = f.eval zβ‚€ - f.eval zβ‚€ * (g.eval zβ‚€).abs * Ξ΄ ^ n / (f.eval zβ‚€).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval zβ‚€), mul_left_comm (g.eval zβ‚€), mul_left_comm (g.eval zβ‚€)⁻¹, mul_inv', inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hΞ΄s : (g.eval zβ‚€).abs * Ξ΄ ^ n / (f.eval zβ‚€).abs < 1, from (div_lt_one hf0').2 $ (lt_div_iff' hg0').1 $ calc Ξ΄ ^ n ≀ Ξ΄ ^ 1 : pow_le_pow_of_le_one (le_of_lt hΞ΄0) hΞ΄1 hn0 ... = Ξ΄ : pow_one _ ... ≀ ((f.eval zβ‚€).abs / (g.eval zβ‚€).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self (div_pos hf0' hg0'), have hFβ‚‚ : (F.eval z').abs = (f.eval zβ‚€).abs - (g.eval zβ‚€).abs * Ξ΄ ^ n, from calc (F.eval z').abs = (f.eval zβ‚€ - f.eval zβ‚€ * (g.eval zβ‚€).abs * Ξ΄ ^ n / (f.eval zβ‚€).abs).abs : congr_arg abs hF₁ ... = abs (f.eval zβ‚€) * complex.abs (1 - (g.eval zβ‚€).abs * Ξ΄ ^ n / (f.eval zβ‚€).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv, sub_eq_add_neg]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hΞ΄s)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval zβ‚€ g) * (eval zβ‚€ f).abs β‰  0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'zβ‚€ : abs (z' - zβ‚€) = Ξ΄, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval zβ‚€ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hΞ΄0), real.pow_nat_rpow_nat_inv (le_of_lt hΞ΄0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval zβ‚€).abs * Ξ΄ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval zβ‚€).abs * (z' - zβ‚€).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel, sub_eq_add_neg, add_assoc] ... = (g.eval z' - g.eval zβ‚€).abs * Ξ΄ ^ n : by rw hz'zβ‚€ ... < _ : (mul_lt_mul_right (pow_pos hΞ΄0 _)).2 (hΞ΄ _ hz'zβ‚€), lt_irrefl (f.eval zβ‚€).abs $ calc (f.eval zβ‚€).abs ≀ (f.eval z').abs : hzβ‚€ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≀ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval zβ‚€).abs - (g.eval zβ‚€).abs * Ξ΄ ^ n + (g.eval zβ‚€).abs * Ξ΄ ^ n : add_lt_add_of_le_of_lt (by rw hFβ‚‚) hF₃ ... = (f.eval zβ‚€).abs : sub_add_cancel _ _ end complex
f0987a88d1dd0003680d7c7b05f78c35b44bfbfc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/equiv/basic.lean
9fe1b123686387d90beabf43b3057d6d63eeb9da
[ "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
62,450
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import logic.equiv.defs import data.option.basic import data.prod.basic import data.sigma.basic import data.subtype import data.sum.basic import logic.function.conjugate /-! # Equivalence between types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/631 > Any changes to this file require a corresponding PR to mathlib4. In this file we continue the work on equivalences begun in `logic/equiv/defs.lean`, defining * canonical isomorphisms between various types: e.g., - `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `Ξ± βŠ• Ξ²` and the sigma-type `Ξ£ b : bool, cond b Ξ± Ξ²`; - `equiv.prod_sum_distrib : Ξ± Γ— (Ξ² βŠ• Ξ³) ≃ (Ξ± Γ— Ξ²) βŠ• (Ξ± Γ— Ξ³)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `equiv.prod_congr ea eb : α₁ Γ— β₁ ≃ Ξ±β‚‚ Γ— Ξ²β‚‚`: combine two equivalences `ea : α₁ ≃ Ξ±β‚‚` and `eb : β₁ ≃ Ξ²β‚‚` using `prod.map`. More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance` does it for many algebraic type classes like `group`, `module`, etc. ## Tags equivalence, congruence, bijective map -/ open function universes u v w z variables {Ξ± : Sort u} {Ξ² : Sort v} {Ξ³ : Sort w} namespace equiv /-- `pprod Ξ± Ξ²` is equivalent to `Ξ± Γ— Ξ²` -/ @[simps apply symm_apply] def pprod_equiv_prod {Ξ± Ξ² : Type*} : pprod Ξ± Ξ² ≃ Ξ± Γ— Ξ² := { to_fun := Ξ» x, (x.1, x.2), inv_fun := Ξ» x, ⟨x.1, x.2⟩, left_inv := Ξ» ⟨x, y⟩, rfl, right_inv := Ξ» ⟨x, y⟩, rfl } /-- Product of two equivalences, in terms of `pprod`. If `Ξ± ≃ Ξ²` and `Ξ³ ≃ Ξ΄`, then `pprod Ξ± Ξ³ ≃ pprod Ξ² Ξ΄`. -/ @[congr, simps apply] def pprod_congr {Ξ΄ : Sort z} (e₁ : Ξ± ≃ Ξ²) (eβ‚‚ : Ξ³ ≃ Ξ΄) : pprod Ξ± Ξ³ ≃ pprod Ξ² Ξ΄ := { to_fun := Ξ» x, ⟨e₁ x.1, eβ‚‚ x.2⟩, inv_fun := Ξ» x, ⟨e₁.symm x.1, eβ‚‚.symm x.2⟩, left_inv := Ξ» ⟨x, y⟩, by simp, right_inv := Ξ» ⟨x, y⟩, by simp } /-- Combine two equivalences using `pprod` in the domain and `prod` in the codomain. -/ @[simps apply symm_apply] def pprod_prod {α₁ β₁ : Sort*} {Ξ±β‚‚ Ξ²β‚‚ : Type*} (ea : α₁ ≃ Ξ±β‚‚) (eb : β₁ ≃ Ξ²β‚‚) : pprod α₁ β₁ ≃ Ξ±β‚‚ Γ— Ξ²β‚‚ := (ea.pprod_congr eb).trans pprod_equiv_prod /-- Combine two equivalences using `pprod` in the codomain and `prod` in the domain. -/ @[simps apply symm_apply] def prod_pprod {α₁ β₁ : Type*} {Ξ±β‚‚ Ξ²β‚‚ : Sort*} (ea : α₁ ≃ Ξ±β‚‚) (eb : β₁ ≃ Ξ²β‚‚) : α₁ Γ— β₁ ≃ pprod Ξ±β‚‚ Ξ²β‚‚ := (ea.symm.pprod_prod eb.symm).symm /-- `pprod Ξ± Ξ²` is equivalent to `plift Ξ± Γ— plift Ξ²` -/ @[simps apply symm_apply] def pprod_equiv_prod_plift {Ξ± Ξ² : Sort*} : pprod Ξ± Ξ² ≃ plift Ξ± Γ— plift Ξ² := equiv.plift.symm.pprod_prod equiv.plift.symm /-- Product of two equivalences. If `α₁ ≃ Ξ±β‚‚` and `β₁ ≃ Ξ²β‚‚`, then `α₁ Γ— β₁ ≃ Ξ±β‚‚ Γ— Ξ²β‚‚`. This is `prod.map` as an equivalence. -/ @[congr, simps apply] def prod_congr {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Type*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ : β₁ ≃ Ξ²β‚‚) : α₁ Γ— β₁ ≃ Ξ±β‚‚ Γ— Ξ²β‚‚ := ⟨prod.map e₁ eβ‚‚, prod.map e₁.symm eβ‚‚.symm, Ξ» ⟨a, b⟩, by simp, Ξ» ⟨a, b⟩, by simp⟩ @[simp] theorem prod_congr_symm {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Type*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ : β₁ ≃ Ξ²β‚‚) : (prod_congr e₁ eβ‚‚).symm = prod_congr e₁.symm eβ‚‚.symm := rfl /-- Type product is commutative up to an equivalence: `Ξ± Γ— Ξ² ≃ Ξ² Γ— Ξ±`. This is `prod.swap` as an equivalence.-/ def prod_comm (Ξ± Ξ² : Type*) : Ξ± Γ— Ξ² ≃ Ξ² Γ— Ξ± := ⟨prod.swap, prod.swap, prod.swap_swap, prod.swap_swap⟩ @[simp] lemma coe_prod_comm (Ξ± Ξ² : Type*) : ⇑(prod_comm Ξ± Ξ²) = prod.swap := rfl @[simp] lemma prod_comm_apply {Ξ± Ξ² : Type*} (x : Ξ± Γ— Ξ²) : prod_comm Ξ± Ξ² x = x.swap := rfl @[simp] lemma prod_comm_symm (Ξ± Ξ²) : (prod_comm Ξ± Ξ²).symm = prod_comm Ξ² Ξ± := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prod_assoc (Ξ± Ξ² Ξ³ : Sort*) : (Ξ± Γ— Ξ²) Γ— Ξ³ ≃ Ξ± Γ— (Ξ² Γ— Ξ³) := ⟨λ p, (p.1.1, p.1.2, p.2), Ξ» p, ((p.1, p.2.1), p.2.2), Ξ» ⟨⟨a, b⟩, c⟩, rfl, Ξ» ⟨a, ⟨b, c⟩⟩, rfl⟩ /-- Functions on `Ξ± Γ— Ξ²` are equivalent to functions `Ξ± β†’ Ξ² β†’ Ξ³`. -/ @[simps {fully_applied := ff}] def curry (Ξ± Ξ² Ξ³ : Type*) : (Ξ± Γ— Ξ² β†’ Ξ³) ≃ (Ξ± β†’ Ξ² β†’ Ξ³) := { to_fun := curry, inv_fun := uncurry, left_inv := uncurry_curry, right_inv := curry_uncurry } section /-- `punit` is a right identity for type product up to an equivalence. -/ @[simps] def prod_punit (Ξ± : Type*) : Ξ± Γ— punit.{u+1} ≃ Ξ± := ⟨λ p, p.1, Ξ» a, (a, punit.star), Ξ» ⟨_, punit.star⟩, rfl, Ξ» a, rfl⟩ /-- `punit` is a left identity for type product up to an equivalence. -/ @[simps] def punit_prod (Ξ± : Type*) : punit.{u+1} Γ— Ξ± ≃ Ξ± := calc punit Γ— Ξ± ≃ Ξ± Γ— punit : prod_comm _ _ ... ≃ Ξ± : prod_punit _ /-- Any `unique` type is a right identity for type product up to equivalence. -/ def prod_unique (Ξ± Ξ² : Type*) [unique Ξ²] : Ξ± Γ— Ξ² ≃ Ξ± := ((equiv.refl Ξ±).prod_congr $ equiv_punit Ξ²).trans $ prod_punit Ξ± @[simp] lemma coe_prod_unique {Ξ± Ξ² : Type*} [unique Ξ²] : ⇑(prod_unique Ξ± Ξ²) = prod.fst := rfl lemma prod_unique_apply {Ξ± Ξ² : Type*} [unique Ξ²] (x : Ξ± Γ— Ξ²) : prod_unique Ξ± Ξ² x = x.1 := rfl @[simp] lemma prod_unique_symm_apply {Ξ± Ξ² : Type*} [unique Ξ²] (x : Ξ±) : (prod_unique Ξ± Ξ²).symm x = (x, default) := rfl /-- Any `unique` type is a left identity for type product up to equivalence. -/ def unique_prod (Ξ± Ξ² : Type*) [unique Ξ²] : Ξ² Γ— Ξ± ≃ Ξ± := ((equiv_punit Ξ²).prod_congr $ equiv.refl Ξ±).trans $ punit_prod Ξ± @[simp] lemma coe_unique_prod {Ξ± Ξ² : Type*} [unique Ξ²] : ⇑(unique_prod Ξ± Ξ²) = prod.snd := rfl lemma unique_prod_apply {Ξ± Ξ² : Type*} [unique Ξ²] (x : Ξ² Γ— Ξ±) : unique_prod Ξ± Ξ² x = x.2 := rfl @[simp] lemma unique_prod_symm_apply {Ξ± Ξ² : Type*} [unique Ξ²] (x : Ξ±) : (unique_prod Ξ± Ξ²).symm x = (default, x) := rfl /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (Ξ± : Type*) : Ξ± Γ— empty ≃ empty := equiv_empty _ /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (Ξ± : Type*) : empty Γ— Ξ± ≃ empty := equiv_empty _ /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (Ξ± : Type*) : Ξ± Γ— pempty ≃ pempty := equiv_pempty _ /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (Ξ± : Type*) : pempty Γ— Ξ± ≃ pempty := equiv_pempty _ end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (Ξ± Ξ² : Type*) : psum Ξ± Ξ² ≃ Ξ± βŠ• Ξ² := { to_fun := Ξ» s, psum.cases_on s inl inr, inv_fun := sum.elim psum.inl psum.inr, left_inv := Ξ» s, by cases s; refl, right_inv := Ξ» s, by cases s; refl } /-- If `Ξ± ≃ Ξ±'` and `Ξ² ≃ Ξ²'`, then `Ξ± βŠ• Ξ² ≃ Ξ±' βŠ• Ξ²'`. This is `sum.map` as an equivalence. -/ @[simps apply] def sum_congr {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Type*} (ea : α₁ ≃ Ξ±β‚‚) (eb : β₁ ≃ Ξ²β‚‚) : α₁ βŠ• β₁ ≃ Ξ±β‚‚ βŠ• Ξ²β‚‚ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, Ξ» x, by simp, Ξ» x, by simp⟩ /-- If `Ξ± ≃ Ξ±'` and `Ξ² ≃ Ξ²'`, then `psum Ξ± Ξ² ≃ psum Ξ±' Ξ²'`. -/ def psum_congr {Ξ΄ : Sort z} (e₁ : Ξ± ≃ Ξ²) (eβ‚‚ : Ξ³ ≃ Ξ΄) : psum Ξ± Ξ³ ≃ psum Ξ² Ξ΄ := { to_fun := Ξ» x, psum.cases_on x (psum.inl ∘ e₁) (psum.inr ∘ eβ‚‚), inv_fun := Ξ» x, psum.cases_on x (psum.inl ∘ e₁.symm) (psum.inr ∘ eβ‚‚.symm), left_inv := by rintro (x|x); simp, right_inv := by rintro (x|x); simp } /-- Combine two `equiv`s using `psum` in the domain and `sum` in the codomain. -/ def psum_sum {α₁ β₁ : Sort*} {Ξ±β‚‚ Ξ²β‚‚ : Type*} (ea : α₁ ≃ Ξ±β‚‚) (eb : β₁ ≃ Ξ²β‚‚) : psum α₁ β₁ ≃ Ξ±β‚‚ βŠ• Ξ²β‚‚ := (ea.psum_congr eb).trans (psum_equiv_sum _ _) /-- Combine two `equiv`s using `sum` in the domain and `psum` in the codomain. -/ def sum_psum {α₁ β₁ : Type*} {Ξ±β‚‚ Ξ²β‚‚ : Sort*} (ea : α₁ ≃ Ξ±β‚‚) (eb : β₁ ≃ Ξ²β‚‚) : α₁ βŠ• β₁ ≃ psum Ξ±β‚‚ Ξ²β‚‚ := (ea.symm.psum_sum eb.symm).symm @[simp] lemma sum_congr_trans {α₁ Ξ±β‚‚ β₁ Ξ²β‚‚ γ₁ Ξ³β‚‚ : Sort*} (e : α₁ ≃ β₁) (f : Ξ±β‚‚ ≃ Ξ²β‚‚) (g : β₁ ≃ γ₁) (h : Ξ²β‚‚ ≃ Ξ³β‚‚) : (equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) := by { ext i, cases i; refl } @[simp] lemma sum_congr_symm {Ξ± Ξ² Ξ³ Ξ΄ : Sort*} (e : Ξ± ≃ Ξ²) (f : Ξ³ ≃ Ξ΄) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl @[simp] lemma sum_congr_refl {Ξ± Ξ² : Sort*} : equiv.sum_congr (equiv.refl Ξ±) (equiv.refl Ξ²) = equiv.refl (Ξ± βŠ• Ξ²) := by { ext i, cases i; refl } namespace perm /-- Combine a permutation of `Ξ±` and of `Ξ²` into a permutation of `Ξ± βŠ• Ξ²`. -/ @[reducible] def sum_congr {Ξ± Ξ² : Type*} (ea : equiv.perm Ξ±) (eb : equiv.perm Ξ²) : equiv.perm (Ξ± βŠ• Ξ²) := equiv.sum_congr ea eb @[simp] lemma sum_congr_apply {Ξ± Ξ² : Type*} (ea : equiv.perm Ξ±) (eb : equiv.perm Ξ²) (x : Ξ± βŠ• Ξ²) : sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x @[simp] lemma sum_congr_trans {Ξ± Ξ² : Sort*} (e : equiv.perm Ξ±) (f : equiv.perm Ξ²) (g : equiv.perm Ξ±) (h : equiv.perm Ξ²) : (sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) := equiv.sum_congr_trans e f g h @[simp] lemma sum_congr_symm {Ξ± Ξ² : Sort*} (e : equiv.perm Ξ±) (f : equiv.perm Ξ²) : (sum_congr e f).symm = sum_congr (e.symm) (f.symm) := equiv.sum_congr_symm e f @[simp] lemma sum_congr_refl {Ξ± Ξ² : Sort*} : sum_congr (equiv.refl Ξ±) (equiv.refl Ξ²) = equiv.refl (Ξ± βŠ• Ξ²) := equiv.sum_congr_refl end perm /-- `bool` is equivalent the sum of two `punit`s. -/ def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} βŠ• punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), sum.elim (Ξ» _, ff) (Ξ» _, tt), Ξ» b, by cases b; refl, Ξ» s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ /-- Sum of types is commutative up to an equivalence. This is `sum.swap` as an equivalence. -/ @[simps apply {fully_applied := ff}] def sum_comm (Ξ± Ξ² : Type*) : Ξ± βŠ• Ξ² ≃ Ξ² βŠ• Ξ± := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_symm (Ξ± Ξ²) : (sum_comm Ξ± Ξ²).symm = sum_comm Ξ² Ξ± := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (Ξ± Ξ² Ξ³ : Type*) : (Ξ± βŠ• Ξ²) βŠ• Ξ³ ≃ Ξ± βŠ• (Ξ² βŠ• Ξ³) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] lemma sum_assoc_apply_inl_inl {Ξ± Ξ² Ξ³} (a) : sum_assoc Ξ± Ξ² Ξ³ (inl (inl a)) = inl a := rfl @[simp] lemma sum_assoc_apply_inl_inr {Ξ± Ξ² Ξ³} (b) : sum_assoc Ξ± Ξ² Ξ³ (inl (inr b)) = inr (inl b) := rfl @[simp] lemma sum_assoc_apply_inr {Ξ± Ξ² Ξ³} (c) : sum_assoc Ξ± Ξ² Ξ³ (inr c) = inr (inr c) := rfl @[simp] lemma sum_assoc_symm_apply_inl {Ξ± Ξ² Ξ³} (a) : (sum_assoc Ξ± Ξ² Ξ³).symm (inl a) = inl (inl a) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inl {Ξ± Ξ² Ξ³} (b) : (sum_assoc Ξ± Ξ² Ξ³).symm (inr (inl b)) = inl (inr b) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inr {Ξ± Ξ² Ξ³} (c) : (sum_assoc Ξ± Ξ² Ξ³).symm (inr (inr c)) = inr c := rfl /-- Sum with `empty` is equivalent to the original type. -/ @[simps symm_apply] def sum_empty (Ξ± Ξ² : Type*) [is_empty Ξ²] : Ξ± βŠ• Ξ² ≃ Ξ± := ⟨sum.elim id is_empty_elim, inl, Ξ» s, by { rcases s with _ | x, refl, exact is_empty_elim x }, Ξ» a, rfl⟩ @[simp] lemma sum_empty_apply_inl {Ξ± Ξ² : Type*} [is_empty Ξ²] (a : Ξ±) : sum_empty Ξ± Ξ² (sum.inl a) = a := rfl /-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/ @[simps symm_apply] def empty_sum (Ξ± Ξ² : Type*) [is_empty Ξ±] : Ξ± βŠ• Ξ² ≃ Ξ² := (sum_comm _ _).trans $ sum_empty _ _ @[simp] lemma empty_sum_apply_inr {Ξ± Ξ² : Type*} [is_empty Ξ±] (b : Ξ²) : empty_sum Ξ± Ξ² (sum.inr b) = b := rfl /-- `option Ξ±` is equivalent to `Ξ± βŠ• punit` -/ def option_equiv_sum_punit (Ξ± : Type*) : option Ξ± ≃ Ξ± βŠ• punit.{u+1} := ⟨λ o, o.elim (inr punit.star) inl, Ξ» s, s.elim some (Ξ» _, none), Ξ» o, by cases o; refl, Ξ» s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {Ξ±} : option_equiv_sum_punit Ξ± none = sum.inr punit.star := rfl @[simp] lemma option_equiv_sum_punit_some {Ξ±} (a) : option_equiv_sum_punit Ξ± (some a) = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_coe {Ξ±} (a : Ξ±) : option_equiv_sum_punit Ξ± a = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_symm_inl {Ξ±} (a) : (option_equiv_sum_punit Ξ±).symm (sum.inl a) = a := rfl @[simp] lemma option_equiv_sum_punit_symm_inr {Ξ±} (a) : (option_equiv_sum_punit Ξ±).symm (sum.inr a) = none := rfl /-- The set of `x : option Ξ±` such that `is_some x` is equivalent to `Ξ±`. -/ @[simps] def option_is_some_equiv (Ξ± : Type*) : {x : option Ξ± // x.is_some} ≃ Ξ± := { to_fun := Ξ» o, option.get o.2, inv_fun := Ξ» x, ⟨some x, dec_trivial⟩, left_inv := Ξ» o, subtype.eq $ option.some_get _, right_inv := Ξ» x, option.get_some _ _ } /-- The product over `option Ξ±` of `Ξ² a` is the binary product of the product over `Ξ±` of `Ξ² (some Ξ±)` and `Ξ² none` -/ @[simps] def pi_option_equiv_prod {Ξ± : Type*} {Ξ² : option Ξ± β†’ Type*} : (Ξ  a : option Ξ±, Ξ² a) ≃ (Ξ² none Γ— Ξ  a : Ξ±, Ξ² (some a)) := { to_fun := Ξ» f, (f none, Ξ» a, f (some a)), inv_fun := Ξ» x a, option.cases_on a x.fst x.snd, left_inv := Ξ» f, funext $ Ξ» a, by cases a; refl, right_inv := Ξ» x, by simp } /-- `Ξ± βŠ• Ξ²` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `Ξ±` and `Ξ²` to be types from the same universe, so it cannot by used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ulift` to work around this difficulty. -/ def sum_equiv_sigma_bool (Ξ± Ξ² : Type u) : Ξ± βŠ• Ξ² ≃ (Ξ£ b: bool, cond b Ξ± Ξ²) := ⟨λ s, s.elim (Ξ» x, ⟨tt, x⟩) (Ξ» x, ⟨ff, x⟩), Ξ» s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, Ξ» s, by cases s; refl, Ξ» s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_fiber_equiv f` for `f : Ξ± β†’ Ξ²` is the natural equivalence between the type of all fibres of `f` and the total space `Ξ±`. -/ -- See also `equiv.sigma_preimage_equiv`. @[simps] def sigma_fiber_equiv {Ξ± Ξ² : Type*} (f : Ξ± β†’ Ξ²) : (Ξ£ y : Ξ², {x // f x = y}) ≃ Ξ± := ⟨λ x, ↑x.2, Ξ» x, ⟨f x, x, rfl⟩, Ξ» ⟨y, x, rfl⟩, rfl, Ξ» x, rfl⟩ end section sum_compl /-- For any predicate `p` on `Ξ±`, the sum of the two subtypes `{a // p a}` and its complement `{a // Β¬ p a}` is naturally equivalent to `Ξ±`. See `subtype_or_equiv` for sum types over subtypes `{x // p x}` and `{x // q x}` that are not necessarily `is_compl p q`. -/ def sum_compl {Ξ± : Type*} (p : Ξ± β†’ Prop) [decidable_pred p] : {a // p a} βŠ• {a // Β¬ p a} ≃ Ξ± := { to_fun := sum.elim coe coe, inv_fun := Ξ» a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := Ξ» a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {Ξ± : Type*} (p : Ξ± β†’ Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {Ξ± : Type*} (p : Ξ± β†’ Prop) [decidable_pred p] (x : {a // Β¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {Ξ± : Type*} (p : Ξ± β†’ Prop) [decidable_pred p] (a : Ξ±) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {Ξ± : Type*} (p : Ξ± β†’ Prop) [decidable_pred p] (a : Ξ±) (h : Β¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h /-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a permutation. -/ def subtype_congr {Ξ± : Type*} {p q : Ξ± β†’ Prop} [decidable_pred p] [decidable_pred q] (e : {x // p x} ≃ {x // q x}) (f : {x // Β¬p x} ≃ {x // Β¬q x}) : perm Ξ± := (sum_compl p).symm.trans ((sum_congr e f).trans (sum_compl q)) open equiv variables {Ξ΅ : Type*} {p : Ξ΅ β†’ Prop} [decidable_pred p] variables (ep ep' : perm {a // p a}) (en en' : perm {a // Β¬ p a}) /-- Combining permutations on `Ξ΅` that permute only inside or outside the subtype split induced by `p : Ξ΅ β†’ Prop` constructs a permutation on `Ξ΅`. -/ def perm.subtype_congr : equiv.perm Ξ΅ := perm_congr (sum_compl p) (sum_congr ep en) lemma perm.subtype_congr.apply (a : Ξ΅) : ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ := by { by_cases h : p a; simp [perm.subtype_congr, h] } @[simp] lemma perm.subtype_congr.left_apply {a : Ξ΅} (h : p a) : ep.subtype_congr en a = ep ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) : ep.subtype_congr en a = ep a := by { convert perm.subtype_congr.left_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.right_apply {a : Ξ΅} (h : Β¬ p a) : ep.subtype_congr en a = en ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // Β¬ p a}) : ep.subtype_congr en a = en a := by { convert perm.subtype_congr.right_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.refl : perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // Β¬ p a}) = equiv.refl Ξ΅ := by { ext x, by_cases h : p x; simp [h] } @[simp] lemma perm.subtype_congr.symm : (ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm := begin ext x, by_cases h : p x, { have : p (ep.symm ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }, { have : Β¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end @[simp] lemma perm.subtype_congr.trans : (ep.subtype_congr en).trans (ep'.subtype_congr en') = perm.subtype_congr (ep.trans ep') (en.trans en') := begin ext x, by_cases h : p x, { have : p (ep ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, this] }, { have : Β¬ p (en ⟨x, h⟩) := subtype.property (en _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end end sum_compl section subtype_preimage variables (p : Ξ± β†’ Prop) [decidable_pred p] (xβ‚€ : {a // p a} β†’ Ξ²) /-- For a fixed function `xβ‚€ : {a // p a} β†’ Ξ²` defined on a subtype of `Ξ±`, the subtype of functions `x : Ξ± β†’ Ξ²` that agree with `xβ‚€` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // Β¬ p a} β†’ Ξ²`. -/ @[simps] def subtype_preimage : {x : Ξ± β†’ Ξ² // x ∘ coe = xβ‚€} ≃ ({a // Β¬ p a} β†’ Ξ²) := { to_fun := Ξ» (x : {x : Ξ± β†’ Ξ² // x ∘ coe = xβ‚€}) a, (x : Ξ± β†’ Ξ²) a, inv_fun := Ξ» x, ⟨λ a, if h : p a then xβ‚€ ⟨a, h⟩ else x ⟨a, h⟩, funext $ Ξ» ⟨a, h⟩, dif_pos h⟩, left_inv := Ξ» ⟨x, hx⟩, subtype.val_injective $ funext $ Ξ» a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := Ξ» x, funext $ Ξ» ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } } lemma subtype_preimage_symm_apply_coe_pos (x : {a // Β¬ p a} β†’ Ξ²) (a : Ξ±) (h : p a) : ((subtype_preimage p xβ‚€).symm x : Ξ± β†’ Ξ²) a = xβ‚€ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // Β¬ p a} β†’ Ξ²) (a : Ξ±) (h : Β¬ p a) : ((subtype_preimage p xβ‚€).symm x : Ξ± β†’ Ξ²) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section /-- A family of equivalences `Ξ  a, β₁ a ≃ Ξ²β‚‚ a` generates an equivalence between `Ξ  a, β₁ a` and `Ξ  a, Ξ²β‚‚ a`. -/ def Pi_congr_right {Ξ±} {β₁ Ξ²β‚‚ : Ξ± β†’ Sort*} (F : Ξ  a, β₁ a ≃ Ξ²β‚‚ a) : (Ξ  a, β₁ a) ≃ (Ξ  a, Ξ²β‚‚ a) := ⟨λ H a, F a (H a), Ξ» H a, (F a).symm (H a), Ξ» H, funext $ by simp, Ξ» H, funext $ by simp⟩ /-- Given `Ο† : Ξ± β†’ Ξ² β†’ Sort*`, we have an equivalence between `Ξ  a b, Ο† a b` and `Ξ  b a, Ο† a b`. This is `function.swap` as an `equiv`. -/ @[simps apply] def Pi_comm {Ξ± Ξ²} (Ο† : Ξ± β†’ Ξ² β†’ Sort*) : (Ξ  a b, Ο† a b) ≃ (Ξ  b a, Ο† a b) := ⟨swap, swap, Ξ» x, rfl, Ξ» y, rfl⟩ @[simp] lemma Pi_comm_symm {Ξ± Ξ²} {Ο† : Ξ± β†’ Ξ² β†’ Sort*} : (Pi_comm Ο†).symm = (Pi_comm $ swap Ο†) := rfl /-- Dependent `curry` equivalence: the type of dependent functions on `Ξ£ i, Ξ² i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/ def Pi_curry {Ξ±} {Ξ² : Ξ± β†’ Sort*} (Ξ³ : Ξ  a, Ξ² a β†’ Sort*) : (Ξ  x : Ξ£ i, Ξ² i, Ξ³ x.1 x.2) ≃ (Ξ  a b, Ξ³ a b) := { to_fun := sigma.curry, inv_fun := sigma.uncurry, left_inv := sigma.uncurry_curry, right_inv := sigma.curry_uncurry } end section prod_congr variables {α₁ β₁ Ξ²β‚‚ : Type*} (e : α₁ β†’ β₁ ≃ Ξ²β‚‚) /-- A family of equivalences `Ξ  (a : α₁), β₁ ≃ Ξ²β‚‚` generates an equivalence between `β₁ Γ— α₁` and `Ξ²β‚‚ Γ— α₁`. -/ def prod_congr_left : β₁ Γ— α₁ ≃ Ξ²β‚‚ Γ— α₁ := { to_fun := Ξ» ab, ⟨e ab.2 ab.1, ab.2⟩, inv_fun := Ξ» ab, ⟨(e ab.2).symm ab.1, ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) : prod_congr_left e (b, a) = (e a b, a) := rfl lemma prod_congr_refl_right (e : β₁ ≃ Ξ²β‚‚) : prod_congr e (equiv.refl α₁) = prod_congr_left (Ξ» _, e) := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences `Ξ  (a : α₁), β₁ ≃ Ξ²β‚‚` generates an equivalence between `α₁ Γ— β₁` and `α₁ Γ— Ξ²β‚‚`. -/ def prod_congr_right : α₁ Γ— β₁ ≃ α₁ Γ— Ξ²β‚‚ := { to_fun := Ξ» ab, ⟨ab.1, e ab.1 ab.2⟩, inv_fun := Ξ» ab, ⟨ab.1, (e ab.1).symm ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) : prod_congr_right e (a, b) = (a, e a b) := rfl lemma prod_congr_refl_left (e : β₁ ≃ Ξ²β‚‚) : prod_congr (equiv.refl α₁) e = prod_congr_right (Ξ» _, e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_left_trans_prod_comm : (prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_right_trans_prod_comm : (prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_congr_right_sigma_equiv_prod : (sigma_congr_right e).trans (sigma_equiv_prod α₁ Ξ²β‚‚) = (sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_equiv_prod_sigma_congr_right : (sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) = (prod_congr_right e).trans (sigma_equiv_prod α₁ Ξ²β‚‚).symm := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences between fibers gives an equivalence between domains. -/ -- See also `equiv.of_preimage_equiv`. @[simps] def of_fiber_equiv {Ξ± Ξ² Ξ³ : Type*} {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} (e : Ξ  c, {a // f a = c} ≃ {b // g b = c}) : Ξ± ≃ Ξ² := (sigma_fiber_equiv f).symm.trans $ (equiv.sigma_congr_right e).trans (sigma_fiber_equiv g) lemma of_fiber_equiv_map {Ξ± Ξ² Ξ³} {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} (e : Ξ  c, {a // f a = c} ≃ {b // g b = c}) (a : Ξ±) : g (of_fiber_equiv e a) = f a := (_ : {b // g b = _}).prop /-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps {fully_applied := ff}] def prod_shear {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Type*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ : α₁ β†’ β₁ ≃ Ξ²β‚‚) : α₁ Γ— β₁ ≃ Ξ±β‚‚ Γ— Ξ²β‚‚ := { to_fun := Ξ» x : α₁ Γ— β₁, (e₁ x.1, eβ‚‚ x.1 x.2), inv_fun := Ξ» y : Ξ±β‚‚ Γ— Ξ²β‚‚, (e₁.symm y.1, (eβ‚‚ $ e₁.symm y.1).symm y.2), left_inv := by { rintro ⟨x₁, yβ‚βŸ©, simp only [symm_apply_apply] }, right_inv := by { rintro ⟨x₁, yβ‚βŸ©, simp only [apply_symm_apply] } } end prod_congr namespace perm variables {α₁ β₁ Ξ²β‚‚ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁) /-- `prod_extend_right a e` extends `e : perm Ξ²` to `perm (Ξ± Γ— Ξ²)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prod_extend_right : perm (α₁ Γ— β₁) := { to_fun := Ξ» ab, if ab.fst = a then (a, e ab.snd) else ab, inv_fun := Ξ» ab, if ab.fst = a then (a, e.symm ab.snd) else ab, left_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] }, right_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] } } @[simp] lemma prod_extend_right_apply_eq (b : β₁) : prod_extend_right a e (a, b) = (a, e b) := if_pos rfl lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' β‰  a) (b : β₁) : prod_extend_right a e (a', b) = (a', b) := if_neg h lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁} (h : prod_extend_right a e (a', b) β‰  (a', b)) : a' = a := by { contrapose! h, exact prod_extend_right_apply_ne _ h _ } @[simp] lemma fst_prod_extend_right (ab : α₁ Γ— β₁) : (prod_extend_right a e ab).fst = ab.fst := begin rw [prod_extend_right, coe_fn_mk], split_ifs with h, { rw h }, { refl } end end perm section /-- The type of functions to a product `Ξ± Γ— Ξ²` is equivalent to the type of pairs of functions `Ξ³ β†’ Ξ±` and `Ξ³ β†’ Ξ²`. -/ def arrow_prod_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Type*) : (Ξ³ β†’ Ξ± Γ— Ξ²) ≃ (Ξ³ β†’ Ξ±) Γ— (Ξ³ β†’ Ξ²) := ⟨λ f, (Ξ» c, (f c).1, Ξ» c, (f c).2), Ξ» p c, (p.1 c, p.2 c), Ξ» f, funext $ Ξ» c, prod.mk.eta, Ξ» p, by { cases p, refl }⟩ open sum /-- The type of functions on a sum type `Ξ± βŠ• Ξ²` is equivalent to the type of pairs of functions on `Ξ±` and on `Ξ²`. -/ def sum_arrow_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Type*) : ((Ξ± βŠ• Ξ²) β†’ Ξ³) ≃ (Ξ± β†’ Ξ³) Γ— (Ξ² β†’ Ξ³) := ⟨λ f, (f ∘ inl, f ∘ inr), Ξ» p, sum.elim p.1 p.2, Ξ» f, by { ext ⟨⟩; refl }, Ξ» p, by { cases p, refl }⟩ @[simp] lemma sum_arrow_equiv_prod_arrow_apply_fst {Ξ± Ξ² Ξ³} (f : (Ξ± βŠ• Ξ²) β†’ Ξ³) (a : Ξ±) : (sum_arrow_equiv_prod_arrow Ξ± Ξ² Ξ³ f).1 a = f (inl a) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_apply_snd {Ξ± Ξ² Ξ³} (f : (Ξ± βŠ• Ξ²) β†’ Ξ³) (b : Ξ²) : (sum_arrow_equiv_prod_arrow Ξ± Ξ² Ξ³ f).2 b = f (inr b) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inl {Ξ± Ξ² Ξ³} (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ³) (a : Ξ±) : ((sum_arrow_equiv_prod_arrow Ξ± Ξ² Ξ³).symm (f, g)) (inl a) = f a := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inr {Ξ± Ξ² Ξ³} (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ³) (b : Ξ²) : ((sum_arrow_equiv_prod_arrow Ξ± Ξ² Ξ³).symm (f, g)) (inr b) = g b := rfl /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sum_prod_distrib (Ξ± Ξ² Ξ³ : Sort*) : (Ξ± βŠ• Ξ²) Γ— Ξ³ ≃ (Ξ± Γ— Ξ³) βŠ• (Ξ² Γ— Ξ³) := ⟨λ p, p.1.map (Ξ» x, (x, p.2)) (Ξ» x, (x, p.2)), Ξ» s, s.elim (prod.map inl id) (prod.map inr id), by rintro ⟨_ | _, _⟩; refl, by rintro (⟨_, _⟩ | ⟨_, _⟩); refl⟩ @[simp] theorem sum_prod_distrib_apply_left {Ξ± Ξ² Ξ³} (a : Ξ±) (c : Ξ³) : sum_prod_distrib Ξ± Ξ² Ξ³ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {Ξ± Ξ² Ξ³} (b : Ξ²) (c : Ξ³) : sum_prod_distrib Ξ± Ξ² Ξ³ (sum.inr b, c) = sum.inr (b, c) := rfl @[simp] theorem sum_prod_distrib_symm_apply_left {Ξ± Ξ² Ξ³} (a : Ξ± Γ— Ξ³) : (sum_prod_distrib Ξ± Ξ² Ξ³).symm (inl a) = (inl a.1, a.2) := rfl @[simp] theorem sum_prod_distrib_symm_apply_right {Ξ± Ξ² Ξ³} (b : Ξ² Γ— Ξ³) : (sum_prod_distrib Ξ± Ξ² Ξ³).symm (inr b) = (inr b.1, b.2) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prod_sum_distrib (Ξ± Ξ² Ξ³ : Sort*) : Ξ± Γ— (Ξ² βŠ• Ξ³) ≃ (Ξ± Γ— Ξ²) βŠ• (Ξ± Γ— Ξ³) := calc Ξ± Γ— (Ξ² βŠ• Ξ³) ≃ (Ξ² βŠ• Ξ³) Γ— Ξ± : prod_comm _ _ ... ≃ (Ξ² Γ— Ξ±) βŠ• (Ξ³ Γ— Ξ±) : sum_prod_distrib _ _ _ ... ≃ (Ξ± Γ— Ξ²) βŠ• (Ξ± Γ— Ξ³) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {Ξ± Ξ² Ξ³} (a : Ξ±) (b : Ξ²) : prod_sum_distrib Ξ± Ξ² Ξ³ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {Ξ± Ξ² Ξ³} (a : Ξ±) (c : Ξ³) : prod_sum_distrib Ξ± Ξ² Ξ³ (a, sum.inr c) = sum.inr (a, c) := rfl @[simp] theorem prod_sum_distrib_symm_apply_left {Ξ± Ξ² Ξ³} (a : Ξ± Γ— Ξ²) : (prod_sum_distrib Ξ± Ξ² Ξ³).symm (inl a) = (a.1, inl a.2) := rfl @[simp] theorem prod_sum_distrib_symm_apply_right {Ξ± Ξ² Ξ³} (a : Ξ± Γ— Ξ³) : (prod_sum_distrib Ξ± Ξ² Ξ³).symm (inr a) = (a.1, inr a.2) := rfl /-- An indexed sum of disjoint sums of types is equivalent to the sum of the indexed sums. -/ @[simps] def sigma_sum_distrib {ΞΉ : Type*} (Ξ± Ξ² : ΞΉ β†’ Type*) : (Ξ£ i, Ξ± i βŠ• Ξ² i) ≃ (Ξ£ i, Ξ± i) βŠ• Ξ£ i, Ξ² i := ⟨λ p, p.2.map (sigma.mk p.1) (sigma.mk p.1), sum.elim (sigma.map id (Ξ» _, sum.inl)) (sigma.map id (Ξ» _, sum.inr)), Ξ» p, by { rcases p with ⟨i, (a | b)⟩; refl }, Ξ» p, by { rcases p with (⟨i, a⟩ | ⟨i, b⟩); refl }⟩ /-- The product of an indexed sum of types (formally, a `sigma`-type `Ξ£ i, Ξ± i`) by a type `Ξ²` is equivalent to the sum of products `Ξ£ i, (Ξ± i Γ— Ξ²)`. -/ def sigma_prod_distrib {ΞΉ : Type*} (Ξ± : ΞΉ β†’ Type*) (Ξ² : Type*) : ((Ξ£ i, Ξ± i) Γ— Ξ²) ≃ (Ξ£ i, (Ξ± i Γ— Ξ²)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, Ξ» p, (⟨p.1, p.2.1⟩, p.2.2), Ξ» p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, Ξ» p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ /-- An equivalence that separates out the 0th fiber of `(Ξ£ (n : β„•), f n)`. -/ def sigma_nat_succ (f : β„• β†’ Type u) : (Ξ£ n, f n) ≃ f 0 βŠ• Ξ£ n, f (n + 1) := ⟨λ x, @sigma.cases_on β„• f (Ξ» _, f 0 βŠ• Ξ£ n, f (n + 1)) x (Ξ» n, @nat.cases_on (Ξ» i, f i β†’ (f 0 βŠ• Ξ£ (n : β„•), f (n + 1))) n (Ξ» (x : f 0), sum.inl x) (Ξ» (n : β„•) (x : f n.succ), sum.inr ⟨n, x⟩)), sum.elim (sigma.mk 0) (sigma.map nat.succ (Ξ» _, id)), by { rintro ⟨(n | n), x⟩; refl }, by { rintro (x | ⟨n, x⟩); refl }⟩ /-- The product `bool Γ— Ξ±` is equivalent to `Ξ± βŠ• Ξ±`. -/ @[simps] def bool_prod_equiv_sum (Ξ± : Type u) : bool Γ— Ξ± ≃ Ξ± βŠ• Ξ± := { to_fun := Ξ» p, cond p.1 (inr p.2) (inl p.2), inv_fun := sum.elim (prod.mk ff) (prod.mk tt), left_inv := by rintro ⟨(_|_), _⟩; refl, right_inv := by rintro (_|_); refl } /-- The function type `bool β†’ Ξ±` is equivalent to `Ξ± Γ— Ξ±`. -/ @[simps] def bool_arrow_equiv_prod (Ξ± : Type u) : (bool β†’ Ξ±) ≃ Ξ± Γ— Ξ± := { to_fun := Ξ» f, (f tt, f ff), inv_fun := Ξ» p b, cond b p.1 p.2, left_inv := Ξ» f, funext $ bool.forall_bool.2 ⟨rfl, rfl⟩, right_inv := Ξ» ⟨x, y⟩, rfl } end section open sum nat /-- The set of natural numbers is equivalent to `β„• βŠ• punit`. -/ def nat_equiv_nat_sum_punit : β„• ≃ β„• βŠ• punit.{u+1} := { to_fun := Ξ» n, nat.cases_on n (inr punit.star) inl, inv_fun := sum.elim nat.succ (Ξ» _, 0), left_inv := Ξ» n, by cases n; refl, right_inv := by rintro (_|_|_); refl } /-- `β„• βŠ• punit` is equivalent to `β„•`. -/ def nat_sum_punit_equiv_nat : β„• βŠ• punit.{u+1} ≃ β„• := nat_equiv_nat_sum_punit.symm /-- The type of integer numbers is equivalent to `β„• βŠ• β„•`. -/ def int_equiv_nat_sum_nat : β„€ ≃ β„• βŠ• β„• := { to_fun := Ξ» z, int.cases_on z inl inr, inv_fun := sum.elim coe int.neg_succ_of_nat, left_inv := by rintro (m|n); refl, right_inv := by rintro (m|n); refl } end /-- An equivalence between `Ξ±` and `Ξ²` generates an equivalence between `list Ξ±` and `list Ξ²`. -/ def list_equiv_of_equiv {Ξ± Ξ² : Type*} (e : Ξ± ≃ Ξ²) : list Ξ± ≃ list Ξ² := { to_fun := list.map e, inv_fun := list.map e.symm, left_inv := Ξ» l, by rw [list.map_map, e.symm_comp_self, list.map_id], right_inv := Ξ» l, by rw [list.map_map, e.self_comp_symm, list.map_id] } /-- If `Ξ±` is equivalent to `Ξ²`, then `unique Ξ±` is equivalent to `unique Ξ²`. -/ def unique_congr (e : Ξ± ≃ Ξ²) : unique Ξ± ≃ unique Ξ² := { to_fun := Ξ» h, @equiv.unique _ _ h e.symm, inv_fun := Ξ» h, @equiv.unique _ _ h e, left_inv := Ξ» _, subsingleton.elim _ _, right_inv := Ξ» _, subsingleton.elim _ _ } /-- If `Ξ±` is equivalent to `Ξ²`, then `is_empty Ξ±` is equivalent to `is_empty Ξ²`. -/ lemma is_empty_congr (e : Ξ± ≃ Ξ²) : is_empty Ξ± ↔ is_empty Ξ² := ⟨λ h, @function.is_empty _ _ h e.symm, Ξ» h, @function.is_empty _ _ h e⟩ protected lemma is_empty (e : Ξ± ≃ Ξ²) [is_empty Ξ²] : is_empty Ξ± := e.is_empty_congr.mpr β€Ή_β€Ί section open subtype /-- If `Ξ±` is equivalent to `Ξ²` and the predicates `p : Ξ± β†’ Prop` and `q : Ξ² β†’ Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. For the statement where `Ξ± = Ξ²`, that is, `e : perm Ξ±`, see `perm.subtype_perm`. -/ def subtype_equiv {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} (e : Ξ± ≃ Ξ²) (h : βˆ€ a, p a ↔ q (e a)) : {a : Ξ± // p a} ≃ {b : Ξ² // q b} := { to_fun := Ξ» a, ⟨e a, (h _).mp a.prop⟩, inv_fun := Ξ» b, ⟨e.symm b, (h _).mpr ((e.apply_symm_apply b).symm β–Έ b.prop)⟩, left_inv := Ξ» a, subtype.ext $ by simp, right_inv := Ξ» b, subtype.ext $ by simp } @[simp] lemma subtype_equiv_refl {p : Ξ± β†’ Prop} (h : βˆ€ a, p a ↔ p (equiv.refl _ a) := Ξ» a, iff.rfl) : (equiv.refl Ξ±).subtype_equiv h = equiv.refl {a : Ξ± // p a} := by { ext, refl } @[simp] lemma subtype_equiv_symm {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} (e : Ξ± ≃ Ξ²) (h : βˆ€ (a : Ξ±), p a ↔ q (e a)) : (e.subtype_equiv h).symm = e.symm.subtype_equiv (Ξ» a, by { convert (h $ e.symm a).symm, exact (e.apply_symm_apply a).symm }) := rfl @[simp] lemma subtype_equiv_trans {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} {r : Ξ³ β†’ Prop} (e : Ξ± ≃ Ξ²) (f : Ξ² ≃ Ξ³) (h : βˆ€ (a : Ξ±), p a ↔ q (e a)) (h' : βˆ€ (b : Ξ²), q b ↔ r (f b)): (e.subtype_equiv h).trans (f.subtype_equiv h') = (e.trans f).subtype_equiv (Ξ» a, (h a).trans (h' $ e a)) := rfl @[simp] lemma subtype_equiv_apply {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} (e : Ξ± ≃ Ξ²) (h : βˆ€ (a : Ξ±), p a ↔ q (e a)) (x : {x // p x}) : e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps] def subtype_equiv_right {p q : Ξ± β†’ Prop} (e : βˆ€x, p x ↔ q x) : {x // p x} ≃ {x // q x} := subtype_equiv (equiv.refl _) e /-- If `Ξ± ≃ Ξ²`, then for any predicate `p : Ξ² β†’ Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtype_equiv_of_subtype {p : Ξ² β†’ Prop} (e : Ξ± ≃ Ξ²) : {a : Ξ± // p (e a)} ≃ {b : Ξ² // p b} := subtype_equiv e $ by simp /-- If `Ξ± ≃ Ξ²`, then for any predicate `p : Ξ± β†’ Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtype_equiv_of_subtype' {p : Ξ± β†’ Prop} (e : Ξ± ≃ Ξ²) : {a : Ξ± // p a} ≃ {b : Ξ² // p (e.symm b)} := e.symm.subtype_equiv_of_subtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtype_equiv_prop {Ξ± : Type*} {p q : Ξ± β†’ Prop} (h : p = q) : subtype p ≃ subtype q := subtype_equiv (equiv.refl Ξ±) (assume a, h β–Έ iff.rfl) /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the β€œinner” predicate to depend on `h : p a`. -/ @[simps] def subtype_subtype_equiv_subtype_exists {Ξ± : Type u} (p : Ξ± β†’ Prop) (q : subtype p β†’ Prop) : subtype q ≃ {a : Ξ± // βˆƒh:p a, q ⟨a, h⟩ } := ⟨λ a, ⟨a, a.1.2, by { rcases a with ⟨⟨a, hap⟩, haq⟩, exact haq }⟩, Ξ» a, ⟨⟨a, a.2.fst⟩, a.2.snd⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, hβ‚‚βŸ©, rfl⟩ /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ @[simps] def subtype_subtype_equiv_subtype_inter {Ξ± : Type u} (p q : Ξ± β†’ Prop) : {x : subtype p // q x.1} ≃ subtype (Ξ» x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_equiv_right $ Ξ» x, exists_prop /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ @[simps] def subtype_subtype_equiv_subtype {Ξ± : Type u} {p q : Ξ± β†’ Prop} (h : βˆ€ {x}, q x β†’ p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_equiv_right $ Ξ» x, and_iff_right_of_imp h /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ @[simps apply symm_apply] def subtype_univ_equiv {Ξ± : Type u} {p : Ξ± β†’ Prop} (h : βˆ€ x, p x) : subtype p ≃ Ξ± := ⟨λ x, x, Ξ» x, ⟨x, h x⟩, Ξ» x, subtype.eq rfl, Ξ» x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {Ξ± : Type u} (p : Ξ± β†’ Type v) (q : Ξ± β†’ Prop) : { y : sigma p // q y.1 } ≃ Ξ£(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, Ξ» x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, Ξ» ⟨⟨x, h⟩, y⟩, rfl, Ξ» ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {Ξ± : Type u} (p : Ξ± β†’ Type v) (q : Ξ± β†’ Prop) (h : βˆ€ x, p x β†’ q x) : (Ξ£ x : subtype q, p x) ≃ Ξ£ x : Ξ±, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ Ξ» x, h x.1 x.2 /-- If a predicate `p : Ξ² β†’ Prop` is true on the range of a map `f : Ξ± β†’ Ξ²`, then `Ξ£ y : {y // p y}, {x // f x = y}` is equivalent to `Ξ±`. -/ def sigma_subtype_fiber_equiv {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (p : Ξ² β†’ Prop) (h : βˆ€ x, p (f x)) : (Ξ£ y : subtype p, {x : Ξ± // f x = y}) ≃ Ξ± := calc _ ≃ Ξ£ y : Ξ², {x : Ξ± // f x = y} : sigma_subtype_equiv_of_subset _ p (Ξ» y ⟨x, h'⟩, h' β–Έ h x) ... ≃ Ξ± : sigma_fiber_equiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Ξ£ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigma_subtype_fiber_equiv_subtype {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} (h : βˆ€ x, p x ↔ q (f x)) : (Ξ£ y : subtype q, {x : Ξ± // f x = y}) ≃ subtype p := calc (Ξ£ y : subtype q, {x : Ξ± // f x = y}) ≃ Ξ£ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', Ξ» h', ⟨(h x).2 (h'.symm β–Έ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_fiber_equiv (Ξ» x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) /-- A sigma type over an `option` is equivalent to the sigma set over the original type, if the fiber is empty at none. -/ def sigma_option_equiv_of_some {Ξ± : Type u} (p : option Ξ± β†’ Type v) (h : p none β†’ false) : (Ξ£ x : option Ξ±, p x) ≃ (Ξ£ x : Ξ±, p (some x)) := begin have h' : βˆ€ x, p x β†’ x.is_some, { intro x, cases x, { intro n, exfalso, exact h n }, { intro s, exact rfl } }, exact (sigma_subtype_equiv_of_subset _ _ h').symm.trans (sigma_congr_left' (option_is_some_equiv Ξ±)), end /-- The `pi`-type `Ξ  i, Ο€ i` is equivalent to the type of sections `f : ΞΉ β†’ Ξ£ i, Ο€ i` of the `sigma` type such that for all `i` we have `(f i).fst = i`. -/ def pi_equiv_subtype_sigma (ΞΉ : Type*) (Ο€ : ΞΉ β†’ Type*) : (Ξ  i, Ο€ i) ≃ {f : ΞΉ β†’ Ξ£ i, Ο€ i // βˆ€ i, (f i).1 = i } := ⟨ Ξ»f, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, Ξ»f i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ /-- The set of functions `f : Ξ  a, Ξ² a` such that for all `a` we have `p a (f a)` is equivalent to the set of functions `Ξ  a, {b : Ξ² a // p a b}`. -/ def subtype_pi_equiv_pi {Ξ± : Sort u} {Ξ² : Ξ± β†’ Sort v} {p : Ξ a, Ξ² a β†’ Prop} : {f : Ξ a, Ξ² a // βˆ€a, p a (f a) } ≃ Ξ a, { b : Ξ² a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, Ξ»f, ⟨λa, (f a).1, Ξ»a, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.ext_val rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {Ξ± : Type u} {Ξ² : Type v} {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} : {c : Ξ± Γ— Ξ² // p c.1 ∧ q c.2} ≃ ({a // p a} Γ— {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, Ξ» x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, Ξ» ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, Ξ» ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ /-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/ def subtype_prod_equiv_sigma_subtype {Ξ± Ξ² : Type*} (p : Ξ± β†’ Ξ² β†’ Prop) : {x : Ξ± Γ— Ξ² // p x.1 x.2} ≃ Ξ£ a, {b : Ξ² // p a b} := { to_fun := Ξ» x, ⟨x.1.1, x.1.2, x.prop⟩, inv_fun := Ξ» x, ⟨⟨x.1, x.2⟩, x.2.prop⟩, left_inv := Ξ» x, by ext; refl, right_inv := Ξ» ⟨a, b, pab⟩, rfl } /-- The type `Ξ  (i : Ξ±), Ξ² i` can be split as a product by separating the indices in `Ξ±` depending on whether they satisfy a predicate `p` or not. -/ @[simps] def pi_equiv_pi_subtype_prod {Ξ± : Type*} (p : Ξ± β†’ Prop) (Ξ² : Ξ± β†’ Type*) [decidable_pred p] : (Ξ  (i : Ξ±), Ξ² i) ≃ (Ξ  (i : {x // p x}), Ξ² i) Γ— (Ξ  (i : {x // Β¬ p x}), Ξ² i) := { to_fun := Ξ» f, (Ξ» x, f x, Ξ» x, f x), inv_fun := Ξ» f x, if h : p x then f.1 ⟨x, h⟩ else f.2 ⟨x, h⟩, right_inv := begin rintros ⟨f, g⟩, ext1; { ext y, rcases y, simp only [y_property, dif_pos, dif_neg, not_false_iff, subtype.coe_mk], refl }, end, left_inv := Ξ» f, begin ext x, by_cases h : p x; { simp only [h, dif_neg, dif_pos, not_false_iff], refl }, end } /-- A product of types can be split as the binary product of one of the types and the product of all the remaining types. -/ @[simps] def pi_split_at {Ξ± : Type*} [decidable_eq Ξ±] (i : Ξ±) (Ξ² : Ξ± β†’ Type*) : (Ξ  j, Ξ² j) ≃ Ξ² i Γ— Ξ  j : {j // j β‰  i}, Ξ² j := { to_fun := Ξ» f, ⟨f i, Ξ» j, f j⟩, inv_fun := Ξ» f j, if h : j = i then h.symm.rec f.1 else f.2 ⟨j, h⟩, right_inv := Ξ» f, by { ext, exacts [dif_pos rfl, (dif_neg x.2).trans (by cases x; refl)] }, left_inv := Ξ» f, by { ext, dsimp only, split_ifs, { subst h }, { refl } } } /-- A product of copies of a type can be split as the binary product of one copy and the product of all the remaining copies. -/ @[simps] def fun_split_at {Ξ± : Type*} [decidable_eq Ξ±] (i : Ξ±) (Ξ² : Type*) : (Ξ± β†’ Ξ²) ≃ Ξ² Γ— ({j // j β‰  i} β†’ Ξ²) := pi_split_at i _ end section subtype_equiv_codomain variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X} /-- The type of all functions `X β†’ Y` with prescribed values for all `x' β‰  x` is equivalent to the codomain `Y`. -/ def subtype_equiv_codomain (f : {x' // x' β‰  x} β†’ Y) : {g : X β†’ Y // g ∘ coe = f} ≃ Y := (subtype_preimage _ f).trans $ @fun_unique {x' // Β¬ x' β‰  x} _ $ show unique {x' // Β¬ x' β‰  x}, from @equiv.unique _ _ (show unique {x' // x' = x}, from { default := ⟨x, rfl⟩, uniq := Ξ» ⟨x', h⟩, subtype.val_injective h }) (subtype_equiv_right $ Ξ» a, not_not) @[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' β‰  x} β†’ Y) : (subtype_equiv_codomain f : {g : X β†’ Y // g ∘ coe = f} β†’ Y) = Ξ» g, (g : X β†’ Y) x := rfl @[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' β‰  x} β†’ Y) (g : {g : X β†’ Y // g ∘ coe = f}) : subtype_equiv_codomain f g = (g : X β†’ Y) x := rfl lemma coe_subtype_equiv_codomain_symm (f : {x' // x' β‰  x} β†’ Y) : ((subtype_equiv_codomain f).symm : Y β†’ {g : X β†’ Y // g ∘ coe = f}) = Ξ» y, ⟨λ x', if h : x' β‰  x then f ⟨x', h⟩ else y, by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl @[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' β‰  x} β†’ Y) (y : Y) (x' : X) : ((subtype_equiv_codomain f).symm y : X β†’ Y) x' = if h : x' β‰  x then f ⟨x', h⟩ else y := rfl @[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' β‰  x} β†’ Y) (y : Y) : ((subtype_equiv_codomain f).symm y : X β†’ Y) x = y := dif_neg (not_not.mpr rfl) lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' β‰  x} β†’ Y) (y : Y) (x' : X) (h : x' β‰  x) : ((subtype_equiv_codomain f).symm y : X β†’ Y) x' = f ⟨x', h⟩ := dif_pos h end subtype_equiv_codomain /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def of_bijective (f : Ξ± β†’ Ξ²) (hf : bijective f) : Ξ± ≃ Ξ² := { to_fun := f, inv_fun := function.surj_inv hf.surjective, left_inv := function.left_inverse_surj_inv hf, right_inv := function.right_inverse_surj_inv _} lemma of_bijective_apply_symm_apply (f : Ξ± β†’ Ξ²) (hf : bijective f) (x : Ξ²) : f ((of_bijective f hf).symm x) = x := (of_bijective f hf).apply_symm_apply x @[simp] lemma of_bijective_symm_apply_apply (f : Ξ± β†’ Ξ²) (hf : bijective f) (x : Ξ±) : (of_bijective f hf).symm (f x) = x := (of_bijective f hf).symm_apply_apply x instance : can_lift (Ξ± β†’ Ξ²) (Ξ± ≃ Ξ²) coe_fn bijective := { prf := Ξ» f hf, ⟨of_bijective f hf, rfl⟩ } section variables {Ξ±' Ξ²' : Type*} (e : perm Ξ±') {p : Ξ²' β†’ Prop} [decidable_pred p] (f : Ξ±' ≃ subtype p) /-- Extend the domain of `e : equiv.perm Ξ±` to one that is over `Ξ²` via `f : Ξ± β†’ subtype p`, where `p : Ξ² β†’ Prop`, permuting only the `b : Ξ²` that satisfy `p b`. This can be used to extend the domain across a function `f : Ξ± β†’ Ξ²`, keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known inverse, or `equiv.of_injective` in the general case.`. -/ def perm.extend_domain : perm Ξ²' := (perm_congr f e).subtype_congr (equiv.refl _) @[simp] lemma perm.extend_domain_apply_image (a : Ξ±') : e.extend_domain f (f a) = f (e a) := by simp [perm.extend_domain] lemma perm.extend_domain_apply_subtype {b : Ξ²'} (h : p b) : e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) := by simp [perm.extend_domain, h] lemma perm.extend_domain_apply_not_subtype {b : Ξ²'} (h : Β¬ p b) : e.extend_domain f b = b := by simp [perm.extend_domain, h] @[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ := by simp [perm.extend_domain] @[simp] lemma perm.extend_domain_symm : (e.extend_domain f).symm = perm.extend_domain e.symm f := rfl lemma perm.extend_domain_trans (e e' : perm Ξ±') : (e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f := by simp [perm.extend_domain, perm_congr_trans] end /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `Ξ±` be a setoid with equivalence relation `~`. Let `pβ‚‚` be a predicate on the quotient type `Ξ±/~`, and `p₁` be the lift of this predicate to `Ξ±`: `p₁ a ↔ pβ‚‚ ⟦a⟧`. Let `~β‚‚` be the restriction of `~` to `{x // p₁ x}`. Then `{x // pβ‚‚ x}` is equivalent to the quotient of `{x // p₁ x}` by `~β‚‚`. -/ def subtype_quotient_equiv_quotient_subtype (p₁ : Ξ± β†’ Prop) [s₁ : setoid Ξ±] [sβ‚‚ : setoid (subtype p₁)] (pβ‚‚ : quotient s₁ β†’ Prop) (hpβ‚‚ : βˆ€ a, p₁ a ↔ pβ‚‚ ⟦a⟧) (h : βˆ€ x y : subtype p₁, @setoid.r _ sβ‚‚ x y ↔ (x : Ξ±) β‰ˆ y) : {x // pβ‚‚ x} ≃ quotient sβ‚‚ := { to_fun := Ξ» a, quotient.hrec_on a.1 (Ξ» a h, ⟦⟨a, (hpβ‚‚ _).2 h⟩⟧) (Ξ» a b hab, hfunext (by rw quotient.sound hab) (Ξ» h₁ hβ‚‚ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := Ξ» a, quotient.lift_on a (Ξ» a, (⟨⟦a.1⟧, (hpβ‚‚ _).1 a.2⟩ : {x // pβ‚‚ x})) (Ξ» a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))), left_inv := Ξ» ⟨a, ha⟩, quotient.induction_on a (Ξ» a ha, rfl) ha, right_inv := Ξ» a, quotient.induction_on a (Ξ» ⟨a, ha⟩, rfl) } @[simp] lemma subtype_quotient_equiv_quotient_subtype_mk (p₁ : Ξ± β†’ Prop) [s₁ : setoid Ξ±] [sβ‚‚ : setoid (subtype p₁)] (pβ‚‚ : quotient s₁ β†’ Prop) (hpβ‚‚ : βˆ€ a, p₁ a ↔ pβ‚‚ ⟦a⟧) (h : βˆ€ x y : subtype p₁, @setoid.r _ sβ‚‚ x y ↔ (x : Ξ±) β‰ˆ y) (x hx) : subtype_quotient_equiv_quotient_subtype p₁ pβ‚‚ hpβ‚‚ h ⟨⟦x⟧, hx⟩ = ⟦⟨x, (hpβ‚‚ _).2 hx⟩⟧ := rfl @[simp] lemma subtype_quotient_equiv_quotient_subtype_symm_mk (p₁ : Ξ± β†’ Prop) [s₁ : setoid Ξ±] [sβ‚‚ : setoid (subtype p₁)] (pβ‚‚ : quotient s₁ β†’ Prop) (hpβ‚‚ : βˆ€ a, p₁ a ↔ pβ‚‚ ⟦a⟧) (h : βˆ€ x y : subtype p₁, @setoid.r _ sβ‚‚ x y ↔ (x : Ξ±) β‰ˆ y) (x) : (subtype_quotient_equiv_quotient_subtype p₁ pβ‚‚ hpβ‚‚ h).symm ⟦x⟧ = ⟨⟦x⟧, (hpβ‚‚ _).1 x.prop⟩ := rfl section swap variable [decidable_eq Ξ±] /-- A helper function for `equiv.swap`. -/ def swap_core (a b r : Ξ±) : Ξ± := if r = a then b else if r = b then a else r theorem swap_core_self (r a : Ξ±) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : Ξ±) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : Ξ±) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : Ξ±) : perm Ξ± := ⟨swap_core a b, swap_core a b, Ξ»r, swap_core_swap_core r a b, Ξ»r, swap_core_swap_core r a b⟩ @[simp] theorem swap_self (a : Ξ±) : swap a a = equiv.refl _ := ext $ Ξ» r, swap_core_self r a theorem swap_comm (a b : Ξ±) : swap a b = swap b a := ext $ Ξ» r, swap_core_comm r _ _ theorem swap_apply_def (a b x : Ξ±) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : Ξ±) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : Ξ±) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : Ξ±} : x β‰  a β†’ x β‰  b β†’ swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : Ξ±) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ Ξ» x, swap_core_swap_core _ _ _ @[simp] lemma symm_swap (a b : Ξ±) : (swap a b).symm = swap a b := rfl @[simp] lemma swap_eq_refl_iff {x y : Ξ±} : swap x y = equiv.refl _ ↔ x = y := begin refine ⟨λ h, (equiv.refl _).injective _, Ξ» h, h β–Έ (swap_self _)⟩, rw [←h, swap_apply_left, h, refl_apply] end theorem swap_comp_apply {a b x : Ξ±} (Ο€ : perm Ξ±) : Ο€.trans (swap a b) x = if Ο€ x = a then b else if Ο€ x = b then a else Ο€ x := by { cases Ο€, refl } lemma swap_eq_update (i j : Ξ±) : (equiv.swap i j : Ξ± β†’ Ξ±) = update (update id j i) i j := funext $ Ξ» x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def] lemma comp_swap_eq_update (i j : Ξ±) (f : Ξ± β†’ Ξ²) : f ∘ equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp.right_id] @[simp] lemma symm_trans_swap_trans [decidable_eq Ξ²] (a b : Ξ±) (e : Ξ± ≃ Ξ²) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (Ξ» x, begin have : βˆ€ a, e.symm x = a ↔ x = e a := Ξ» a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma trans_swap_trans_symm [decidable_eq Ξ²] (a b : Ξ²) (e : Ξ± ≃ Ξ²) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] lemma swap_apply_self (i j a : Ξ±) : swap i j (swap i j a) = a := by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ lemma apply_swap_eq_self {v : Ξ± β†’ Ξ²} {i j : Ξ±} (hv : v i = v j) (k : Ξ±) : v (swap i j k) = v k := begin by_cases hi : k = i, { rw [hi, swap_apply_left, hv] }, by_cases hj : k = j, { rw [hj, swap_apply_right, hv] }, rw swap_apply_of_ne_of_ne hi hj, end lemma swap_apply_eq_iff {x y z w : Ξ±} : swap x y z = w ↔ z = swap x y w := by rw [apply_eq_iff_eq_symm_apply, symm_swap] lemma swap_apply_ne_self_iff {a b x : Ξ±} : swap a b x β‰  x ↔ a β‰  b ∧ (x = a ∨ x = b) := begin by_cases hab : a = b, { simp [hab] }, by_cases hax : x = a, { simp [hax, eq_comm] }, by_cases hbx : x = b, { simp [hbx] }, simp [hab, hax, hbx, swap_apply_of_ne_of_ne] end namespace perm @[simp] lemma sum_congr_swap_refl {Ξ± Ξ² : Sort*} [decidable_eq Ξ±] [decidable_eq Ξ²] (i j : Ξ±) : equiv.perm.sum_congr (equiv.swap i j) (equiv.refl Ξ²) = equiv.swap (sum.inl i) (sum.inl j) := begin ext x, cases x, { simp [sum.map, swap_apply_def], split_ifs; refl}, { simp [sum.map, swap_apply_of_ne_of_ne] }, end @[simp] lemma sum_congr_refl_swap {Ξ± Ξ² : Sort*} [decidable_eq Ξ±] [decidable_eq Ξ²] (i j : Ξ²) : equiv.perm.sum_congr (equiv.refl Ξ±) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := begin ext x, cases x, { simp [sum.map, swap_apply_of_ne_of_ne] }, { simp [sum.map, swap_apply_def], split_ifs; refl}, end end perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : Ξ± ≃ Ξ²) (a : Ξ±) (b : Ξ²) : Ξ± ≃ Ξ² := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : Ξ± ≃ Ξ²) (a : Ξ±) (b : Ξ²) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap end equiv namespace function.involutive /-- Convert an involutive function `f` to a permutation with `to_fun = inv_fun = f`. -/ def to_perm (f : Ξ± β†’ Ξ±) (h : involutive f) : equiv.perm Ξ± := ⟨f, f, h.left_inverse, h.right_inverse⟩ @[simp] lemma coe_to_perm {f : Ξ± β†’ Ξ±} (h : involutive f) : (h.to_perm f : Ξ± β†’ Ξ±) = f := rfl @[simp] lemma to_perm_symm {f : Ξ± β†’ Ξ±} (h : involutive f) : (h.to_perm f).symm = h.to_perm f := rfl lemma to_perm_involutive {f : Ξ± β†’ Ξ±} (h : involutive f) : involutive (h.to_perm f) := h end function.involutive lemma plift.eq_up_iff_down_eq {x : plift Ξ±} {y : Ξ±} : x = plift.up y ↔ x.down = y := equiv.plift.eq_symm_apply lemma function.injective.map_swap {Ξ± Ξ² : Type*} [decidable_eq Ξ±] [decidable_eq Ξ²] {f : Ξ± β†’ Ξ²} (hf : function.injective f) (x y z : Ξ±) : f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) := begin conv_rhs { rw equiv.swap_apply_def }, split_ifs with h₁ hβ‚‚, { rw [hf h₁, equiv.swap_apply_left] }, { rw [hf hβ‚‚, equiv.swap_apply_right] }, { rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) hβ‚‚)] } end namespace equiv section variables (P : Ξ± β†’ Sort w) (e : Ξ± ≃ Ξ²) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def Pi_congr_left' : (Ξ  a, P a) ≃ (Ξ  b, P (e.symm b)) := { to_fun := Ξ» f x, f (e.symm x), inv_fun := Ξ» f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := Ξ» f, funext $ Ξ» x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := Ξ» f, funext $ Ξ» x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } end section variables (P : Ξ² β†’ Sort w) (e : Ξ± ≃ Ξ²) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Ξ  a, P (e a)) ≃ (Ξ  b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : Ξ± β†’ Sort w} {Z : Ξ² β†’ Sort z} (h₁ : Ξ± ≃ Ξ²) (hβ‚‚ : Ξ  a : Ξ±, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def Pi_congr : (Ξ  a, W a) ≃ (Ξ  b, Z b) := (equiv.Pi_congr_right hβ‚‚).trans (equiv.Pi_congr_left _ h₁) @[simp] lemma coe_Pi_congr_symm : ((h₁.Pi_congr hβ‚‚).symm : (Ξ  b, Z b) β†’ (Ξ  a, W a)) = Ξ» f a, (hβ‚‚ a).symm (f (h₁ a)) := rfl lemma Pi_congr_symm_apply (f : Ξ  b, Z b) : (h₁.Pi_congr hβ‚‚).symm f = Ξ» a, (hβ‚‚ a).symm (f (h₁ a)) := rfl @[simp] lemma Pi_congr_apply_apply (f : Ξ  a, W a) (a : Ξ±) : h₁.Pi_congr hβ‚‚ f (h₁ a) = hβ‚‚ a (f a) := begin change cast _ ((hβ‚‚ (h₁.symm (h₁ a))) (f (h₁.symm (h₁ a)))) = (hβ‚‚ a) (f a), generalize_proofs hZa, revert hZa, rw h₁.symm_apply_apply a, simp, end end section variables {W : Ξ± β†’ Sort w} {Z : Ξ² β†’ Sort z} (h₁ : Ξ± ≃ Ξ²) (hβ‚‚ : Ξ  b : Ξ², (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Ξ  a, W a) ≃ (Ξ  b, Z b) := (Pi_congr h₁.symm (Ξ» b, (hβ‚‚ b).symm)).symm @[simp] lemma coe_Pi_congr' : (h₁.Pi_congr' hβ‚‚ : (Ξ  a, W a) β†’ (Ξ  b, Z b)) = Ξ» f b, hβ‚‚ b $ f $ h₁.symm b := rfl lemma Pi_congr'_apply (f : Ξ  a, W a) : h₁.Pi_congr' hβ‚‚ f = Ξ» b, hβ‚‚ b $ f $ h₁.symm b := rfl @[simp] lemma Pi_congr'_symm_apply_symm_apply (f : Ξ  b, Z b) (b : Ξ²) : (h₁.Pi_congr' hβ‚‚).symm f (h₁.symm b) = (hβ‚‚ b).symm (f b) := begin change cast _ ((hβ‚‚ (h₁ (h₁.symm b))).symm (f (h₁ (h₁.symm b)))) = (hβ‚‚ b).symm (f b), generalize_proofs hWb, revert hWb, generalize hb : h₁ (h₁.symm b) = b', rw h₁.apply_symm_apply b at hb, subst hb, simp, end end section binary_op variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ β†’ α₁ β†’ α₁) lemma semiconj_conj (f : α₁ β†’ α₁) : semiconj e f (e.conj f) := Ξ» x, by simp lemma semiconjβ‚‚_conj : semiconjβ‚‚ e f (e.arrow_congr e.conj f) := Ξ» x y, by simp instance [is_associative α₁ f] : is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconjβ‚‚_conj f).is_associative_right e.surjective instance [is_idempotent α₁ f] : is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconjβ‚‚_conj f).is_idempotent_right e.surjective instance [is_left_cancel α₁ f] : is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ Ξ» x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩ instance [is_right_cancel α₁ f] : is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ Ξ» x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩ end binary_op end equiv lemma function.injective.swap_apply [decidable_eq Ξ±] [decidable_eq Ξ²] {f : Ξ± β†’ Ξ²} (hf : function.injective f) (x y z : Ξ±) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := begin by_cases hx : z = x, by simp [hx], by_cases hy : z = y, by simp [hy], rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] end lemma function.injective.swap_comp [decidable_eq Ξ±] [decidable_eq Ξ²] {f : Ξ± β†’ Ξ²} (hf : function.injective f) (x y : Ξ±) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := funext $ Ξ» z, hf.swap_apply _ _ _ /-- If `Ξ±` is a subsingleton, then it is equivalent to `Ξ± Γ— Ξ±`. -/ def subsingleton_prod_self_equiv {Ξ± : Type*} [subsingleton Ξ±] : Ξ± Γ— Ξ± ≃ Ξ± := { to_fun := Ξ» p, p.1, inv_fun := Ξ» a, (a, a), left_inv := Ξ» p, subsingleton.elim _ _, right_inv := Ξ» p, subsingleton.elim _ _, } /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton Ξ±] [subsingleton Ξ²] (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ±) : Ξ± ≃ Ξ² := { to_fun := f, inv_fun := g, left_inv := Ξ» _, subsingleton.elim _ _, right_inv := Ξ» _, subsingleton.elim _ _ } /-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/ noncomputable def equiv.punit_of_nonempty_of_subsingleton {Ξ± : Sort*} [h : nonempty Ξ±] [subsingleton Ξ±] : Ξ± ≃ punit.{v} := equiv_of_subsingleton_of_subsingleton (Ξ» _, punit.star) (Ξ» _, h.some) /-- `unique (unique Ξ±)` is equivalent to `unique Ξ±`. -/ def unique_unique_equiv : unique (unique Ξ±) ≃ unique Ξ± := equiv_of_subsingleton_of_subsingleton (Ξ» h, h.default) (Ξ» h, { default := h, uniq := Ξ» _, subsingleton.elim _ _ }) namespace function lemma update_comp_equiv {Ξ± Ξ² Ξ±' : Sort*} [decidable_eq Ξ±'] [decidable_eq Ξ±] (f : Ξ± β†’ Ξ²) (g : Ξ±' ≃ Ξ±) (a : Ξ±) (v : Ξ²) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply] lemma update_apply_equiv_apply {Ξ± Ξ² Ξ±' : Sort*} [decidable_eq Ξ±'] [decidable_eq Ξ±] (f : Ξ± β†’ Ξ²) (g : Ξ±' ≃ Ξ±) (a : Ξ±) (v : Ξ²) (a' : Ξ±') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' lemma Pi_congr_left'_update [decidable_eq Ξ±] [decidable_eq Ξ²] (P : Ξ± β†’ Sort*) (e : Ξ± ≃ Ξ²) (f : Ξ  a, P a) (b : Ξ²) (x : P (e.symm b)) : e.Pi_congr_left' P (update f (e.symm b) x) = update (e.Pi_congr_left' P f) b x := begin ext b', rcases eq_or_ne b' b with rfl | h, { simp, }, { simp [h], }, end lemma Pi_congr_left'_symm_update [decidable_eq Ξ±] [decidable_eq Ξ²] (P : Ξ± β†’ Sort*) (e : Ξ± ≃ Ξ²) (f : Ξ  b, P (e.symm b)) (b : Ξ²) (x : P (e.symm b)) : (e.Pi_congr_left' P).symm (update f b x) = update ((e.Pi_congr_left' P).symm f) (e.symm b) x := by simp [(e.Pi_congr_left' P).symm_apply_eq, Pi_congr_left'_update] end function
91093ff78089f8ea500caaa5971365657527df73
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Compiler/IR/ResetReuse.lean
786bd9d5d05aff7bc9b8ac620f3ee2b59c2fb912
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
6,218
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.Compiler.IR.Basic import Lean.Compiler.IR.LiveVars import Lean.Compiler.IR.Format namespace Lean.IR.ResetReuse /- Remark: the insertResetReuse transformation is applied before we have inserted `inc/dec` instructions, and perfomed lower level optimizations that introduce the instructions `release` and `set`. -/ /- Remark: the functions `S`, `D` and `R` defined here implement the corresponding functions in the paper "Counting Immutable Beans" Here are the main differences: - We use the State monad to manage the generation of fresh variable names. - Support for join points, and `uset` and `sset` instructions for unboxed data. - `D` uses the auxiliary function `Dmain`. - `Dmain` returns a pair `(b, found)` to avoid quadratic behavior when checking the last occurrence of the variable `x`. - Because we have join points in the actual implementation, a variable may be live even if it does not occur in a function body. See example at `livevars.lean`. -/ private def mayReuse (c₁ cβ‚‚ : CtorInfo) : Bool := c₁.size == cβ‚‚.size && c₁.usize == cβ‚‚.usize && c₁.ssize == cβ‚‚.ssize && /- The following condition is a heuristic. We don't want to reuse cells from different types even when they are compatible because it produces counterintuitive behavior. -/ c₁.name.getPrefix == cβ‚‚.name.getPrefix private partial def S (w : VarId) (c : CtorInfo) : FnBody β†’ FnBody | FnBody.vdecl x t v@(Expr.ctor c' ys) b => if mayReuse c c' then let updtCidx := c.cidx != c'.cidx FnBody.vdecl x t (Expr.reuse w c' updtCidx ys) b else FnBody.vdecl x t v (S w c b) | FnBody.jdecl j ys v b => let v' := S w c v if v == v' then FnBody.jdecl j ys v (S w c b) else FnBody.jdecl j ys v' b | FnBody.case tid x xType alts => FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody (S w c) | b => if b.isTerminal then b else let (instr, b) := b.split instr.setBody (S w c b) /- We use `Context` to track join points in scope. -/ abbrev M := ReaderT LocalContext (StateT Index Id) private def mkFresh : M VarId := do let idx ← getModify (fun n => n + 1) pure { idx := idx } private def tryS (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := do let w ← mkFresh let b' := S w c b if b == b' then pure b else pure $ FnBody.vdecl w IRType.object (Expr.reset c.size x) b' private def Dfinalize (x : VarId) (c : CtorInfo) : FnBody Γ— Bool β†’ M FnBody | (b, true) => pure b | (b, false) => tryS x c b private def argsContainsVar (ys : Array Arg) (x : VarId) : Bool := ys.any fun arg => match arg with | Arg.var y => x == y | _ => false private def isCtorUsing (b : FnBody) (x : VarId) : Bool := match b with | (FnBody.vdecl _ _ (Expr.ctor _ ys) _) => argsContainsVar ys x | _ => false /- Given `Dmain b`, the resulting pair `(new_b, flag)` contains the new body `new_b`, and `flag == true` if `x` is live in `b`. Note that, in the function `D` defined in the paper, for each `let x := e; F`, `D` checks whether `x` is live in `F` or not. This is great for clarity but it is expensive: `O(n^2)` where `n` is the size of the function body. -/ private partial def Dmain (x : VarId) (c : CtorInfo) : FnBody β†’ M (FnBody Γ— Bool) | e@(FnBody.case tid y yType alts) => do let ctx ← read if e.hasLiveVar ctx x then do /- If `x` is live in `e`, we recursively process each branch. -/ let alts ← alts.mapM fun alt => alt.mmodifyBody fun b => Dmain x c b >>= Dfinalize x c pure (FnBody.case tid y yType alts, true) else pure (e, false) | FnBody.jdecl j ys v b => do let (b, found) ← withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b) let (v, _ /- found' -/) ← Dmain x c v /- If `found' == true`, then `Dmain b` must also have returned `(b, true)` since we assume the IR does not have dead join points. So, if `x` is live in `j` (i.e., `v`), then it must also live in `b` since `j` is reachable from `b` with a `jmp`. On the other hand, `x` may be live in `b` but dead in `j` (i.e., `v`). -/ pure (FnBody.jdecl j ys v b, found) | e => do let ctx ← read if e.isTerminal then pure (e, e.hasLiveVar ctx x) else do let (instr, b) := e.split if isCtorUsing instr x then /- If the scrutinee `x` (the one that is providing memory) is being stored in a constructor, then reuse will probably not be able to reuse memory at runtime. It may work only if the new cell is consumed, but we ignore this case. -/ pure (e, true) else let (b, found) ← Dmain x c b /- Remark: it is fine to use `hasFreeVar` instead of `hasLiveVar` since `instr` is not a `FnBody.jmp` (it is not a terminal) nor it is a `FnBody.jdecl`. -/ if found || !instr.hasFreeVar x then pure (instr.setBody b, found) else let b ← tryS x c b pure (instr.setBody b, true) private def D (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := Dmain x c b >>= Dfinalize x c partial def R : FnBody β†’ M FnBody | FnBody.case tid x xType alts => do let alts ← alts.mapM fun alt => do let alt ← alt.mmodifyBody R match alt with | Alt.ctor c b => if c.isScalar then pure alt else Alt.ctor c <$> D x c b | _ => pure alt pure $ FnBody.case tid x xType alts | FnBody.jdecl j ys v b => do let v ← R v let b ← withReader (fun ctx => ctx.addJP j ys v) (R b) pure $ FnBody.jdecl j ys v b | e => do if e.isTerminal then pure e else do let (instr, b) := e.split let b ← R b pure (instr.setBody b) end ResetReuse open ResetReuse def Decl.insertResetReuse (d : Decl) : Decl := match d with | Decl.fdecl (body := b) ..=> let nextIndex := d.maxIndex + 1 let bNew := (R b {}).run' nextIndex d.updateBody! bNew | other => other end Lean.IR
7e1b9d0e6a564fba382e9f1b9eb973713164b8e6
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/ext.lean
786807ca590398cb80c4135245d839d40177b3ee
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
19,990
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Jesse Michael Han -/ import tactic.rcases import logic.function.basic universes u₁ uβ‚‚ open interactive interactive.types section ext open lean.parser nat tactic declare_trace ext /-- `derive_struct_ext_lemma n` generates two extensionality lemmas based on the equality of all non-propositional projections. On the following: ```lean @[ext] structure foo (Ξ± : Type*) := (x y : β„•) (z : {z // z < x}) (k : Ξ±) (h : x < y) ``` `derive_struct_lemma` generates: ```lean lemma foo.ext : βˆ€ {Ξ± : Type u_1} (x y : foo Ξ±), x.x = y.x β†’ x.y = y.y β†’ x.z == y.z β†’ x.k = y.k β†’ x = y lemma foo.ext_iff : βˆ€ {Ξ± : Type u_1} (x y : foo Ξ±), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ meta def derive_struct_ext_lemma (n : name) : tactic name := do e ← get_env, fs ← e.structure_fields n, d ← get_decl n, n ← resolve_constant n, let r := @expr.const tt n $ d.univ_params.map level.param, (args,_) ← infer_type r >>= open_pis, let args := args.map expr.to_implicit_local_const, let t := r.mk_app args, x ← mk_local_def `x t, y ← mk_local_def `y t, let args_x := args ++ [x], let args_y := args ++ [y], bs ← fs.mmap $ Ξ» f, do { d ← get_decl (n ++ f), let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param, t ← infer_type a, s ← infer_type t, if s β‰  `(Prop) then do let x := a.mk_app args_x, let y := a.mk_app args_y, t ← infer_type x, t' ← infer_type y, some <$> if t = t' then mk_app `eq [x,y] >>= mk_local_def `h else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h else pure none }, let bs := bs.filter_map id, eq_t ← mk_app `eq [x,y], t ← pis (args ++ [x,y] ++ bs) eq_t, pr ← run_async $ do { (_,pr) ← solve_aux t (do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, bs.mmap' (Ξ» _, do e ← intro1, cases e), reflexivity }), instantiate_mvars pr }, let decl_n := n <.> "ext", add_decl (declaration.thm decl_n d.univ_params t pr), bs ← bs.mmap infer_type, let rhs := expr.mk_and_lst bs, iff_t ← mk_app `iff [eq_t,rhs], t ← pis (args ++ [x,y]) iff_t, pr ← run_async $ do { (_,pr) ← solve_aux t $ do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, split, solve1 $ do { h ← intro1, hs ← injection h, subst_vars, repeat (refine ``( and.intro _ _ ) >> reflexivity ), done <|> reflexivity }, solve1 $ do { repeat (do refine ``(and_imp.mpr _), h ← intro1, cases h, skip ), h ← intro1, cases h, reflexivity } }, instantiate_mvars pr }, add_decl (declaration.thm (n <.> "ext_iff") d.univ_params t pr), pure decl_n meta def get_ext_subject : expr β†’ tactic name | (expr.pi n bi d b) := do v ← mk_local' n bi d, b' ← whnf $ b.instantiate_var v, get_ext_subject b' | (expr.app _ e) := do t ← infer_type e >>= instantiate_mvars >>= head_beta, if t.get_app_fn.is_constant then pure $ t.get_app_fn.const_name else if t.is_pi then pure $ name.mk_numeral 0 name.anonymous else if t.is_sort then pure $ name.mk_numeral 1 name.anonymous else do t ← pp t, fail format!"only constants and Pi types are supported: {t}" | e := fail format!"Only expressions of the form `_ β†’ _ β†’ ... β†’ R ... e are supported: {e}" open native meta def saturate_fun : name β†’ tactic expr | (name.mk_numeral 0 name.anonymous) := do vβ‚€ ← mk_mvar, v₁ ← mk_mvar, return $ vβ‚€.imp v₁ | (name.mk_numeral 1 name.anonymous) := do u ← mk_meta_univ, pure $ expr.sort u | n := do e ← resolve_constant n >>= mk_const, a ← get_arity e, e.mk_app <$> (list.iota a).mmap (Ξ» _, mk_mvar) meta def equiv_type_constr (n n' : name) : tactic unit := do e ← saturate_fun n, e' ← saturate_fun n', unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types" section performance_hack /-- For performance reasons, it is inadvisable to use `user_attribute.get_param`. The parameter is stored as a reflected expression. When calling `get_param`, the stored parameter is evaluated using `eval_expr`, which first compiles the expression into VM bytecode. The unevaluated expression is available using `user_attribute.get_param_untyped`. In particular, `user_attribute.get_param` MUST NEVER BE USED in the implementation of an attribute cache. This is because calling `eval_expr` disables the attribute cache. There are several possible workarounds: 1. Set a different attribute depending on the parameter. 2. Use your own evaluation function instead of `eval_expr`, such as e.g. `expr.to_nat`. 3. Write your own `has_reflect Param` instance (using a more efficient serialization format). The `user_attribute` code unfortunately checks whether the expression has the correct type, but you can use `` `(id %%e : Param) `` to pretend that your expression `e` has type `Param`. -/ library_note "user attribute parameters" /-! For performance reasons, the parameters of the `@[ext]` attribute are stored in two auxiliary attributes: ```lean attribute [ext thunk] funext -- is turned into attribute [_ext_core (@id name @funext)] thunk attribute [_ext_lemma_core] funext ``` see Note [user attribute parameters] -/ local attribute [semireducible] reflected local attribute [instance, priority 9000] private meta def hacky_name_reflect : has_reflect name := Ξ» n, `(id %%(expr.const n []) : name) @[user_attribute] private meta def ext_attr_core : user_attribute (name_map name) name := { name := `_ext_core, descr := "(internal attribute used by ext)", cache_cfg := { dependencies := [], mk_cache := Ξ» ns, ns.mfoldl (Ξ» m n, do ext_l ← ext_attr_core.get_param_untyped n, pure (m.insert n ext_l.app_arg.const_name)) mk_name_map }, parser := failure } end performance_hack /-- Private attribute used to tag extensionality lemmas. -/ @[user_attribute] private meta def ext_lemma_attr_core : user_attribute := { name := `_ext_lemma_core, descr := "(internal attribute used by ext)", parser := failure } /-- Returns the extensionality lemmas in the environment, as a map from structure name to lemma name. -/ meta def get_ext_lemmas : tactic (name_map name) := ext_attr_core.get_cache /-- Returns the extensionality lemmas in the environment, as a list of lemma names. -/ meta def get_ext_lemma_names : tactic (list name) := attribute.get_instances ext_lemma_attr_core.name /-- Marks `lem` as an extensionality lemma corresponding to type constructor `constr`; if `persistent` is true then this is a global attribute, else local. -/ meta def add_ext_lemma (constr lem : name) (persistent : bool) : tactic unit := ext_attr_core.set constr lem persistent >> ext_lemma_attr_core.set lem () persistent /-- Tag lemmas of the form: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : βˆ€ x, a.lookup x = b.lookup y) : a = b := ... ``` The attribute indexes extensionality lemma using the type of the objects (i.e. `my_collection`) which it gets from the statement of the lemma. In some cases, the same lemma can be used to state the extensionality of multiple types that are definitionally equivalent. ```lean attribute [ext thunk, ext stream] funext ``` Also, the following: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : βˆ€ x, a.lookup x = b.lookup y) : a = b := ... ``` is equivalent to ```lean @[ext my_collection] lemma my_collection.ext (a b : my_collection) (h : βˆ€ x, a.lookup x = b.lookup y) : a = b := ... ``` This allows us specify type synonyms along with the type that is referred to in the lemma statement. ```lean @[ext, ext my_type_synonym] lemma my_collection.ext (a b : my_collection) (h : βˆ€ x, a.lookup x = b.lookup y) : a = b := ... ``` The `ext` attribute can be applied to a structure to generate its extensionality lemmas: ```lean @[ext] structure foo (Ξ± : Type*) := (x y : β„•) (z : {z // z < x}) (k : Ξ±) (h : x < y) ``` will generate: ```lean @[ext] lemma foo.ext : βˆ€ {Ξ± : Type u_1} (x y : foo Ξ±), x.x = y.x β†’ x.y = y.y β†’ x.z == y.z β†’ x.k = y.k β†’ x = y lemma foo.ext_iff : βˆ€ {Ξ± : Type u_1} (x y : foo Ξ±), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute unit (option name) := { name := `ext, descr := "lemmas usable by `ext` tactic", parser := optional ident, before_unset := some $ Ξ» _ _, pure (), after_set := some $ Ξ» n _ b, do add ← extensional_attribute.get_param n, unset_attribute `ext n, e ← get_env, n ← if (e.structure_fields n).is_some then derive_struct_ext_lemma n else pure n, s ← mk_const n >>= infer_type >>= get_ext_subject, match add with | none := add_ext_lemma s n b | some add := equiv_type_constr s add >> add_ext_lemma add n b end } add_tactic_doc { name := "ext", category := doc_category.attr, decl_names := [`extensional_attribute], tags := ["rewrite", "logic"] } /-- When possible, `ext` lemmas are stated without a full set of arguments. As an example, for bundled homs `f`, `g`, and `of`, `f.comp of = g.comp of β†’ f = g` is a better `ext` lemma than `(βˆ€ x, f (of x) = g (of x)) β†’ f = g`, as the former allows a second type-specific extensionality lemmas to be applied to `f.comp of = g.comp of`. If the domain of `of` is `β„•` or `β„€` and `of` is a `ring_hom`, such a lemma could then make the goal `f (of 1) = g (of 1)`. For bundled morphisms, there is a `ext` lemma that always applies of the form `(βˆ€ x, ⇑f x = ⇑g x) β†’ f = g`. When adding type-specific `ext` lemmas like the one above, we want these to be tried first. This happens automatically since the type-specific lemmas are inevitably defined later. -/ library_note "partially-applied ext lemmas" -- We mark some existing extensionality lemmas. attribute [ext] array.ext propext function.hfunext attribute [ext thunk] _root_.funext -- This line is equivalent to: -- attribute [ext (β†’)] _root_.funext -- but (β†’) is not actually a binary relation with a constant at the head, -- so we use the special name [anon].0 to represent (β†’). run_cmd add_ext_lemma (name.mk_numeral 0 name.anonymous) ``_root_.funext tt -- We create some extensionality lemmas for existing structures. attribute [ext] ulift namespace plift -- This is stronger than the one generated automatically. @[ext] lemma ext {P : Prop} (a b : plift P) : a = b := begin cases a, cases b, refl end end plift -- Conservatively, we'll only add extensionality lemmas for `has_*` structures -- as they become useful. attribute [ext] has_zero @[ext] lemma unit.ext {x y : unit} : x = y := by { cases x, cases y, refl, } @[ext] lemma punit.ext {x y : punit} : x = y := by { cases x, cases y, refl, } namespace tactic /-- Helper structure for `ext` and `ext1`. `lemmas` keeps track of extensionality lemmas applied so far. -/ meta structure ext_state : Type := (patts : list rcases_patt := []) (trace_msg : list string := []) (fuel : option β„• := none) /-- Helper function for `try_intros`. Additionally populates the `trace_msg` field of `ext_state`. -/ private meta def try_intros_core : state_t ext_state tactic unit := do ⟨patts, trace_msg, fuel⟩ ← get, match patts with | [] := do { es ← state_t.lift intros, when (es.length > 0) $ do let msg := "intros " ++ (" ".intercalate (es.map (Ξ» e, e.local_pp_name.to_string))), modify (Ξ» ⟨patts, trace_msg, fuel⟩, ⟨patts, trace_msg ++ [msg], fuel⟩) } <|> pure () | (x::xs) := do tgt ← state_t.lift (target >>= whnf), when tgt.is_pi $ do state_t.lift (rintro [x]), msg ← state_t.lift (((++) "rintro ") <$> format.to_string <$> x.format ff), modify (Ξ» ⟨_, trace_msg, fuel⟩, ⟨xs, trace_msg ++ [msg], fuel⟩), try_intros_core end /-- Try to introduce as many arguments as possible, using the given patterns to destruct the introduced variables. Returns the unused patterns. -/ meta def try_intros (patts : list rcases_patt) : tactic (list rcases_patt) := let Οƒ := ext_state.mk patts [] none in (ext_state.patts ∘ prod.snd) <$> state_t.run try_intros_core Οƒ /-- Apply one extensionality lemma, and destruct the arguments using the patterns in the ext_state. -/ meta def ext1_core (cfg : apply_cfg := {}) : state_t ext_state tactic unit := do ⟨patts, trace_msg, _⟩ ← get, (new_msgs) ← state_t.lift $ focus1 $ do { m ← get_ext_lemmas, tgt ← target, when_tracing `ext $ trace!"[ext] goal: {tgt}", subject ← get_ext_subject tgt, new_trace_msg ← do { rule ← (m.find subject), if is_trace_enabled_for `ext then trace!"[ext] matched goal to rule: {rule}" >> timetac "[ext] application attempt time" (applyc rule cfg) else applyc rule cfg, pure (["apply " ++ rule.to_string]) } <|> do { ls ← get_ext_lemma_names, let nms := ls.map name.to_string, rule ← (ls.any_of (Ξ» n, (if is_trace_enabled_for `ext then trace!"[ext] trying to apply ext lemma: {n}" >> timetac "[ext] application attempt time" (applyc n cfg) else applyc n cfg) *> pure n)), pure (["apply " ++ rule.to_string]) } <|> (fail format!"no applicable extensionality rule found for {subject}"), pure new_trace_msg }, modify (Ξ» ⟨patts, trace_msg, fuel⟩, ⟨patts, trace_msg ++ new_msgs, fuel⟩), try_intros_core /-- Apply multiple extensionality lemmas, destructing the arguments using the given patterns. -/ meta def ext_core (cfg : apply_cfg := {}) : state_t ext_state tactic unit := do acc@⟨_, _, fuel⟩ ← get, match fuel with | (some 0) := pure () | n := do { ext1_core cfg, modify (Ξ» ⟨patts, lemmas, _⟩, ⟨patts, lemmas, nat.pred <$> n⟩), ext_core <|> pure () } end /-- Apply one extensionality lemma, and destruct the arguments using the given patterns. Returns the unused patterns. -/ meta def ext1 (xs : list rcases_patt) (cfg : apply_cfg := {}) (trace : bool := ff) : tactic (list rcases_patt) := do ⟨_, ΟƒβŸ© ← state_t.run (ext1_core cfg) {patts := xs}, when trace $ tactic.trace $ "Try this: " ++ ", ".intercalate Οƒ.trace_msg, pure Οƒ.patts /-- Apply multiple extensionality lemmas, destructing the arguments using the given patterns. `ext ps (some n)` applies at most `n` extensionality lemmas. Returns the unused patterns. -/ meta def ext (xs : list rcases_patt) (fuel : option β„•) (cfg : apply_cfg := {}) (trace : bool := ff): tactic (list rcases_patt) := do ⟨_, ΟƒβŸ© ← state_t.run (ext_core cfg) {patts := xs, fuel := fuel}, when trace $ tactic.trace $ "Try this: " ++ ", ".intercalate Οƒ.trace_msg, pure Οƒ.patts local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. Placing a `?` after `ext1` (e.g. `ext1? i ⟨a,b⟩ : 3`) will display a sequence of tactic applications that can replace the call to `ext1`. -/ meta def interactive.ext1 (trace : parse (tk "?")?) (xs : parse rcases_patt_parse_hi*) : tactic unit := ext1 xs {} trace.is_some $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. - `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. - Placing a `?` after `ext` (e.g. `ext? i ⟨a,b⟩ : 3`) will display a sequence of tactic applications that can replace the call to `ext`. - `set_option trace.ext true` will trace every attempted lemma application, along with the time it takes for the application to succeed or fail. This is useful for debugging slow `ext` calls. When trying to prove: ```lean Ξ± Ξ² : Type, f g : Ξ± β†’ set Ξ² ⊒ f = g ``` applying `ext x y` yields: ```lean Ξ± Ξ² : Type, f g : Ξ± β†’ set Ξ², x : Ξ±, y : Ξ² ⊒ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean Ξ± Ξ² Ξ³ : Type f g : Ξ± Γ— Ξ² β†’ Ξ³ ⊒ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean Ξ± Ξ² Ξ³ : Type, f g : Ξ± Γ— Ξ² β†’ Ξ³, a : Ξ±, b : Ξ² ⊒ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. In the previous example, applying `ext? ⟨a,b⟩` will produce the trace message: ```lean Try this: apply funext, rintro ⟨a, b⟩ ``` A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : (parse $ (tk "?")?) β†’ parse rcases_patt_parse_hi* β†’ parse (tk ":" *> small_nat)? β†’ tactic unit | trace [] (some n) := iterate_range 1 n (ext1 [] {} trace.is_some $> ()) | trace [] none := repeat1 (ext1 [] {} trace.is_some $> ()) | trace xs n := ext xs n {} trace.is_some $> () /-- * `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. * `ext` applies as many extensionality lemmas as possible; * `ext ids`, with `ids` a list of identifiers, finds extensionality lemmas and applies them until it runs out of identifiers in `ids` to name the local constants. * `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. - Placing a `?` after `ext`/`ext1` (e.g. `ext? i ⟨a,b⟩ : 3`) will display a sequence of tactic applications that can replace the call to `ext`/`ext1`. - `set_option trace.ext true` will trace every attempted lemma application, along with the time it takes for the application to succeed or fail. This is useful for debugging slow `ext` calls. When trying to prove: ```lean Ξ± Ξ² : Type, f g : Ξ± β†’ set Ξ² ⊒ f = g ``` applying `ext x y` yields: ```lean Ξ± Ξ² : Type, f g : Ξ± β†’ set Ξ², x : Ξ±, y : Ξ² ⊒ y ∈ f x ↔ y ∈ g x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean Ξ± Ξ² Ξ³ : Type f g : Ξ± Γ— Ξ² β†’ Ξ³ ⊒ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean Ξ± Ξ² Ξ³ : Type, f g : Ξ± Γ— Ξ² β†’ Ξ³, a : Ξ±, b : Ξ² ⊒ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. In the previous example, applying `ext? ⟨a,b⟩` will produce the trace message: ```lean Try this: apply funext, rintro ⟨a, b⟩ ``` A maximum depth can be provided with `ext x y z : 3`. -/ add_tactic_doc { name := "ext1 / ext", category := doc_category.tactic, decl_names := [`tactic.interactive.ext1, `tactic.interactive.ext], tags := ["rewriting", "logic"] } end tactic end ext
6a9f75ffdfb69ae98b63beba2389559f30798626
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/linear_recurrence.lean
c93768c5e72316399b8eb7f9e92a597f5b10843c
[ "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
8,232
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import data.polynomial.ring_division import linear_algebra.dimension import algebra.polynomial.big_operators /-! # Linear recurrence Informally, a "linear recurrence" is an assertion of the form `βˆ€ n : β„•, u (n + d) = a 0 * u n + a 1 * u (n+1) + ... + a (d-1) * u (n+d-1)`, where `u` is a sequence, `d` is the *order* of the recurrence and the `a i` are its *coefficients*. In this file, we define the structure `linear_recurrence` so that `linear_recurrence.mk d a` represents the above relation, and we call a sequence `u` which verifies it a *solution* of the linear recurrence. We prove a few basic lemmas about this concept, such as : * the space of solutions is a submodule of `(β„• β†’ Ξ±)` (i.e a vector space if `Ξ±` is a field) * the function that maps a solution `u` to its first `d` terms builds a `linear_equiv` between the solution space and `fin d β†’ Ξ±`, aka `Ξ± ^ d`. As a consequence, two solutions are equal if and only if their first `d` terms are equals. * a geometric sequence `q ^ n` is solution iff `q` is a root of a particular polynomial, which we call the *characteristic polynomial* of the recurrence Of course, although we can inductively generate solutions (cf `mk_sol`), the interesting part would be to determinate closed-forms for the solutions. This is currently *not implemented*, as we are waiting for definition and properties of eigenvalues and eigenvectors. -/ noncomputable theory open finset open_locale big_operators /-- A "linear recurrence relation" over a commutative semiring is given by its order `n` and `n` coefficients. -/ structure linear_recurrence (Ξ± : Type*) [comm_semiring Ξ±] := (order : β„•) (coeffs : fin order β†’ Ξ±) instance (Ξ± : Type*) [comm_semiring Ξ±] : inhabited (linear_recurrence Ξ±) := ⟨⟨0, default _⟩⟩ namespace linear_recurrence section comm_semiring variables {Ξ± : Type*} [comm_semiring Ξ±] (E : linear_recurrence Ξ±) /-- We say that a sequence `u` is solution of `linear_recurrence order coeffs` when we have `u (n + order) = βˆ‘ i : fin order, coeffs i * u (n + i)` for any `n`. -/ def is_solution (u : β„• β†’ Ξ±) := βˆ€ n, u (n + E.order) = βˆ‘ i, E.coeffs i * u (n + i) /-- A solution of a `linear_recurrence` which satisfies certain initial conditions. We will prove this is the only such solution. -/ def mk_sol (init : fin E.order β†’ Ξ±) : β„• β†’ Ξ± | n := if h : n < E.order then init ⟨n, h⟩ else βˆ‘ k : fin E.order, have n - E.order + k < n := begin rw [add_comm, ← nat.add_sub_assoc (not_lt.mp h), sub_lt_iff_left], { exact add_lt_add_right k.is_lt n }, { convert add_le_add (zero_le (k : β„•)) (not_lt.mp h), simp only [zero_add] } end, E.coeffs k * mk_sol (n - E.order + k) /-- `E.mk_sol` indeed gives solutions to `E`. -/ lemma is_sol_mk_sol (init : fin E.order β†’ Ξ±) : E.is_solution (E.mk_sol init) := Ξ» n, by rw mk_sol; simp /-- `E.mk_sol init`'s first `E.order` terms are `init`. -/ lemma mk_sol_eq_init (init : fin E.order β†’ Ξ±) : βˆ€ n : fin E.order, E.mk_sol init n = init n := Ξ» n, by { rw mk_sol, simp only [n.is_lt, dif_pos, fin.mk_coe, fin.eta] } /-- If `u` is a solution to `E` and `init` designates its first `E.order` values, then `βˆ€ n, u n = E.mk_sol init n`. -/ lemma eq_mk_of_is_sol_of_eq_init {u : β„• β†’ Ξ±} {init : fin E.order β†’ Ξ±} (h : E.is_solution u) (heq : βˆ€ n : fin E.order, u n = init n) : βˆ€ n, u n = E.mk_sol init n | n := if h' : n < E.order then by rw mk_sol; simp only [h', dif_pos]; exact_mod_cast heq ⟨n, h'⟩ else begin rw [mk_sol, ← nat.sub_add_cancel (le_of_not_lt h'), h (n-E.order)], simp [h'], congr' with k, exact have wf : n - E.order + k < n := begin rw [add_comm, ← nat.add_sub_assoc (not_lt.mp h'), sub_lt_iff_left], { exact add_lt_add_right k.is_lt n }, { convert add_le_add (zero_le (k : β„•)) (not_lt.mp h'), simp only [zero_add] } end, by rw eq_mk_of_is_sol_of_eq_init end /-- If `u` is a solution to `E` and `init` designates its first `E.order` values, then `u = E.mk_sol init`. This proves that `E.mk_sol init` is the only solution of `E` whose first `E.order` values are given by `init`. -/ lemma eq_mk_of_is_sol_of_eq_init' {u : β„• β†’ Ξ±} {init : fin E.order β†’ Ξ±} (h : E.is_solution u) (heq : βˆ€ n : fin E.order, u n = init n) : u = E.mk_sol init := funext (E.eq_mk_of_is_sol_of_eq_init h heq) /-- The space of solutions of `E`, as a `submodule` over `Ξ±` of the module `β„• β†’ Ξ±`. -/ def sol_space : submodule Ξ± (β„• β†’ Ξ±) := { carrier := {u | E.is_solution u}, zero_mem' := Ξ» n, by simp, add_mem' := Ξ» u v hu hv n, by simp [mul_add, sum_add_distrib, hu n, hv n], smul_mem' := Ξ» a u hu n, by simp [hu n, mul_sum]; congr'; ext; ac_refl } /-- Defining property of the solution space : `u` is a solution iff it belongs to the solution space. -/ lemma is_sol_iff_mem_sol_space (u : β„• β†’ Ξ±) : E.is_solution u ↔ u ∈ E.sol_space := iff.rfl /-- The function that maps a solution `u` of `E` to its first `E.order` terms as a `linear_equiv`. -/ def to_init : E.sol_space ≃ₗ[Ξ±] (fin E.order β†’ Ξ±) := { to_fun := Ξ» u x, (u : β„• β†’ Ξ±) x, map_add' := Ξ» u v, by { ext, simp }, map_smul' := Ξ» a u, by { ext, simp }, inv_fun := Ξ» u, ⟨E.mk_sol u, E.is_sol_mk_sol u⟩, left_inv := Ξ» u, by ext n; symmetry; apply E.eq_mk_of_is_sol_of_eq_init u.2; intros k; refl, right_inv := Ξ» u, function.funext_iff.mpr (Ξ» n, E.mk_sol_eq_init u n) } /-- Two solutions are equal iff they are equal on `range E.order`. -/ lemma sol_eq_of_eq_init (u v : β„• β†’ Ξ±) (hu : E.is_solution u) (hv : E.is_solution v) : u = v ↔ set.eq_on u v ↑(range E.order) := begin refine iff.intro (Ξ» h x hx, h β–Έ rfl) _, intro h, set u' : β†₯(E.sol_space) := ⟨u, hu⟩, set v' : β†₯(E.sol_space) := ⟨v, hv⟩, change u'.val = v'.val, suffices h' : u' = v', from h' β–Έ rfl, rw [← E.to_init.to_equiv.apply_eq_iff_eq, linear_equiv.coe_to_equiv], ext x, exact_mod_cast h (mem_range.mpr x.2) end /-! `E.tuple_succ` maps `![sβ‚€, s₁, ..., sβ‚™]` to `![s₁, ..., sβ‚™, βˆ‘ (E.coeffs i) * sα΅’]`, where `n := E.order`. This operation is quite useful for determining closed-form solutions of `E`. -/ /-- `E.tuple_succ` maps `![sβ‚€, s₁, ..., sβ‚™]` to `![s₁, ..., sβ‚™, βˆ‘ (E.coeffs i) * sα΅’]`, where `n := E.order`. -/ def tuple_succ : (fin E.order β†’ Ξ±) β†’β‚—[Ξ±] (fin E.order β†’ Ξ±) := { to_fun := Ξ» X i, if h : (i : β„•) + 1 < E.order then X ⟨i+1, h⟩ else (βˆ‘ i, E.coeffs i * X i), map_add' := Ξ» x y, begin ext i, split_ifs ; simp [h, mul_add, sum_add_distrib], end, map_smul' := Ξ» x y, begin ext i, split_ifs ; simp [h, mul_sum], exact sum_congr rfl (Ξ» x _, by ac_refl), end } end comm_semiring section field variables {Ξ± : Type*} [field Ξ±] (E : linear_recurrence Ξ±) /-- The dimension of `E.sol_space` is `E.order`. -/ lemma sol_space_dim : module.rank Ξ± E.sol_space = E.order := @dim_fin_fun Ξ± _ E.order β–Έ E.to_init.dim_eq end field section comm_ring variables {Ξ± : Type*} [comm_ring Ξ±] (E : linear_recurrence Ξ±) /-- The characteristic polynomial of `E` is `X ^ E.order - βˆ‘ i : fin E.order, (E.coeffs i) * X ^ i`. -/ def char_poly : polynomial Ξ± := polynomial.monomial E.order 1 - (βˆ‘ i : fin E.order, polynomial.monomial i (E.coeffs i)) /-- The geometric sequence `q^n` is a solution of `E` iff `q` is a root of `E`'s characteristic polynomial. -/ lemma geom_sol_iff_root_char_poly (q : Ξ±) : E.is_solution (Ξ» n, q^n) ↔ E.char_poly.is_root q := begin rw [char_poly, polynomial.is_root.def, polynomial.eval], simp only [polynomial.evalβ‚‚_finset_sum, one_mul, ring_hom.id_apply, polynomial.evalβ‚‚_monomial, polynomial.evalβ‚‚_sub], split, { intro h, simpa [sub_eq_zero] using h 0 }, { intros h n, simp only [pow_add, sub_eq_zero.mp h, mul_sum], exact sum_congr rfl (Ξ» _ _, by ring) } end end comm_ring end linear_recurrence
1f8ae2abb0d9be8bda68c35ff08610c11ad58b25
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Lean/Elab/Term.lean
29f6716459af94e4482d76f5b18cdd8522cd4f46
[ "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
73,282
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.ResolveName import Lean.Util.Sorry import Lean.Util.ReplaceExpr import Lean.Structure import Lean.Meta.ExprDefEq import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Meta.Tactic.Util import Lean.Hygiene import Lean.Util.RecDepth import Lean.Elab.Log import Lean.Elab.Level import Lean.Elab.Attributes import Lean.Elab.AutoBound import Lean.Elab.InfoTree import Lean.Elab.Open import Lean.Elab.SetOption namespace Lean.Elab.Term /- Set isDefEq configuration for the elaborator. Note that we enable all approximations but `quasiPatternApprox` In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration. The example: ``` def ex : StateT Ξ΄ (StateT Οƒ Id) Οƒ := monadLift (get : StateT Οƒ Id Οƒ) ``` demonstrates why it produces counterintuitive behavior. We have the `Monad-lift` application: ``` @monadLift ?m ?n ?c ?Ξ± (get : StateT Οƒ id Οƒ) : ?n ?Ξ± ``` It produces the following unification problem when we process the expected type: ``` ?n ?Ξ± =?= StateT Ξ΄ (StateT Οƒ id) Οƒ ==> (approximate using first-order unification) ?n := StateT Ξ΄ (StateT Οƒ id) ?Ξ± := Οƒ ``` Then, we need to solve: ``` ?m ?Ξ± =?= StateT Οƒ id Οƒ ==> instantiate metavars ?m Οƒ =?= StateT Οƒ id Οƒ ==> (approximate since it is a quasi-pattern unification constraint) ?m := fun Οƒ => StateT Οƒ id Οƒ ``` Note that the constraint is not a Milner pattern because Οƒ is in the local context of `?m`. We are ignoring the other possible solutions: ``` ?m := fun Οƒ' => StateT Οƒ id Οƒ ?m := fun Οƒ' => StateT Οƒ' id Οƒ ?m := fun Οƒ' => StateT Οƒ id Οƒ' ``` We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions). If we had use first-order unification, then we would have produced the right answer: `?m := StateT Οƒ id` Haskell would work on this example since it always uses first-order unification. -/ def setElabConfig (cfg : Meta.Config) : Meta.Config := { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false } structure Context where fileName : String fileMap : FileMap declName? : Option Name := none macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : Std.PArray Expr := {} /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where -- typeclass instance search | typeClass /- Similar to typeClass, but error messages are different. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) (ctx : SavedContext) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (ctx : SavedContext) instance : ToString SyntheticMVarKind where toString | SyntheticMVarKind.typeClass => "typeclass" | SyntheticMVarKind.coe .. => "coe" | SyntheticMVarKind.tactic .. => "tactic" | SyntheticMVarKind.postponed .. => "postponed" structure SyntheticMVarDecl where mvarId : MVarId stx : Syntax kind : SyntheticMVarKind inductive MVarErrorKind where | implicitArg (ctx : Expr) | hole | custom (msgData : MessageData) instance : ToString MVarErrorKind where toString | MVarErrorKind.implicitArg ctx => "implicitArg" | MVarErrorKind.hole => "hole" | MVarErrorKind.custom msg => "custom" structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId structure State where levelNames : List Name := [] syntheticMVars : List SyntheticMVarDecl := [] mvarErrorInfos : List MVarErrorInfo := [] messages : MessageLog := {} letRecsToLift : List LetRecToLift := [] infoState : InfoState := {} deriving Inhabited abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax β†’ Option Expr β†’ TermElabM Expr open Meta instance : Inhabited (TermElabM Ξ±) where default := throw arbitrary structure SavedState where meta : Meta.SavedState Β«elabΒ» : State deriving Inhabited protected def saveState : TermElabM SavedState := do pure { meta := (← Meta.saveState), Β«elabΒ» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do modify fun s => { s with infoState := infoState } instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (Ξ± : Type) := EStateM.Result Exception SavedState Ξ± instance [Inhabited Ξ±] : Inhabited (TermElabResult Ξ±) where default := EStateM.Result.ok arbitrary arbitrary def setMessageLog (messages : MessageLog) : TermElabM Unit := modify fun s => { s with messages := messages } def resetMessageLog : TermElabM Unit := setMessageLog {} def getMessageLog : TermElabM MessageLog := return (← get).messages /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ @[inline] def observing (x : TermElabM Ξ±) : TermElabM (TermElabResult Ξ±) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.ok e sNew) catch | ex@(Exception.error _ _) => let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.error ex sNew) | ex@(Exception.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ @[inline] def applyResult (result : TermElabResult Ξ±) : TermElabM Ξ± := match result with | EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM Ξ±) : TermElabM Ξ± := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the environment is at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. -/ def withoutModifyingElabMetaState (x : TermElabM Ξ±) : TermElabM Ξ± := do let s ← get let sMeta ← getThe Meta.State try x finally set s set sMeta def getLevelNames : TermElabM (List Name) := return (← get).levelNames def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) instance : MonadLog TermElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let ctx ← readThe Core.Context let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule @[inline] protected def withFreshMacroScope (x : TermElabM Ξ±) : TermElabM Ξ± := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation TermElabM where getCurrMacroScope := Term.getCurrMacroScope getMainModule := Term.getMainModule withFreshMacroScope := Term.withFreshMacroScope instance : MonadInfoTree TermElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[implementedBy mkTermElabAttributeUnsafe] constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) | getOp (ref : Syntax) (idx : Syntax) def LVal.getRef : LVal β†’ Syntax | LVal.fieldIdx ref _ => ref | LVal.fieldName ref .. => ref | LVal.getOp ref _ => ref def LVal.isFieldName : LVal β†’ Bool | LVal.fieldName .. => true | _ => false instance : ToString LVal where toString | LVal.fieldIdx _ i => toString i | LVal.fieldName _ n .. => n | LVal.getOp _ idx => "[" ++ toString idx ++ "]" def getDeclName? : TermElabM (Option Name) := return (← read).declName? def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val } def withDeclName (name : Name) (x : TermElabM Ξ±) : TermElabM Ξ± := withReader (fun ctx => { ctx with declName? := name }) x def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } def withLevelNames (levelNames : List Name) (x : TermElabM Ξ±) : TermElabM Ξ± := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved def withoutErrToSorry (x : TermElabM Ξ±) : TermElabM Ξ± := withReader (fun ctx => { ctx with errToSorry := false }) x /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← get).messages.hasErrors then throwError "Error(s)" @[inline] def traceAtCmdPos (cls : Name) (msg : Unit β†’ MessageData) : TermElabM Unit := withRef Syntax.missing $ trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM Ξ±) : TermElabM Ξ± := do let ctx ← read let ref ← getRef let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := ref, autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | EStateM.Result.error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM Ξ±) : TermElabM Ξ± := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos } def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM Ξ± := do if (← get).messages.hasErrors then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg : MessageData := "don't know how to synthesize placeholder" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do let s ← get let hasOtherErrors := s.messages.hasErrors let mut hasNewErrors := false let mut alreadyVisited : NameSet := {} for mvarErrorInfo in s.mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId let foundError ← withMVarContext mvarId do /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do mvarErrorInfo.logError extraMsg? pure true else pure false if foundError then hasNewErrors := true return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ @[inline] def withoutPostponing (x : TermElabM Ξ±) : TermElabM Ξ± := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are of the form `u_i` where `i >= nextParamIdx`. The method returns the updated expression and new `nextParamIdx`. Remark: we make sure the generated parameter names do not clash with the universes at `ctx.levelNames`. -/ def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr Γ— Nat) := do let mctx ← getMCtx let levelNames ← getLevelNames let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx setMCtx r.mctx pure (r.expr, r.nextParamIdx) /-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/ def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do let nextParamIdx ← get let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx set nextParamIdx pure e /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope $ MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax := return mkIdentFrom ref (← mkFreshBinderName) private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => match applicationTime? with | none => attrImpl.add declName attr.stx attr.kind | some applicationTime => if applicationTime == attrImpl.applicationTime then attrImpl.add declName attr.stx attr.kind /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM Ξ± := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e extraMsg @[inline] def withoutMacroStackAtErr (x : TermElabM Ξ±) : TermElabM Ξ± := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← isExprMVarAssigned instMVar) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError "failed to synthesize instance{indentExpr type}" register_builtin_option autoLift : Bool := { defValue := true descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed" } register_builtin_option maxCoeSize : Nat := { defValue := 16 descr := "maximum number of instances used to construct an automatic coercion" } def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions))) /- The coercion from `Ξ±` to `Thunk Ξ±` cannot be implemented using an instance because it would eagerly evaluate `e` -/ def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do match expectedType with | Expr.app (Expr.const ``Thunk u _) arg _ => if (← isDefEq eType arg) then pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e))) else pure none | _ => pure none /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (Ξ± : Sort u) (a : Ξ±) (Ξ² : Sort v) abbrev coe {Ξ± : Sort u} {Ξ² : Sort v} (a : Ξ±) [CoeT Ξ± a Ξ²] : Ξ² ``` -/ private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do if (← isDefEq expectedType eType) then return e else match (← tryCoeThunk? expectedType eType e) with | some r => return r | none => let u ← getLevel eType let v ← getLevel expectedType let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType] let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar] let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe eNew else -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe` -- after we syntheze `mvar` let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?) return mvarAux catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f? def isTypeApp? (type : Expr) : TermElabM (Option (Expr Γ— Expr)) := do let type ← withReducible $ whnf type match type with | Expr.app m Ξ± _ => pure (some ((← instantiateMVars m), (← instantiateMVars Ξ±))) | _ => pure none def synthesizeInst (type : Expr) : TermElabM Expr := do let type ← instantiateMVars type match (← trySynthInstance type) with | LOption.some val => pure val | LOption.undef => throwError "failed to synthesize instance{indentExpr type}" | LOption.none => throwError "failed to synthesize instance{indentExpr type}" def isMonadApp (type : Expr) : TermElabM Bool := do let some (m, _) ← isTypeApp? type | pure false return (← isMonad? m) |>.isSome /-- Try to coerce `a : Ξ±` into `m Ξ²` by first coercing `a : Ξ±` into ‡β`, and then using `pure`. The method is only applied if `Ξ±` is not monadic (e.g., `Nat β†’ IO Unit`), and the head symbol of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool β†’ ?m Nat`). The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y` since none of them is polymorphic ``` def f (x : Bool) : IO Bool := do let y ← if x == 0 then IO.println "hello"; true else false; !y ``` On the other hand, the following fails since `+` is polymorphic ``` def f (x : Bool) : IO Nat := do IO.prinln x x + x -- Error: failed to synthesize `Add (IO Nat)` ``` -/ private def tryPureCoe? (errorMsgHeader? : Option String) (m Ξ² Ξ± a : Expr) : TermElabM (Option Expr) := commitWhenSome? do let doIt : TermElabM (Option Expr) := do try let aNew ← tryCoe errorMsgHeader? Ξ² Ξ± a none let aNew ← mkPure m aNew pure (some aNew) catch _ => pure none forallTelescope Ξ± fun _ Ξ± => do if (← isMonadApp Ξ±) then pure none else if !Ξ±.getAppFn.isMVar then doIt else pure none /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n Ξ²`, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n Ξ²`, if `eType` is of the form `Ξ±`, but not `m Ξ±` 1 - Try to coerce ‡α` into ‡β`, and use `pure` to lift it to `n Ξ±`. It only works if `n` implements `Pure` If `eType` is of the form `m Ξ±`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we use ``` coeM {m : Type u β†’ Type v} {Ξ± Ξ² : Type u} [βˆ€ a, CoeT Ξ± a Ξ²] [Monad m] (x : m Ξ±) : m Ξ² ``` `n` must be a `Monad` to use this one. 2- If there is monad lift from `m` to `n` and we can unify `Ξ±` and `Ξ²`, we use ``` liftM : βˆ€ {m : Type u_1 β†’ Type u_2} {n : Type u_1 β†’ Type u_3} [self : MonadLiftT m n] {Ξ± : Type u_1}, m Ξ± β†’ n Ξ± ``` Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as ``` def g (x : Nat) : IO Nat := do IO.println x pure x def f {m} [MonadLiftT IO m] : m Nat := g 10 ``` 3- If there is a monad lif from `m` to `n` and a coercion from `Ξ±` to `Ξ²`, we use ``` liftCoeM {m : Type u β†’ Type v} {n : Type u β†’ Type w} {Ξ± Ξ² : Type u} [MonadLiftT m n] [βˆ€ a, CoeT Ξ± a Ξ²] [Monad n] (x : m Ξ±) : n Ξ² ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `Ξ±` to `Ξ²` for all values in `Ξ±`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?Ξ±`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {Ξ± m n} [MonadLiftT m n] {Ξ±} : Coe (m Ξ±) (n Ξ±) := ... ``` It is not applicable because TC would have to assign `?Ξ± := Nat`. On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do let expectedType ← instantiateMVars expectedType let eType ← instantiateMVars eType let throwMismatch {Ξ±} : TermElabM Ξ± := throwTypeMismatchError errorMsgHeader? expectedType eType e f? let tryCoeSimple : TermElabM Expr := tryCoe errorMsgHeader? expectedType eType e f? let some (n, Ξ²) ← isTypeApp? expectedType | tryCoeSimple let tryPureCoeAndSimple : TermElabM Expr := do if autoLift.get (← getOptions) then match (← tryPureCoe? errorMsgHeader? n Ξ² eType e) with | some eNew => pure eNew | none => tryCoeSimple else tryCoeSimple let some (m, Ξ±) ← isTypeApp? eType | tryPureCoeAndSimple if (← isDefEq m n) then let some monadInst ← isMonad? n | tryCoeSimple try expandCoe (← mkAppOptM ``coeM #[m, Ξ±, Ξ², none, monadInst, e]) catch _ => throwMismatch else if autoLift.get (← getOptions) then try -- Construct lift from `m` to `n` let monadLiftType ← mkAppM ``MonadLiftT #[m, n] let monadLiftVal ← synthesizeInst monadLiftType let u_1 ← getDecLevel Ξ± let u_2 ← getDecLevel eType let u_3 ← getDecLevel expectedType let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, Ξ±, e] let eNewType ← inferType eNew if (← isDefEq expectedType eNewType) then return eNew -- approach 2 worked else let some monadInst ← isMonad? n | tryCoeSimple let u ← getLevel Ξ± let v ← getLevel Ξ² let coeTInstType := Lean.mkForall `a BinderInfo.default Ξ± $ mkAppN (mkConst ``CoeT [u, v]) #[Ξ±, mkBVar 0, Ξ²] let coeTInstVal ← synthesizeInst coeTInstType let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, Ξ±, Ξ², monadLiftVal, coeTInstVal, monadInst, e]) let eNewType ← inferType eNew unless (← isDefEq expectedType eNewType) do throwMismatch return eNew -- approach 3 worked catch _ => /- If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`. Otherwise, we just try `tryCoe?`. -/ match (← isMonad? m) with | none => tryPureCoeAndSimple | some _ => tryCoeSimple else tryCoeSimple /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do match expectedType? with | none => pure e | some expectedType => if (← isDefEq eType expectedType) then pure e else tryLiftAndCoe errorMsgHeader? expectedType eType e f? /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr := match expectedType? with | none => pure e | _ => do let eType ← inferType e ensureHasTypeAux expectedType? eType e none errorMsgHeader? private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if e.getAppFn.isMVar then let e ← instantiateMVars e if e.getAppFn.isMVar then tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "{msg}, expected type must be known" let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone throwError "{msg}, expected type contains metavariables{indentExpr expectedType}" pure expectedType private def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry } def withSavedContext (savedCtx : SavedContext) (x : TermElabM Ξ±) : TermElabM Ξ± := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) x private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque let ctx ← read registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) pure mvar /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List TermElab β†’ TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => do try elabFn stx expectedType? catch ex => match ex with | Exception.error ref msg => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | Exception.internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then s.restore elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTerm stx expectedType? else throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let table := termElabAttribute.ext.getState (← getEnv) |>.table let k := stx.getKind match table.find? k with | some elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns | none => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {Ξ±} (a : Ξ±) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax β†’ Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $x:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $x:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(noImplicitLambda% $x:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($e : $type)) => true | _ => false def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := mkAnnotation `noImplicitLambda type def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : Ξ±} β†’ Ξ²` or `[a : Ξ±] β†’ Ξ²` and `blockImplicitLambda stx` is not true, else return `none`. -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then pure none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then pure none else let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType | _ => pure none | _ => pure none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | Exception.error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r pure r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c.binderInfo d fun fvar => do let type ← whnfForall (b.instantiate1 fvar) loop type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax β†’ TermElabM Expr | Syntax.missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do trace[Elab.step] "expected type: {expectedType?}, term\n{stx}" checkMaxHeartbeats "elaborator" withNestedTraces do let env ← getEnv let stxNew? ← catchInternalId unsupportedSyntaxExceptionId (do let newStx ← adaptMacro (getMacros env) stx; pure (some newStx)) (fun _ => pure none) match stxNew? with | some stxNew => withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone def addTermInfo (stx : Syntax) (e : Expr) : TermElabM Unit := do if (← getInfoState).enabled then pushInfoLeaf <| Info.ofTermInfo { lctx := (← getLCtx), expr := e, stx := stx } def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId def mkTermInfo (stx : Syntax) (e : Expr) : TermElabM (Sum Info MVarId) := do let isHole? : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId _ => match (← getSyntheticMVarDecl? mvarId) with | some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId | _ => return none | _ => pure none match (← isHole?) with | none => return Sum.inl <| Info.ofTermInfo { lctx := (← getLCtx), expr := e, stx := stx } | some mvarId => return Sum.inr mvarId /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx := stx, lctx := (← getLCtx) } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withInfoContext' (withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx) (mkTermInfo stx) def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM Ξ±) : TermElabM (Option Ξ±) := do let saved ← saveState modify fun s => { s with messages := {} } try let a ← x if (← get).messages.hasErrors then restoreState saved return none else modify fun s => { s with messages := saved.elab.messages ++ s.messages } return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax β†’ TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' $ elabTerm stx' expectedType? def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass pure mvar /- Relevant definitions: ``` class CoeSort (Ξ± : Sort u) (Ξ² : outParam (Sort v)) abbrev coeSort {Ξ± : Sort u} {Ξ² : Sort v} (a : Ξ±) [CoeSort Ξ± Ξ²] : Ξ² ``` -/ private def tryCoeSort (Ξ± : Expr) (a : Expr) : TermElabM Expr := do let Ξ² ← mkFreshTypeMVar let u ← getLevel Ξ± let v ← getLevel Ξ² let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[Ξ±, Ξ²] let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[Ξ±, Ξ², a, mvar] else throwError "type expected" catch | Exception.error _ msg => throwError "type expected\n{msg}" | _ => throwError "type expected" /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then pure e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then pure e else tryCoeSort eType e /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx $ ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM Ξ±) : TermElabM Ξ± := do let flag := autoBoundImplicitLocal.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM Ξ± := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM Ξ±) : TermElabM Ξ± := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k /-- Return `autoBoundImplicits ++ xs. This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autoBoundImplicits := (← read).autoBoundImplicits for auto in autoBoundImplicits do let localDecl ← getLocalDecl auto.fvarId! for x in xs do if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autoBoundImplicits.toArray ++ xs def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ Β·.mvarId)}" let mvarId := (← getMCtx).getDelayedRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (Β·.mvarId == mvarId) /- ======================================= Builtin elaboration functions ======================================= -/ @[builtinTermElab Β«propΒ»] def elabProp : TermElab := fun _ _ => return mkSort levelZero private def elabOptLevel (stx : Syntax) : TermElabM Level := if stx.isNone then pure levelZero else elabLevel stx[0] @[builtinTermElab Β«sortΒ»] def elabSort : TermElab := fun stx _ => return mkSort (← elabOptLevel stx[1]) @[builtinTermElab Β«typeΒ»] def elabTypeStx : TermElab := fun stx _ => return mkSort (mkLevelSucc (← elabOptLevel stx[1])) /- the method `resolveName` adds a completion point for it using the given expected type. Thus, we propagate the expected type if `stx[0]` is an identifier. It doesn't "hurt" if the identifier can be resolved because the expected type is not used in this case. Recall that if the name resolution fails a synthetic sorry is returned.-/ @[builtinTermElab Β«pipeCompletionΒ»] def elabPipeCompletion : TermElab := fun stx expectedType? => do let e ← elabTerm stx[0] none unless e.isSorry do addDotCompletionInfo stx e expectedType? throwErrorAt stx[1] "invalid field notation, identifier or numeral expected" @[builtinTermElab Β«completionΒ»] def elabCompletion : TermElab := fun stx expectedType? => do /- `ident.` is ambiguous in Lean, we may try to be completing a declaration name or access a "field". -/ if stx[0].isIdent then /- If we can elaborate the identifier successfully, we assume it a dot-completion. Otherwise, we treat it as identifier completion with a dangling `.`. Recall that the server falls back to identifier completion when dot-completion fails. -/ let s ← saveState try let e ← elabTerm stx[0] none addDotCompletionInfo stx e expectedType? catch _ => s.restore addCompletionInfo <| CompletionInfo.id stx stx[0].getId (danglingDot := true) (← getLCtx) expectedType? throwErrorAt stx[1] "invalid field notation, identifier or numeral expected" else elabPipeCompletion stx expectedType? @[builtinTermElab Β«holeΒ»] def elabHole : TermElab := fun stx expectedType? => do let mvar ← mkFreshExprMVar expectedType? registerMVarErrorHoleInfo mvar.mvarId! stx pure mvar @[builtinTermElab Β«syntheticHoleΒ»] def elabSyntheticHole : TermElab := fun stx expectedType? => do let arg := stx[1] let userName := if arg.isIdent then arg.getId else Name.anonymous let mkNewHole : Unit β†’ TermElabM Expr := fun _ => do let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque userName registerMVarErrorHoleInfo mvar.mvarId! stx pure mvar if userName.isAnonymous then mkNewHole () else let mctx ← getMCtx match mctx.findUserName? userName with | none => mkNewHole () | some mvarId => let mvar := mkMVar mvarId let mvarDecl ← getMVarDecl mvarId let lctx ← getLCtx if mvarDecl.lctx.isSubPrefixOf lctx then pure mvar else match mctx.getExprAssignment? mvarId with | some val => let val ← instantiateMVars val if mctx.isWellFormed lctx val then pure val else withLCtx mvarDecl.lctx mvarDecl.localInstances do throwError "synthetic hole has already been defined and assigned to value incompatible with the current context{indentExpr val}" | none => if mctx.isDelayedAssigned mvarId then -- We can try to improve this case if needed. throwError "synthetic hole has already beend defined and delayed assigned with an incompatible local context" else if lctx.isSubPrefixOf mvarDecl.lctx then let mvarNew ← mkNewHole () modifyMCtx fun mctx => mctx.assignExpr mvarId mvarNew pure mvarNew else throwError "synthetic hole has already been defined with an incompatible local context" private def mkTacticMVar (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque let mvarId := mvar.mvarId! let ref ← getRef let declName? ← getDeclName? registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic tacticCode (← saveContext) return mvar @[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar expectedType stx | none => throwError ("invalid 'by' tactic, expected type has not been provided") @[builtinTermElab noImplicitLambda] def elabNoImplicitLambda : TermElab := fun stx expectedType? => elabTerm stx[1] (mkNoImplicitLambdaAnnotation <$> expectedType?) def resolveLocalName (n : Name) : TermElabM (Option (Expr Γ— List String)) := do let lctx ← getLCtx let view := extractMacroScopes n let rec loop (n : Name) (projs : List String) := match lctx.findFromUserName? { view with name := n }.review with | some decl => some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => loop pre (s::projs) | _ => none return loop view.name [] /- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name Γ— List String)) (explicitLevels : List Level) : TermElabM (List (Expr Γ— List String)) := do candidates.foldlM (init := []) fun result (constName, projs) => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. let const ← mkConst constName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name Γ— List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr Γ— List String)) := do try if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (Β·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved catch ex => if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? throw ex where process (candidates : List (Name Γ— List String)) : TermElabM (List (Expr Γ— List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, fβ‚‚])` where `id` is an identifier for `v.head`, and `f₁` and `fβ‚‚` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr Γ— Syntax Γ— List Syntax)) := do match ident with | Syntax.ident info rawStr n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let (cSstr, fields) := fields.foldr (init := (rawStr, [])) fun field (restSstr, fs) => let fieldSstr := restSstr.takeRightWhile (Β· β‰  '.') ({ restSstr with stopPos := restSstr.stopPos - (fieldSstr.bsize + 1) }, (field, fieldSstr) :: fs) let mkIdentFromPos pos rawVal val := let info := match info with | SourceInfo.original .. => SourceInfo.original "".toSubstring pos "".toSubstring (pos + rawVal.bsize) | _ => SourceInfo.synthetic pos (pos + rawVal.bsize) Syntax.ident info rawVal val [] let id := match c with | Expr.const id _ _ => id | Expr.fvar id _ => id | _ => unreachable! let id := mkIdentFromPos (ident.getPos?.getD 0) cSstr id match info.getPos? with | none => return (c, id, fields.map fun (field, _) => mkIdentFrom ident (Name.mkSimple field)) | some pos => let mut pos := pos + cSstr.bsize + 1 let mut newFields := #[] for (field, fieldSstr) in fields do newFields := newFields.push <| mkIdentFromPos pos fieldSstr (Name.mkSimple field) pos := pos + fieldSstr.bsize + 1 return (c, id, newFields.toList) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => if withInfo then addTermInfo stx f pure (some f) | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" @[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ => throwError "invalid occurrence of `Β·` notation, it must be surrounded by parentheses (e.g. `(Β· + 1)`)" @[builtinTermElab strLit] def elabStrLit : TermElab := fun stx _ => do match stx.isStrLit? with | some val => pure $ mkStrLit val | none => throwIllFormedSyntax private def mkFreshTypeMVarFor (expectedType? : Option Expr) : TermElabM Expr := do let typeMVar ← mkFreshTypeMVar MetavarKind.synthetic match expectedType? with | some expectedType => discard <| isDefEq expectedType typeMVar | _ => pure () return typeMVar @[builtinTermElab numLit] def elabNumLit : TermElab := fun stx expectedType? => do let val ← match stx.isNatLit? with | some val => pure val | none => throwIllFormedSyntax let typeMVar ← mkFreshTypeMVarFor expectedType? let u ← getDecLevel typeMVar let mvar ← mkInstMVar (mkApp2 (Lean.mkConst ``OfNat [u]) typeMVar (mkNatLit val)) let r := mkApp3 (Lean.mkConst ``OfNat.ofNat [u]) typeMVar (mkNatLit val) mvar registerMVarErrorImplicitArgInfo mvar.mvarId! stx r return r @[builtinTermElab rawNatLit] def elabRawNatLit : TermElab := fun stx expectedType? => do match stx[1].isNatLit? with | some val => return mkNatLit val | none => throwIllFormedSyntax @[builtinTermElab scientificLit] def elabScientificLit : TermElab := fun stx expectedType? => do match stx.isScientificLit? with | none => throwIllFormedSyntax | some (m, sign, e) => let typeMVar ← mkFreshTypeMVarFor expectedType? let u ← getDecLevel typeMVar let mvar ← mkInstMVar (mkApp (Lean.mkConst ``OfScientific [u]) typeMVar) return mkApp5 (Lean.mkConst ``OfScientific.ofScientific [u]) typeMVar mvar (mkNatLit m) (toExpr sign) (mkNatLit e) @[builtinTermElab charLit] def elabCharLit : TermElab := fun stx _ => do match stx.isCharLit? with | some val => return mkApp (Lean.mkConst ``Char.ofNat) (mkNatLit val.toNat) | none => throwIllFormedSyntax @[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ => match stx[0].isNameLit? with | some val => pure $ toExpr val | none => throwIllFormedSyntax @[builtinTermElab doubleQuotedName] def elabDoubleQuotedName : TermElab := fun stx _ => do match stx[1].isNameLit? with | some val => toExpr (← resolveGlobalConstNoOverloadWithInfo stx[1] val) | none => throwIllFormedSyntax @[builtinTermElab typeOf] def elabTypeOf : TermElab := fun stx _ => do inferType (← elabTerm stx[1] none) @[builtinTermElab ensureTypeOf] def elabEnsureTypeOf : TermElab := fun stx expectedType? => match stx[2].isStrLit? with | none => throwIllFormedSyntax | some msg => do let refTerm ← elabTerm stx[1] none let refTermType ← inferType refTerm elabTermEnsuringType stx[3] refTermType (errorMsgHeader? := msg) @[builtinTermElab ensureExpectedType] def elabEnsureExpectedType : TermElab := fun stx expectedType? => match stx[1].isStrLit? with | none => throwIllFormedSyntax | some msg => elabTermEnsuringType stx[2] expectedType? (errorMsgHeader? := msg) @[builtinTermElab Β«openΒ»] def elabOpen : TermElab := fun stx expectedType? => do try pushScope let openDecls ← elabOpenDecl stx[1] withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do elabTerm stx[3] expectedType? finally popScope @[builtinTermElab Β«set_optionΒ»] def elabSetOption : TermElab := fun stx expectedType? => do let options ← Elab.elabSetOption stx[1] stx[2] withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do elabTerm stx[4] expectedType? private def mkSomeContext : Context := { fileName := "<TermElabM>" fileMap := arbitrary } @[inline] def TermElabM.run (x : TermElabM Ξ±) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (Ξ± Γ— State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM Ξ±) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM Ξ± := (Β·.1) <$> x.run ctx s @[inline] def TermElabM.toIO (x : TermElabM Ξ±) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (Ξ± Γ— Core.State Γ— Meta.State Γ— State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta pure (a, sCore, sMeta, s) instance [MetaEval Ξ±] : MetaEval (TermElabM Ξ±) where eval env opts x _ := let x : TermElabM Ξ± := do try x finally let s ← get s.messages.forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext unsafe def evalExpr (Ξ±) (typeName : Name) (value : Expr) : TermElabM Ξ± := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst Ξ± name private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : Std.HashSet (Level Γ— Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i]) throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0]) @[specialize] def withoutPostponingUniverseConstraints (x : TermElabM Ξ±) : TermElabM Ξ± := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr setPostponed postponed return a catch ex => setPostponed postponed throw ex end Term builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
5c0e3183e13a7f433f6109173b9c1e7e7b8e87f9
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/concrete_category/bundled_hom.lean
421d91fb74dedb81d9a6dd60f9bd82cf15bfdd5a
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
3,406
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yury Kudryashov -/ import category_theory.concrete_category.basic import category_theory.concrete_category.bundled /-! # Category instances for algebraic structures that use bundled homs. Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types, along with an `is_monoid_hom` typeclass), but the general trend is towards using bundled homs. This file provides a basic infrastructure to define concrete categories using bundled homs, and define forgetful functors between them. -/ universes u namespace category_theory variables {c : Type u β†’ Type u} (hom : Ξ  ⦃α Ξ² : Type u⦄ (IΞ± : c Ξ±) (IΞ² : c Ξ²), Type u) /-- Class for bundled homs. Note that the arguments order follows that of lemmas for `monoid_hom`. This way we can use `⟨@monoid_hom.to_fun, @monoid_hom.id ...⟩` in an instance. -/ structure bundled_hom := (to_fun : Ξ  {Ξ± Ξ² : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²), hom IΞ± IΞ² β†’ Ξ± β†’ Ξ²) (id : Ξ  {Ξ± : Type u} (I : c Ξ±), hom I I) (comp : Ξ  {Ξ± Ξ² Ξ³ : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²) (IΞ³ : c Ξ³), hom IΞ² IΞ³ β†’ hom IΞ± IΞ² β†’ hom IΞ± IΞ³) (hom_ext : βˆ€ {Ξ± Ξ² : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²), function.injective (to_fun IΞ± IΞ²) . obviously) (id_to_fun : βˆ€ {Ξ± : Type u} (I : c Ξ±), to_fun I I (id I) = _root_.id . obviously) (comp_to_fun : βˆ€ {Ξ± Ξ² Ξ³ : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²) (IΞ³ : c Ξ³) (f : hom IΞ± IΞ²) (g : hom IΞ² IΞ³), to_fun IΞ± IΞ³ (comp IΞ± IΞ² IΞ³ g f) = (to_fun IΞ² IΞ³ g) ∘ (to_fun IΞ± IΞ² f) . obviously) attribute [class] bundled_hom attribute [simp] bundled_hom.id_to_fun bundled_hom.comp_to_fun namespace bundled_hom variable [π’ž : bundled_hom hom] include π’ž /-- Every `@bundled_hom c _` defines a category with objects in `bundled c`. -/ instance : category (bundled c) := by refine { hom := Ξ» X Y, @hom X.1 Y.1 X.str Y.str, id := Ξ» X, @bundled_hom.id c hom π’ž X X.str, comp := Ξ» X Y Z f g, @bundled_hom.comp c hom π’ž X Y Z X.str Y.str Z.str g f, comp_id' := _, id_comp' := _, assoc' := _}; intros; apply π’ž.hom_ext; simp only [π’ž.id_to_fun, π’ž.comp_to_fun, function.left_id, function.right_id] /-- A category given by `bundled_hom` is a concrete category. -/ instance concrete_category : concrete_category (bundled c) := { forget := { obj := Ξ» X, X, map := Ξ» X Y f, π’ž.to_fun X.str Y.str f, map_id' := Ξ» X, π’ž.id_to_fun X.str, map_comp' := by intros; erw π’ž.comp_to_fun; refl }, forget_faithful := { injectivity' := by intros; apply π’ž.hom_ext } } variables {hom} local attribute [instance] concrete_category.has_coe_to_fun /-- A version of `has_forgetβ‚‚.mk'` for categories defined using `@bundled_hom`. -/ def mk_has_forgetβ‚‚ {d : Type u β†’ Type u} {hom_d : Ξ  ⦃α Ξ² : Type u⦄ (IΞ± : d Ξ±) (IΞ² : d Ξ²), Type u} [bundled_hom hom_d] (obj : Ξ  ⦃α⦄, c Ξ± β†’ d Ξ±) (map : Ξ  {X Y : bundled c}, (X ⟢ Y) β†’ ((bundled.map obj X) ⟢ (bundled.map obj Y))) (h_map : βˆ€ {X Y : bundled c} (f : X ⟢ Y), (map f : X β†’ Y) = f) : has_forgetβ‚‚ (bundled c) (bundled d) := has_forgetβ‚‚.mk' (bundled.map @obj) (Ξ» _, rfl) @map (by intros; apply heq_of_eq; apply h_map) end bundled_hom end category_theory
3214aa98b1534a71e7d6cc8ad88bfe279918b62e
54c9ed381c63410c9b6af3b0a1722c41152f037f
/Lib4/Mathlib.lean
57fbf606d1630e47a6470b32ac3dd9ddc5a2f0a9
[ "Apache-2.0" ]
permissive
dselsam/binport
0233f1aa961a77c4fc96f0dccc780d958c5efc6c
aef374df0e169e2c3f1dc911de240c076315805c
refs/heads/master
1,687,453,448,108
1,627,483,296,000
1,627,483,296,000
333,825,622
0
0
null
null
null
null
UTF-8
Lean
false
false
19
lean
import Mathlib.all
f3f1a6dd448f2391d85185bb3fefb628a26b6ed6
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/pretty_cases.lean
3a4db128e6e9d01c48086fc60c4af9f30165a9c4
[ "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,825
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.core /-! # `pretty_cases` tactic When using `induction` and `cases`, `pretty_cases` prints a `"Try this:"` advice that shows how to structure the proof with `case { ... }` commands. In the following example, we apply induction on a permutation assumption about lists. `pretty_cases` gives us a proof skeleton that explicit selects the branches and explicit names the new local constants: ```lean example {Ξ±} (xs ys : list Ξ±) (h : xs ~ ys) : true := begin induction h, pretty_cases, -- Try this: -- case list.perm.nil : -- { admit }, -- case list.perm.cons : h_x h_l₁ h_lβ‚‚ h_a h_ih -- { admit }, -- case list.perm.swap : h_x h_y h_l -- { admit }, -- case list.perm.trans : h_l₁ h_lβ‚‚ h_l₃ h_a h_a_1 h_ih_a h_ih_a_1 -- { admit }, end ``` ## Main definitions * `pretty_cases_advice` return `pretty_cases` advice without printing it * `pretty_cases` main tactic -/ namespace tactic /-- Query the proof goal and print the skeleton of a proof by cases. -/ meta def pretty_cases_advice : tactic string := retrieve $ do gs ← get_goals, cases ← gs.mmap $ Ξ» g, do { t : list name ← get_tag g, let vs := t.tail, let ⟨vs,ts⟩ := vs.span (Ξ» n, name.last_string n = "_arg"), set_goals [g], ls ← local_context, let m := native.rb_map.of_list $ (ls.map expr.local_uniq_name).zip (ls.map expr.local_pp_name), let vs := vs.map $ Ξ» v, (m.find v.get_prefix).get_or_else `_, let var_decls := string.intercalate " " $ vs.map to_string, let var_decls := if vs.empty then "" else " : " ++ var_decls, pure sformat!" case {ts.head}{var_decls}\n {{ admit }" }, let cases := string.intercalate ",\n" cases, pure sformat!"Try this:\n{cases}" namespace interactive /-- Query the proof goal and print the skeleton of a proof by cases. For example, let us consider the following proof: ```lean example {Ξ±} (xs ys : list Ξ±) (h : xs ~ ys) : true := begin induction h, pretty_cases, -- Try this: -- case list.perm.nil : -- { admit }, -- case list.perm.cons : h_x h_l₁ h_lβ‚‚ h_a h_ih -- { admit }, -- case list.perm.swap : h_x h_y h_l -- { admit }, -- case list.perm.trans : h_l₁ h_lβ‚‚ h_l₃ h_a h_a_1 h_ih_a h_ih_a_1 -- { admit }, end ``` The output helps the user layout the cases and rename the introduced variables. -/ meta def pretty_cases : tactic unit := pretty_cases_advice >>= trace add_tactic_doc { name := "pretty_cases", category := doc_category.tactic, decl_names := [``tactic.interactive.pretty_cases], tags := ["context management", "goal management"] } end interactive end tactic
12cf2e9a57d620b12dde9868eba10ee909ccd50e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Conv.lean
f974028bc0d6d29855b59cee161bdce794c9a446
[ "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
13,186
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Notation for operators defined at Prelude.lean -/ prelude import Init.NotationExtra namespace Lean.Parser.Tactic.Conv /-- `conv` is the syntax category for a "conv tactic", where "conv" is short for conversion. A conv tactic is a program which receives a target, printed as `| a`, and is tasked with coming up with some term `b` and a proof of `a = b`. It is mainly used for doing targeted term transformations, for example rewriting only on the left side of an equality. -/ declare_syntax_cat conv (behavior := both) syntax convSeq1Indented := sepBy1IndentSemicolon(conv) syntax convSeqBracketed := "{" withoutPosition(sepByIndentSemicolon(conv)) "}" -- Order is important: a missing `conv` proof should not be parsed as `{ <missing> }`, -- automatically closing goals syntax convSeq := convSeqBracketed <|> convSeq1Indented /-- The `*` occurrence list means to apply to all occurrences of the pattern. -/ syntax occsWildcard := "*" /-- A list `1 2 4` of occurrences means to apply to the first, second, and fourth occurrence of the pattern. -/ syntax occsIndexed := num+ /-- An occurrence specification, either `*` or a list of numbers. The default is `[1]`. -/ syntax occs := atomic("(" &"occs") " := " (occsWildcard <|> occsIndexed) ") " /-- `with_annotate_state stx t` annotates the lexical range of `stx : Syntax` with the initial and final state of running tactic `t`. -/ scoped syntax (name := withAnnotateState) "with_annotate_state " rawStx ppSpace conv : conv /-- `skip` does nothing. -/ syntax (name := skip) "skip" : conv /-- Traverses into the left subterm of a binary operator. (In general, for an `n`-ary operator, it traverses into the second to last argument.) -/ syntax (name := lhs) "lhs" : conv /-- Traverses into the right subterm of a binary operator. (In general, for an `n`-ary operator, it traverses into the last argument.) -/ syntax (name := rhs) "rhs" : conv /-- Reduces the target to Weak Head Normal Form. This reduces definitions in "head position" until a constructor is exposed. For example, `List.map f [a, b, c]` weak head normalizes to `f a :: List.map f [b, c]`. -/ syntax (name := whnf) "whnf" : conv /-- Expands let-declarations and let-variables. -/ syntax (name := zeta) "zeta" : conv /-- Puts term in normal form, this tactic is meant for debugging purposes only. -/ syntax (name := reduce) "reduce" : conv /-- Performs one step of "congruence", which takes a term and produces subgoals for all the function arguments. For example, if the target is `f x y` then `congr` produces two subgoals, one for `x` and one for `y`. -/ syntax (name := congr) "congr" : conv /-- * `arg i` traverses into the `i`'th argument of the target. For example if the target is `f a b c d` then `arg 1` traverses to `a` and `arg 3` traverses to `c`. * `arg @i` is the same as `arg i` but it counts all arguments instead of just the explicit arguments. -/ syntax (name := arg) "arg " "@"? num : conv /-- `ext x` traverses into a binder (a `fun x => e` or `βˆ€ x, e` expression) to target `e`, introducing name `x` in the process. -/ syntax (name := ext) "ext" (ppSpace colGt ident)* : conv /-- `change t'` replaces the target `t` with `t'`, assuming `t` and `t'` are definitionally equal. -/ syntax (name := change) "change " term : conv /-- `delta id1 id2 ...` unfolds all occurrences of `id1`, `id2`, ... in the target. Like the `delta` tactic, this ignores any definitional equations and uses primitive delta-reduction instead, which may result in leaking implementation details. Users should prefer `unfold` for unfolding definitions. -/ syntax (name := delta) "delta" (ppSpace colGt ident)+ : conv /-- * `unfold foo` unfolds all occurrences of `foo` in the target. * `unfold id1 id2 ...` is equivalent to `unfold id1; unfold id2; ...`. Like the `unfold` tactic, this uses equational lemmas for the chosen definition to rewrite the target. For recursive definitions, only one layer of unfolding is performed. -/ syntax (name := unfold) "unfold" (ppSpace colGt ident)+ : conv /-- * `pattern pat` traverses to the first subterm of the target that matches `pat`. * `pattern (occs := *) pat` traverses to every subterm of the target that matches `pat` which is not contained in another match of `pat`. It generates one subgoal for each matching subterm. * `pattern (occs := 1 2 4) pat` matches occurrences `1, 2, 4` of `pat` and produces three subgoals. Occurrences are numbered left to right from the outside in. Note that skipping an occurrence of `pat` will traverse inside that subexpression, which means it may find more matches and this can affect the numbering of subsequent pattern matches. For example, if we are searching for `f _` in `f (f a) = f b`: * `occs := 1 2` (and `occs := *`) returns `| f (f a)` and `| f b` * `occs := 2` returns `| f a` * `occs := 2 3` returns `| f a` and `| f b` * `occs := 1 3` is an error, because after skipping `f b` there is no third match. -/ syntax (name := pattern) "pattern " (occs)? term : conv /-- `rw [thm]` rewrites the target using `thm`. See the `rw` tactic for more information. -/ syntax (name := rewrite) "rewrite" (config)? rwRuleSeq : conv /-- `simp [thm]` performs simplification using `thm` and marked `@[simp]` lemmas. See the `simp` tactic for more information. -/ syntax (name := simp) "simp" (config)? (discharger)? (&" only")? (" [" withoutPosition((simpStar <|> simpErase <|> simpLemma),*) "]")? : conv /-- `dsimp` is the definitional simplifier in `conv`-mode. It differs from `simp` in that it only applies theorems that hold by reflexivity. Examples: ```lean example (a : Nat): (0 + 0) = a - a := by conv => lhs dsimp rw [← Nat.sub_self a] ``` -/ syntax (name := dsimp) "dsimp" (config)? (discharger)? (&" only")? (" [" withoutPosition((simpErase <|> simpLemma),*) "]")? : conv /-- `simp_match` simplifies match expressions. For example, ``` match [a, b] with | [] => 0 | hd :: tl => hd ``` simplifies to `a`. -/ syntax (name := simpMatch) "simp_match" : conv /-- Executes the given tactic block without converting `conv` goal into a regular goal. -/ syntax (name := nestedTacticCore) "tactic'" " => " tacticSeq : conv /-- Focuses, converts the `conv` goal `⊒ lhs` into a regular goal `⊒ lhs = rhs`, and then executes the given tactic block. -/ syntax (name := nestedTactic) "tactic" " => " tacticSeq : conv /-- Executes the given conv block without converting regular goal into a `conv` goal. -/ syntax (name := convTactic) "conv'" " => " convSeq : tactic /-- `{ convs }` runs the list of `convs` on the current target, and any subgoals that remain are trivially closed by `skip`. -/ syntax (name := nestedConv) convSeqBracketed : conv /-- `(convs)` runs the `convs` in sequence on the current list of targets. This is pure grouping with no added effects. -/ syntax (name := paren) "(" withoutPosition(convSeq) ")" : conv /-- `rfl` closes one conv goal "trivially", by using reflexivity (that is, no rewriting). -/ macro "rfl" : conv => `(conv| tactic => rfl) /-- `done` succeeds iff there are no goals remaining. -/ macro "done" : conv => `(conv| tactic' => done) /-- `trace_state` prints the current goal state. -/ macro "trace_state" : conv => `(conv| tactic' => trace_state) /-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/ macro (name := allGoals) tk:"all_goals " s:convSeq : conv => `(conv| tactic' => all_goals%$tk conv' => $s) /-- `any_goals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds. -/ macro (name := anyGoals) tk:"any_goals " s:convSeq : conv => `(conv| tactic' => any_goals%$tk conv' => $s) /-- * `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails. * `case tag x₁ ... xβ‚™ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. * `case tag₁ | tagβ‚‚ => tac` is equivalent to `(case tag₁ => tac); (case tagβ‚‚ => tac)`. -/ macro (name := case) tk:"case " args:sepBy1(caseArg, " | ") arr:" => " s:convSeq : conv => `(conv| tactic' => case%$tk $args|* =>%$arr conv' => ($s); all_goals rfl) /-- `case'` is similar to the `case tag => tac` tactic, but does not ensure the goal has been solved after applying `tac`, nor admits the goal if `tac` failed. Recall that `case` closes the goal using `sorry` when `tac` fails, and the tactic execution is not interrupted. -/ macro (name := case') tk:"case' " args:sepBy1(caseArg, " | ") arr:" => " s:convSeq : conv => `(conv| tactic' => case'%$tk $args|* =>%$arr conv' => $s) /-- `next => tac` focuses on the next goal and solves it using `tac`, or else fails. `next x₁ ... xβ‚™ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ macro "next" args:(ppSpace binderIdent)* " => " tac:convSeq : conv => `(conv| case _ $args* => $tac) /-- `focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it. Usually `Β· tac`, which enforces that the goal is closed by `tac`, should be preferred. -/ macro (name := focus) tk:"focus " s:convSeq : conv => `(conv| tactic' => focus%$tk conv' => $s) /-- `conv => cs` runs `cs` in sequence on the target `t`, resulting in `t'`, which becomes the new target subgoal. -/ syntax (name := convConvSeq) "conv" " => " convSeq : conv /-- `Β· conv` focuses on the main conv goal and tries to solve it using `s`. -/ macro dot:patternIgnore("Β·" <|> ".") s:convSeq : conv => `(conv| {%$dot ($s) }) /-- `fail_if_success t` fails if the tactic `t` succeeds. -/ macro (name := failIfSuccess) tk:"fail_if_success " s:convSeq : conv => `(conv| tactic' => fail_if_success%$tk conv' => $s) /-- `rw [rules]` applies the given list of rewrite rules to the target. See the `rw` tactic for more information. -/ macro "rw" c:(config)? s:rwRuleSeq : conv => `(conv| rewrite $[$c]? $s) /-- `erw [rules]` is a shorthand for `rw (config := { transparency := .default }) [rules]`. This does rewriting up to unfolding of regular definitions (by comparison to regular `rw` which only unfolds `@[reducible]` definitions). -/ macro "erw" s:rwRuleSeq : conv => `(conv| rw (config := { transparency := .default }) $s) /-- `args` traverses into all arguments. Synonym for `congr`. -/ macro "args" : conv => `(conv| congr) /-- `left` traverses into the left argument. Synonym for `lhs`. -/ macro "left" : conv => `(conv| lhs) /-- `right` traverses into the right argument. Synonym for `rhs`. -/ macro "right" : conv => `(conv| rhs) /-- `intro` traverses into binders. Synonym for `ext`. -/ macro "intro" xs:(ppSpace colGt ident)* : conv => `(conv| ext $xs*) syntax enterArg := ident <|> ("@"? num) /-- `enter [arg, ...]` is a compact way to describe a path to a subterm. It is a shorthand for other conv tactics as follows: * `enter [i]` is equivalent to `arg i`. * `enter [@i]` is equivalent to `arg @i`. * `enter [x]` (where `x` is an identifier) is equivalent to `ext x`. For example, given the target `f (g a (fun x => x b))`, `enter [1, 2, x, 1]` will traverse to the subterm `b`. -/ syntax "enter" " [" withoutPosition(enterArg,+) "]" : conv macro_rules | `(conv| enter [$i:num]) => `(conv| arg $i) | `(conv| enter [@$i]) => `(conv| arg @$i) | `(conv| enter [$id:ident]) => `(conv| ext $id) | `(conv| enter [$arg, $args,*]) => `(conv| (enter [$arg]; enter [$args,*])) /-- The `apply thm` conv tactic is the same as `apply thm` the tactic. There are no restrictions on `thm`, but strange results may occur if `thm` cannot be reasonably interpreted as proving one equality from a list of others. -/ -- TODO: error if non-conv subgoals? macro "apply " e:term : conv => `(conv| tactic => apply $e) /-- `first | conv | ...` runs each `conv` until one succeeds, or else fails. -/ syntax (name := first) "first " withPosition((ppDedent(ppLine) colGe "| " convSeq)+) : conv /-- `try tac` runs `tac` and succeeds even if `tac` failed. -/ macro "try " t:convSeq : conv => `(conv| first | $t | skip) macro:1 x:conv tk:" <;> " y:conv:0 : conv => `(conv| tactic' => (conv' => $x:conv) <;>%$tk (conv' => $y:conv)) /-- `repeat convs` runs the sequence `convs` repeatedly until it fails to apply. -/ syntax "repeat " convSeq : conv macro_rules | `(conv| repeat $seq) => `(conv| first | ($seq); repeat $seq | skip) /-- `conv => ...` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover.github.io/theorem_proving_in_lean4/conv.html> for more details. Basic forms: * `conv => cs` will rewrite the goal with conv tactics `cs`. * `conv at h => cs` will rewrite hypothesis `h`. * `conv in pat => cs` will rewrite the first subexpression matching `pat` (see `pattern`). -/ -- HACK: put this at the end so that references to `conv` above -- refer to the syntax category instead of this syntax syntax (name := conv) "conv" (" at " ident)? (" in " (occs)? term)? " => " convSeq : tactic end Lean.Parser.Tactic.Conv
11519c73c42fcb3f43d38c0e90f8816ba48b4fc4
865bfafdd5c31c148e891f22dba45be7ae8fe9c5
/move_to_lib.hlean
0e605e785f7249aa11d3db314c2b00ee6b3ba775
[ "Apache-2.0" ]
permissive
fpvandoorn/sequential_colimits
f0eaae8e87469c41e74bbac1ba32d1772ed0e7fa
e39c3bd2efc6dfb251d334cec8c76b6aa3947c31
refs/heads/master
1,590,752,488,347
1,511,385,696,000
1,511,385,754,000
43,088,713
0
0
null
1,443,123,449,000
1,443,123,449,000
null
UTF-8
Lean
false
false
6,061
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke -/ -- these definitions and theorems should be moved to the HoTT library import types.equiv cubical.pathover2 eq2 types.eq types.fin types.pointed2 open eq nat algebra is_equiv equiv function sigma is_trunc fin attribute tro_invo_tro [unfold 9] -- TODO: move /- replace proof of le_of_succ_le by this -/ definition le_step_left {n m : β„•} (H : succ n ≀ m) : n ≀ m := by induction H with H m H'; exact le_succ n; exact le.step H' /- TODO: make proof of le_succ_of_le simpler -/ definition nat.add_le_add_left2 {n m : β„•} (H : n ≀ m) (k : β„•) : k + n ≀ k + m := by induction H with m H Hβ‚‚; reflexivity; exact le.step Hβ‚‚ -- definition le_add_right2 (n k : β„•) : n ≀ n + k := -- by induction H with m H Hβ‚‚ -- example : le_add_right 0 = (Ξ»n, nat.zero_le (0+n)) := -- idp /- move this to types.eq -/ definition total_space_method2 {A : Type} (aβ‚€ : A) (code : A β†’ Type) (H : is_contr (Ξ£a, code a)) (cβ‚€ : code aβ‚€) (a : A) : (aβ‚€ = a) ≃ code a := total_space_method aβ‚€ code H (ap pr1 (center_eq ⟨aβ‚€, cβ‚€βŸ©)) a definition total_space_method2_refl {A : Type} (aβ‚€ : A) (code : A β†’ Type) (H : is_contr (Ξ£a, code a)) (cβ‚€ : code aβ‚€) : total_space_method2 aβ‚€ code H cβ‚€ aβ‚€ idp = cβ‚€ := begin exact sorry --esimp [total_space_method2, total_space_method, eq.encode], end definition equiv_pathover2 {A : Type} {a a' : A} (p : a = a') {B : A β†’ Type} {C : A β†’ Type} (f : B a ≃ C a) (g : B a' ≃ C a') (r : to_fun f =[p] to_fun g) : f =[p] g := begin fapply pathover_of_fn_pathover_fn, { intro a, apply equiv.sigma_char }, { apply sigma_pathover _ _ _ r, apply is_prop.elimo } end definition equiv_pathover_inv {A : Type} {a a' : A} (p : a = a') {B : A β†’ Type} {C : A β†’ Type} (f : B a ≃ C a) (g : B a' ≃ C a') (r : to_inv f =[p] to_inv g) : f =[p] g := begin /- this proof is a bit weird, but it works -/ apply equiv_pathover2, change f⁻¹ᢠ⁻¹ᢠ =[p] g⁻¹ᢠ⁻¹ᢠ, apply apo (Ξ»(a: A) (h : C a ≃ B a), h⁻¹ᢠ), apply equiv_pathover2, exact r end definition transport_lemma {A : Type} {C : A β†’ Type} {g₁ : A β†’ A} {x y : A} (p : x = y) (f : Π⦃x⦄, C x β†’ C (g₁ x)) (z : C x) : transport C (ap g₁ p)⁻¹ (f (transport C p z)) = f z := by induction p; reflexivity definition transport_lemma2 {A : Type} {C : A β†’ Type} {g₁ : A β†’ A} {x y : A} (p : x = y) (f : Π⦃x⦄, C x β†’ C (g₁ x)) (z : C x) : transport C (ap g₁ p) (f z) = f (transport C p z) := by induction p; reflexivity definition iterate_equiv2 {A : Type} {C : A β†’ Type} (f : A β†’ A) (h : Ξ a, C a ≃ C (f a)) (k : β„•) (a : A) : C a ≃ C (f^[k] a) := begin induction k with k IH, reflexivity, exact IH ⬝e h (f^[k] a) end definition ap_sigma_functor_sigma_eq {A A' : Type} {B : A β†’ Type} {B' : A' β†’ Type} {a a' : A} {b : B a} {b' : B a'} (f : A β†’ A') (g : Ξ a, B a β†’ B' (f a)) (p : a = a') (q : b =[p] b') : ap (sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) (pathover_ap B' f (apo g q)) := by induction q; reflexivity definition ap_sigma_functor_id_sigma_eq {A : Type} {B B' : A β†’ Type} {a a' : A} {b : B a} {b' : B a'} (g : Ξ a, B a β†’ B' a) (p : a = a') (q : b =[p] b') : ap (sigma_functor id g) (sigma_eq p q) = sigma_eq p (apo g q) := by induction q; reflexivity definition sigma_eq_pr2_constant {A B : Type} {a a' : A} {b b' : B} (p : a = a') (q : b =[p] b') : ap pr2 (sigma_eq p q) = (eq_of_pathover q) := by induction q; reflexivity definition sigma_eq_pr2_constant2 {A B : Type} {a a' : A} {b b' : B} (p : a = a') (q : b = b') : ap pr2 (sigma_eq p (pathover_of_eq p q)) = q := by induction p; induction q; reflexivity definition sigma_eq_concato_eq {A : Type} {B : A β†’ Type} {a a' : A} {b : B a} {b₁ bβ‚‚ : B a'} (p : a = a') (q : b =[p] b₁) (q' : b₁ = bβ‚‚) : sigma_eq p (q ⬝op q') = sigma_eq p q ⬝ ap (dpair a') q' := by induction q'; reflexivity definition eq_of_pathover_apo {A C : Type} {B : A β†’ Type} {a a' : A} {b : B a} {b' : B a'} {p : a = a'} (g : Ξ a, B a β†’ C) (q : b =[p] b') : eq_of_pathover (apo g q) = apd011 g p q := by induction q; reflexivity definition lift_succ2 [constructor] ⦃n : ℕ⦄ (x : fin n) : fin (succ n) := fin.mk x (le.step (is_lt x)) open fiber pointed /- move to fiber -/ definition fiber_functor [constructor] {A A' B B' : Type} {f : A β†’ B} {f' : A' β†’ B'} {b : B} {b' : B'} (g : A β†’ A') (h : B β†’ B') (H : hsquare g h f f') (p : h b = b') (x : fiber f b) : fiber f' b' := fiber.mk (g (point x)) (H (point x) ⬝ ap h (point_eq x) ⬝ p) definition pfiber_functor [constructor] {A A' B B' : Type*} {f : A β†’* B} {f' : A' β†’* B'} (g : A β†’* A') (h : B β†’* B') (H : psquare g h f f') : pfiber f β†’* pfiber f' := pmap.mk (fiber_functor g h H (respect_pt h)) begin fapply fiber_eq, exact respect_pt g, exact !con.assoc ⬝ to_homotopy_pt H end -- TODO: use this in pfiber_pequiv_of_phomotopy definition fiber_equiv_of_homotopy {A B : Type} {f g : A β†’ B} (h : f ~ g) (b : B) : fiber f b ≃ fiber g b := begin refine (fiber.sigma_char f b ⬝e _ ⬝e (fiber.sigma_char g b)⁻¹ᡉ), apply sigma_equiv_sigma_right, intros a, apply equiv_eq_closed_left, apply h end definition fiber_equiv_of_square {A B C D : Type} {b : B} {d : D} {f : A β†’ B} {g : C β†’ D} (h : A ≃ C) (k : B ≃ D) (s : k ∘ f ~ g ∘ h) (p : k b = d) : fiber f b ≃ fiber g d := calc fiber f b ≃ fiber (k ∘ f) (k b) : fiber.equiv_postcompose ... ≃ fiber (k ∘ f) d : transport_fiber_equiv (k ∘ f) p ... ≃ fiber (g ∘ h) d : fiber_equiv_of_homotopy s d ... ≃ fiber g d : fiber.equiv_precompose definition fiber_equiv_of_triangle {A B C : Type} {b : B} {f : A β†’ B} {g : C β†’ B} (h : A ≃ C) (s : f ~ g ∘ h) : fiber f b ≃ fiber g b := fiber_equiv_of_square h erfl s idp
1c783060a634770b68bb82519960432a229f3fd6
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/finsupp/interval.lean
b71f5d4d4987c01978e03190cedfca0611852ac3
[ "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
4,212
lean
/- Copyright (c) 2022 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import data.finset.finsupp import data.finset.locally_finite import data.finsupp.order /-! # Finite intervals of finitely supported functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides the `locally_finite_order` instance for `ΞΉ β†’β‚€ Ξ±` when `Ξ±` itself is locally finite and calculates the cardinality of its finite intervals. ## Main declarations * `finsupp.range_singleton`: Postcomposition with `has_singleton.singleton` on `finset` as a `finsupp`. * `finsupp.range_Icc`: Postcomposition with `finset.Icc` as a `finsupp`. Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely supported. -/ noncomputable theory open finset finsupp function open_locale big_operators classical pointwise variables {ΞΉ Ξ± : Type*} namespace finsupp section range_singleton variables [has_zero Ξ±] {f : ΞΉ β†’β‚€ Ξ±} {i : ΞΉ} {a : Ξ±} /-- Pointwise `finset.singleton` bundled as a `finsupp`. -/ @[simps] def range_singleton (f : ΞΉ β†’β‚€ Ξ±) : ΞΉ β†’β‚€ finset Ξ± := { to_fun := Ξ» i, {f i}, support := f.support, mem_support_to_fun := Ξ» i, begin rw [←not_iff_not, not_mem_support_iff, not_ne_iff], exact singleton_injective.eq_iff.symm, end } lemma mem_range_singleton_apply_iff : a ∈ f.range_singleton i ↔ a = f i := mem_singleton end range_singleton section range_Icc variables [has_zero Ξ±] [partial_order Ξ±] [locally_finite_order Ξ±] {f g : ΞΉ β†’β‚€ Ξ±} {i : ΞΉ} {a : Ξ±} /-- Pointwise `finset.Icc` bundled as a `finsupp`. -/ @[simps to_fun] def range_Icc (f g : ΞΉ β†’β‚€ Ξ±) : ΞΉ β†’β‚€ finset Ξ± := { to_fun := Ξ» i, Icc (f i) (g i), support := by haveI := classical.dec_eq ΞΉ; exact f.support βˆͺ g.support, mem_support_to_fun := Ξ» i, begin rw [mem_union, ←not_iff_not, not_or_distrib, not_mem_support_iff, not_mem_support_iff, not_ne_iff], exact Icc_eq_singleton_iff.symm, end } @[simp] lemma range_Icc_support [decidable_eq ΞΉ] (f g : ΞΉ β†’β‚€ Ξ±) : (range_Icc f g).support = f.support βˆͺ g.support := by convert rfl lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≀ a ∧ a ≀ g i := mem_Icc end range_Icc section partial_order variables [partial_order Ξ±] [has_zero Ξ±] [locally_finite_order Ξ±] (f g : ΞΉ β†’β‚€ Ξ±) instance : locally_finite_order (ΞΉ β†’β‚€ Ξ±) := by haveI := classical.dec_eq ΞΉ; haveI := classical.dec_eq Ξ±; exact locally_finite_order.of_Icc (ΞΉ β†’β‚€ Ξ±) (Ξ» f g, (f.support βˆͺ g.support).finsupp $ f.range_Icc g) (Ξ» f g x, begin refine (mem_finsupp_iff_of_support_subset $ finset.subset_of_eq $ range_Icc_support _ _).trans _, simp_rw mem_range_Icc_apply_iff, exact forall_and_distrib, end) lemma Icc_eq [decidable_eq ΞΉ] : Icc f g = (f.support βˆͺ g.support).finsupp (f.range_Icc g) := by convert rfl lemma card_Icc [decidable_eq ΞΉ] : (Icc f g).card = ∏ i in f.support βˆͺ g.support, (Icc (f i) (g i)).card := by simp_rw [Icc_eq, card_finsupp, range_Icc_to_fun] lemma card_Ico [decidable_eq ΞΉ] : (Ico f g).card = ∏ i in f.support βˆͺ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc [decidable_eq ΞΉ] : (Ioc f g).card = ∏ i in f.support βˆͺ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo [decidable_eq ΞΉ] : (Ioo f g).card = ∏ i in f.support βˆͺ g.support, (Icc (f i) (g i)).card - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end partial_order section canonically_ordered variables [canonically_ordered_add_monoid Ξ±] [locally_finite_order Ξ±] variables (f : ΞΉ β†’β‚€ Ξ±) lemma card_Iic : (Iic f).card = ∏ i in f.support, (Iic (f i)).card := begin classical, simp_rw [Iic_eq_Icc, card_Icc, finsupp.bot_eq_zero, support_zero, empty_union, zero_apply, bot_eq_zero] end lemma card_Iio : (Iio f).card = ∏ i in f.support, (Iic (f i)).card - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end canonically_ordered end finsupp
3421a9a0ea5ef08d48af28533fa8e7e07463ff69
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/factorial/basic.lean
d971f5283a5216b74704a420f0bf2955c91c4416
[ "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
14,934
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn, YaΓ«l Dillies -/ import data.nat.basic import data.nat.pow /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. ## Main declarations * `factorial`: The factorial. * `asc_factorial`: The ascending factorial. Note that it runs from `n + 1` to `n + k` and *not* from`n` to `n + k - 1`. We might want to change that in the future. * `desc_factorial`: The descending factorial. It runs from `n - k` to `n`. -/ namespace nat /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : β„• β†’ β„• | 0 := 1 | (succ n) := succ n * factorial n localized "notation n `!`:10000 := nat.factorial n" in nat section factorial variables {m n : β„•} @[simp] theorem factorial_zero : 0! = 1 := rfl @[simp] theorem factorial_succ (n : β„•) : n.succ! = (n + 1) * n! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl @[simp] theorem factorial_two : 2! = 2 := rfl theorem mul_factorial_pred (hn : 0 < n) : n * (n - 1)! = n! := tsub_add_cancel_of_le (nat.succ_le_of_lt hn) β–Έ rfl theorem factorial_pos : βˆ€ n, 0 < n! | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : β„•) : n! β‰  0 := ne_of_gt (factorial_pos _) theorem factorial_dvd_factorial {m n} (h : m ≀ n) : m! ∣ n! := begin induction n with n IH; simp, { have := nat.eq_zero_of_le_zero h, subst m, simp }, obtain he | hl := h.eq_or_lt, { subst m, simp }, exact (IH (le_of_lt_succ hl)).mul_left _, end theorem dvd_factorial : βˆ€ {m n}, 0 < m β†’ m ≀ n β†’ m ∣ n! | (succ m) n _ h := dvd_of_mul_right_dvd (factorial_dvd_factorial h) @[mono] theorem factorial_le {m n} (h : m ≀ n) : m! ≀ n! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) lemma factorial_mul_pow_le_factorial : βˆ€ {m n : β„•}, m! * m.succ ^ n ≀ (m + n)! | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.factorial_succ, mul_comm (nat.succ _), pow_succ', ← mul_assoc]; exact mul_le_mul factorial_mul_pow_le_factorial (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_factorial : monotone factorial := Ξ» n m, factorial_le lemma factorial_lt (hn : 0 < n) : n! < m! ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (factorial_le hmn) }, have : βˆ€ n, 0 < n β†’ n! < n.succ!, { intros k hk, rw [factorial_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (factorial_pos k) }, induction h with k hnk generalizing hn, { exact this _ hn, }, refine lt_trans (h_ih hn) (this _ _), exact lt_trans hn (lt_of_succ_le hnk), end lemma one_lt_factorial : 1 < n! ↔ 1 < n := by { convert factorial_lt _, refl, exact one_pos } lemma factorial_eq_one : n! = 1 ↔ n ≀ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_factorial, h], apply lt_irrefl }, cases h with h h, refl, cases h, refl, end lemma factorial_inj (hn : 1 < n!) : n! = m! ↔ n = m := begin split; intro h, { obtain hnm | hnm | hnm := lt_trichotomy n m, { exfalso, rw [← factorial_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_factorial] at hn, exact lt_trans one_pos hn }, { exact hnm }, exfalso, rw [h, one_lt_factorial] at hn, rw [←factorial_lt (lt_trans one_pos hn), h] at hnm, exact lt_irrefl _ hnm, }, { rw h }, end lemma self_le_factorial : βˆ€ n : β„•, n ≀ n! | 0 := zero_le_one | (k + 1) := le_mul_of_one_le_right k.zero_lt_succ.le (nat.one_le_of_lt $ nat.factorial_pos _) lemma lt_factorial_self {n : β„•} (hi : 3 ≀ n) : n < n! := begin rw [← succ_pred_eq_of_pos ((zero_lt_two.trans (lt.base 2)).trans_le hi), factorial_succ], exact lt_mul_of_one_lt_right ((pred n).succ_pos) ((one_lt_two.trans_le (le_pred_of_lt (succ_le_iff.mp hi))).trans_le (self_le_factorial _)), end lemma add_factorial_succ_lt_factorial_add_succ {i : β„•} (n : β„•) (hi : 2 ≀ i) : i + (n + 1)! < (i + n + 1)! := begin rw [factorial_succ (i + _), add_mul, one_mul], have : i ≀ i + n := le.intro rfl, exact add_lt_add_of_lt_of_le (this.trans_lt ((lt_mul_iff_one_lt_right (zero_lt_two.trans_le (hi.trans this))).mpr (lt_iff_le_and_ne.mpr ⟨(i + n).factorial_pos, Ξ» g, nat.not_succ_le_self 1 ((hi.trans this).trans (factorial_eq_one.mp g.symm))⟩))) (factorial_le ((le_of_eq (add_comm n 1)).trans ((add_le_add_iff_right n).mpr (one_le_two.trans hi)))), end lemma add_factorial_lt_factorial_add {i n : β„•} (hi : 2 ≀ i) (hn : 1 ≀ n) : i + n! < (i + n)! := begin cases hn, { rw factorial_one, exact lt_factorial_self (succ_le_succ hi) }, exact add_factorial_succ_lt_factorial_add_succ _ hi, end lemma add_factorial_succ_le_factorial_add_succ (i : β„•) (n : β„•) : i + (n + 1)! ≀ (i + (n + 1))! := begin obtain i2 | (_ | ⟨_, i0⟩) := le_or_lt 2 i, { exact (n.add_factorial_succ_lt_factorial_add_succ i2).le }, { change 1 + (n + 1)! ≀ (1 + n + 1) * (1 + n)!, rw [add_mul, one_mul, add_comm 1 n], exact (add_le_add_iff_right _).mpr (one_le_mul (nat.le_add_left 1 n) (n + 1).factorial_pos) }, rw [nat.le_zero_iff.mp (nat.succ_le_succ_iff.mp i0), zero_add, zero_add] end lemma add_factorial_le_factorial_add (i : β„•) {n : β„•} (n1 : 1 ≀ n) : i + n! ≀ (i + n)! := begin cases n1 with h, { exact self_le_factorial _ }, exact add_factorial_succ_le_factorial_add_succ i h, end lemma factorial_mul_pow_sub_le_factorial {n m : β„•} (hnm : n ≀ m) : n! * n ^ (m - n) ≀ m! := begin suffices : n! * (n + 1) ^ (m - n) ≀ m!, { apply trans _ this, rw mul_le_mul_left, apply pow_le_pow_of_le_left (zero_le n) (le_succ n), exact factorial_pos n,}, convert nat.factorial_mul_pow_le_factorial, exact (add_tsub_cancel_of_le hnm).symm, end end factorial /-! ### Ascending and descending factorials -/ section asc_factorial /-- `n.asc_factorial k = (n + k)! / n!` (as seen in `nat.asc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def asc_factorial (n : β„•) : β„• β†’ β„• | 0 := 1 | (k + 1) := (n + k + 1) * asc_factorial k @[simp] lemma asc_factorial_zero (n : β„•) : n.asc_factorial 0 = 1 := rfl @[simp] lemma zero_asc_factorial (k : β„•) : (0 : β„•).asc_factorial k = k! := begin induction k with t ht, refl, unfold asc_factorial, rw [ht, zero_add, nat.factorial_succ], end lemma asc_factorial_succ {n k : β„•} : n.asc_factorial k.succ = (n + k + 1) * n.asc_factorial k := rfl lemma succ_asc_factorial (n : β„•) : βˆ€ k, (n + 1) * n.succ.asc_factorial k = (n + k + 1) * n.asc_factorial k | 0 := by rw [add_zero, asc_factorial_zero, asc_factorial_zero] | (k + 1) := by rw [asc_factorial, mul_left_comm, succ_asc_factorial, asc_factorial, succ_add, ←add_assoc] /-- `n.asc_factorial k = (n + k)! / n!` but without β„•-division. See `nat.asc_factorial_eq_div` for the version with β„•-division. -/ theorem factorial_mul_asc_factorial (n : β„•) : βˆ€ k, n! * n.asc_factorial k = (n + k)! | 0 := by rw [asc_factorial, add_zero, mul_one] | (k + 1) := by rw [asc_factorial_succ, mul_left_comm, factorial_mul_asc_factorial, ← add_assoc, factorial] /-- Avoid in favor of `nat.factorial_mul_asc_factorial` if you can. β„•-division isn't worth it. -/ lemma asc_factorial_eq_div (n k : β„•) : n.asc_factorial k = (n + k)! / n! := begin apply mul_left_cancelβ‚€ (factorial_ne_zero n), rw factorial_mul_asc_factorial, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ le.intro rfl).symm end lemma asc_factorial_of_sub {n k : β„•} (h : k < n) : (n - k) * (n - k).asc_factorial k = (n - (k + 1)).asc_factorial (k + 1) := begin set t := n - k.succ with ht, suffices h' : n - k = t.succ, by rw [←ht, h', succ_asc_factorial, asc_factorial_succ], rw [ht, succ_eq_add_one, ←tsub_tsub_assoc (succ_le_of_lt h) (succ_pos _), succ_sub_one], end lemma pow_succ_le_asc_factorial (n : β„•) : βˆ€ (k : β„•), (n + 1)^k ≀ n.asc_factorial k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw pow_succ, exact nat.mul_le_mul (nat.add_le_add_right le_self_add _) (pow_succ_le_asc_factorial k), end lemma pow_lt_asc_factorial' (n k : β„•) : (n + 1)^(k + 2) < n.asc_factorial (k + 2) := begin rw pow_succ, exact nat.mul_lt_mul (nat.add_lt_add_right (nat.lt_add_of_pos_right succ_pos') 1) (pow_succ_le_asc_factorial n _) (pow_pos succ_pos' _), end lemma pow_lt_asc_factorial (n : β„•) : βˆ€ {k : β„•}, 2 ≀ k β†’ (n + 1)^k < n.asc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := Ξ» _, pow_lt_asc_factorial' n k lemma asc_factorial_le_pow_add (n : β„•) : βˆ€ (k : β„•), n.asc_factorial k ≀ (n + k)^k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw [asc_factorial_succ, pow_succ], exact nat.mul_le_mul_of_nonneg_left ((asc_factorial_le_pow_add k).trans (nat.pow_le_pow_of_le_left (le_succ _) _)), end lemma asc_factorial_lt_pow_add (n : β„•) : βˆ€ {k : β„•}, 2 ≀ k β†’ n.asc_factorial k < (n + k)^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := Ξ» _, begin rw [asc_factorial_succ, pow_succ], refine nat.mul_lt_mul' (le_refl _) ((asc_factorial_le_pow_add n _).trans_lt (pow_lt_pow_of_lt_left (lt_add_one _) (succ_pos _))) (succ_pos _), end lemma asc_factorial_pos (n k : β„•) : 0 < n.asc_factorial k := (pow_pos (succ_pos n) k).trans_le (pow_succ_le_asc_factorial n k) end asc_factorial section desc_factorial /-- `n.desc_factorial k = n! / (n - k)!` (as seen in `nat.desc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def desc_factorial (n : β„•) : β„• β†’ β„• | 0 := 1 | (k + 1) := (n - k) * desc_factorial k @[simp] lemma desc_factorial_zero (n : β„•) : n.desc_factorial 0 = 1 := rfl @[simp] lemma desc_factorial_succ (n k : β„•) : n.desc_factorial k.succ = (n - k) * n.desc_factorial k := rfl lemma zero_desc_factorial_succ (k : β„•) : (0 : β„•).desc_factorial k.succ = 0 := by rw [desc_factorial_succ, zero_tsub, zero_mul] @[simp] lemma desc_factorial_one (n : β„•) : n.desc_factorial 1 = n := by rw [desc_factorial_succ, desc_factorial_zero, mul_one, tsub_zero] @[simp] lemma succ_desc_factorial_succ (n : β„•) : βˆ€ k : β„•, (n + 1).desc_factorial (k + 1) = (n + 1) * n.desc_factorial k | 0 := by rw [desc_factorial_zero, desc_factorial_one, mul_one] | (succ k) := by rw [desc_factorial_succ, succ_desc_factorial_succ, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma succ_desc_factorial (n : β„•) : βˆ€ k, (n + 1 - k) * (n + 1).desc_factorial k = (n + 1) * n.desc_factorial k | 0 := by rw [tsub_zero, desc_factorial_zero, desc_factorial_zero] | (k + 1) := by rw [desc_factorial, succ_desc_factorial, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma desc_factorial_self : βˆ€ n : β„•, n.desc_factorial n = n! | 0 := by rw [desc_factorial_zero, factorial_zero] | (succ n) := by rw [succ_desc_factorial_succ, desc_factorial_self, factorial_succ] @[simp] lemma desc_factorial_eq_zero_iff_lt {n : β„•} : βˆ€ {k : β„•}, n.desc_factorial k = 0 ↔ n < k | 0 := by simp only [desc_factorial_zero, nat.one_ne_zero, nat.not_lt_zero] | (succ k) := begin rw [desc_factorial_succ, mul_eq_zero, desc_factorial_eq_zero_iff_lt, lt_succ_iff, tsub_eq_zero_iff_le, lt_iff_le_and_ne, or_iff_left_iff_imp, and_imp], exact Ξ» h _, h, end alias nat.desc_factorial_eq_zero_iff_lt ↔ _ nat.desc_factorial_of_lt lemma add_desc_factorial_eq_asc_factorial (n : β„•) : βˆ€ k : β„•, (n + k).desc_factorial k = n.asc_factorial k | 0 := by rw [asc_factorial_zero, desc_factorial_zero] | (succ k) := by rw [nat.add_succ, succ_desc_factorial_succ, asc_factorial_succ, add_desc_factorial_eq_asc_factorial] /-- `n.desc_factorial k = n! / (n - k)!` but without β„•-division. See `nat.desc_factorial_eq_div` for the version using β„•-division. -/ theorem factorial_mul_desc_factorial : βˆ€ {n k : β„•}, k ≀ n β†’ (n - k)! * n.desc_factorial k = n! | n 0 := Ξ» _, by rw [desc_factorial_zero, mul_one, tsub_zero] | 0 (succ k) := Ξ» h, by { exfalso, exact not_succ_le_zero k h } | (succ n) (succ k) := Ξ» h, by rw [succ_desc_factorial_succ, succ_sub_succ, ←mul_assoc, mul_comm (n - k)!, mul_assoc, factorial_mul_desc_factorial (nat.succ_le_succ_iff.1 h), factorial_succ] /-- Avoid in favor of `nat.factorial_mul_desc_factorial` if you can. β„•-division isn't worth it. -/ lemma desc_factorial_eq_div {n k : β„•} (h : k ≀ n) : n.desc_factorial k = n! / (n - k)! := begin apply mul_left_cancelβ‚€ (factorial_ne_zero (n - k)), rw factorial_mul_desc_factorial h, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ nat.sub_le n k).symm, end lemma pow_sub_le_desc_factorial (n : β„•) : βˆ€ (k : β„•), (n + 1 - k)^k ≀ n.desc_factorial k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ, succ_sub_succ], exact nat.mul_le_mul_of_nonneg_left (le_trans (nat.pow_le_pow_of_le_left (tsub_le_tsub_right (le_succ _) _) k) (pow_sub_le_desc_factorial k)), end lemma pow_sub_lt_desc_factorial' {n : β„•} : βˆ€ {k : β„•}, k + 2 ≀ n β†’ (n - (k + 1))^(k + 2) < n.desc_factorial (k + 2) | 0 := Ξ» h, begin rw [desc_factorial_succ, pow_succ, pow_one, desc_factorial_one], exact nat.mul_lt_mul_of_pos_left (tsub_lt_self (lt_of_lt_of_le zero_lt_two h) zero_lt_one) (tsub_pos_of_lt h), end | (k + 1) := Ξ» h, begin rw [desc_factorial_succ, pow_succ], refine nat.mul_lt_mul_of_pos_left ((nat.pow_le_pow_of_le_left (tsub_le_tsub_right (le_succ n) _) _).trans_lt _) (tsub_pos_of_lt h), rw succ_sub_succ, exact (pow_sub_lt_desc_factorial' ((le_succ _).trans h)), end lemma pow_sub_lt_desc_factorial {n : β„•} : βˆ€ {k : β„•}, 2 ≀ k β†’ k ≀ n β†’ (n + 1 - k)^k < n.desc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := Ξ» _ h, by { rw succ_sub_succ, exact pow_sub_lt_desc_factorial' h } lemma desc_factorial_le_pow (n : β„•) : βˆ€ (k : β„•), n.desc_factorial k ≀ n^k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ], exact nat.mul_le_mul (nat.sub_le _ _) (desc_factorial_le_pow k), end lemma desc_factorial_lt_pow {n : β„•} (hn : 1 ≀ n) : βˆ€ {k : β„•}, 2 ≀ k β†’ n.desc_factorial k < n^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := Ξ» _, begin rw [desc_factorial_succ, pow_succ', mul_comm], exact nat.mul_lt_mul' (desc_factorial_le_pow _ _) (tsub_lt_self hn k.zero_lt_succ) (pow_pos hn _), end end desc_factorial end nat
f4a3411fb333a00fe5d8a5aa26567a20117ee655
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Elab/StructInst.lean
9b0d6a7246434f4e7a29d2d88621f977440be356
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,289
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.FindExpr import Lean.Parser.Term import Lean.Elab.App import Lean.Elab.Binders namespace Lean.Elab.Term.StructInst open Std (HashMap) open Meta /- Structure instances are of the form: "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional ", ")) >> optEllipsis >> optional (" : " >> termParser) >> " }" -/ @[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx => let expectedArg := stx[4] if expectedArg.isNone then Macro.throwUnsupported else let expected := expectedArg[1] let stxNew := stx.setArg 4 mkNullNode `(($stxNew : $expected)) /- If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`. Note that this one is not a `Macro` because we need to access the local context. -/ private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) := withFreshMacroScope do let sourceOpt := stx[1] if sourceOpt.isNone then pure none else let source := sourceOpt[0] match (← isLocalIdent? source) with | some _ => pure none | none => if source.isMissing then throwAbortTerm else let src ← `(src) let sourceOpt := sourceOpt.setArg 0 src let stxNew := stx.setArg 1 sourceOpt `(let src := $source; $stxNew) inductive Source where | none -- structure instance source has not been provieded | implicit (stx : Syntax) -- `..` | explicit (stx : Syntax) (src : Expr) -- `src with` deriving Inhabited def Source.isNone : Source β†’ Bool | Source.none => true | _ => false def setStructSourceSyntax (structStx : Syntax) : Source β†’ Syntax | Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode | Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx | Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode private def getStructSource (stx : Syntax) : TermElabM Source := withRef stx do let explicitSource := stx[1] let implicitSource := stx[3] if explicitSource.isNone && implicitSource[0].isNone then return Source.none else if explicitSource.isNone then return Source.implicit implicitSource else if implicitSource[0].isNone then let fvar? ← isLocalIdent? explicitSource[0] match fvar? with | none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here | some src => return Source.explicit explicitSource src else throwError "invalid structure instance `with` and `..` cannot be used together" /- We say a `{ ... }` notation is a `modifyOp` if it contains only one ``` def structInstArrayRef := leading_parser "[" >> termParser >>"]" ``` -/ private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do let s? ← stx[2].getArgs.foldlM (init := none) fun s? p => /- p is of the form `(group ((structInstFieldAbbrev <|> structInstField) >> optional ", "))` -/ let arg := p[0] if arg.getKind == ``Lean.Parser.Term.structInstField then /- Remark: the syntax for `structInstField` is ``` def structInstLVal := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstField := leading_parser structInstLVal >> " := " >> termParser ``` -/ let lval := arg[0] let k := lval[0].getKind if k == ``Lean.Parser.Term.structInstArrayRef then match s? with | none => pure (some arg) | some s => if s.getKind == ``Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid \{...} notation, at most one `[..]` at a given level" else throwErrorAt arg "invalid \{...} notation, can't mix field and `[..]` at a given level" else match s? with | none => pure (some arg) | some s => if s.getKind == ``Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid \{...} notation, can't mix field and `[..]` at a given level" else pure s? else pure s? match s? with | none => pure none | some s => if s[0][0].getKind == ``Lean.Parser.Term.structInstArrayRef then pure s? else pure none private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let cont (val : Syntax) : TermElabM Expr := do let lval := modifyOp[0][0] let idx := lval[1] let self := source[0] let stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val)) trace[Elab.struct.modifyOp] "{stx}\n===>\n{stxNew}" withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? trace[Elab.struct.modifyOp] "{modifyOp}\nSource: {source}" let rest := modifyOp[0][1] if rest.isNone then cont modifyOp[2] else let s ← `(s) let valFirst := rest[0] let valFirst := if valFirst.getKind == ``Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1] let restArgs := rest.getArgs let valRest := mkNullNode restArgs[1:restArgs.size] let valField := modifyOp.setArg 0 <| Syntax.node ``Parser.Term.structInstLVal #[valFirst, valRest] let valSource := source.modifyArg 0 fun _ => s let val := stx.setArg 1 valSource let val := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]] trace[Elab.struct.modifyOp] "{stx}\nval: {val}" cont val /- Get structure name and elaborate explicit source (if available) -/ private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM (Name Γ— Expr) := do tryPostponeIfNoneOrMVar expectedType? let useSource : Unit β†’ TermElabM (Name Γ— Expr) := fun _ => match sourceView, expectedType? with | Source.explicit _ src, _ => do let srcType ← inferType src let srcType ← whnf srcType tryPostponeIfMVar srcType match srcType.getAppFn with | Expr.const constName _ _ => return (constName, srcType) | _ => throwUnexpectedExpectedType srcType "source" | _, some expectedType => throwUnexpectedExpectedType expectedType | _, none => throwUnknownExpectedType match expectedType? with | none => useSource () | some expectedType => let expectedType ← whnf expectedType match expectedType.getAppFn with | Expr.const constName _ _ => return (constName, expectedType) | _ => useSource () where throwUnknownExpectedType := throwError "invalid \{...} notation, expected type is not known" throwUnexpectedExpectedType type (kind := "expected") := do let type ← instantiateMVars type if type.getAppFn.isMVar then throwUnknownExpectedType else throwError "invalid \{...} notation, {kind} type is not of the form (C ...){indentExpr type}" inductive FieldLHS where | fieldName (ref : Syntax) (name : Name) | fieldIndex (ref : Syntax) (idx : Nat) | modifyOp (ref : Syntax) (index : Syntax) deriving Inhabited instance : ToFormat FieldLHS := ⟨fun lhs => match lhs with | FieldLHS.fieldName _ n => format n | FieldLHS.fieldIndex _ i => format i | FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩ inductive FieldVal (Οƒ : Type) where | term (stx : Syntax) : FieldVal Οƒ | nested (s : Οƒ) : FieldVal Οƒ | default : FieldVal Οƒ -- mark that field must be synthesized using default value deriving Inhabited structure Field (Οƒ : Type) where ref : Syntax lhs : List FieldLHS val : FieldVal Οƒ expr? : Option Expr := none deriving Inhabited def Field.isSimple {Οƒ} : Field Οƒ β†’ Bool | { lhs := [_], .. } => true | _ => false inductive Struct where | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source) deriving Inhabited abbrev Fields := List (Field Struct) /- true if all fields of the given structure are marked as `default` -/ partial def Struct.allDefault : Struct β†’ Bool | ⟨_, _, fields, _⟩ => fields.all fun ⟨_, _, val, _⟩ => match val with | FieldVal.term _ => false | FieldVal.default => true | FieldVal.nested s => allDefault s def Struct.ref : Struct β†’ Syntax | ⟨ref, _, _, _⟩ => ref def Struct.structName : Struct β†’ Name | ⟨_, structName, _, _⟩ => structName def Struct.fields : Struct β†’ Fields | ⟨_, _, fields, _⟩ => fields def Struct.source : Struct β†’ Source | ⟨_, _, _, s⟩ => s def formatField (formatStruct : Struct β†’ Format) (field : Field Struct) : Format := Format.joinSep field.lhs " . " ++ " := " ++ match field.val with | FieldVal.term v => v.prettyPrint | FieldVal.nested s => formatStruct s | FieldVal.default => "<default>" partial def formatStruct : Struct β†’ Format | ⟨_, structName, fields, source⟩ => let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", " match source with | Source.none => "{" ++ fieldsFmt ++ "}" | Source.implicit _ => "{" ++ fieldsFmt ++ " .. }" | Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}" instance : ToFormat Struct := ⟨formatStruct⟩ instance : ToString Struct := ⟨toString ∘ format⟩ instance : ToFormat (Field Struct) := ⟨formatField formatStruct⟩ instance : ToString (Field Struct) := ⟨toString ∘ format⟩ /- Recall that `structInstField` elements have the form ``` def structInstField := leading_parser structInstLVal >> " := " >> termParser def structInstLVal := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstArrayRef := leading_parser "[" >> termParser >>"]" ``` -/ -- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName` def FieldLHS.toSyntax (first : Bool) : FieldLHS β†’ Syntax | FieldLHS.modifyOp stx _ => stx | FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkGroupNode #[mkAtomFrom stx ".", mkIdentFrom stx name] | FieldLHS.fieldIndex stx _ => if first then stx else mkGroupNode #[mkAtomFrom stx ".", stx] def FieldVal.toSyntax : FieldVal Struct β†’ Syntax | FieldVal.term stx => stx | _ => unreachable! def Field.toSyntax : Field Struct β†’ Syntax | field => let stx := field.ref let stx := stx.setArg 2 field.val.toSyntax match field.lhs with | first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ] | _ => unreachable! private def toFieldLHS (stx : Syntax) : MacroM FieldLHS := if stx.getKind == ``Lean.Parser.Term.structInstArrayRef then return FieldLHS.modifyOp stx stx[1] else -- Note that the representation of the first field is different. let stx := if stx.getKind == groupKind then stx[1] else stx if stx.isIdent then return FieldLHS.fieldName stx stx.getId.eraseMacroScopes else match stx.isFieldIdx? with | some idx => return FieldLHS.fieldIndex stx idx | none => Macro.throwError "unexpected structure syntax" private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : MacroM Struct := do /- Recall that `stx` is of the form ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let fieldsStx ← stx[2].getArgs.mapM fun stx => let stx := stx[0] if stx.getKind == ``Lean.Parser.Term.structInstField then return stx else let id := stx[0] `(Lean.Parser.Term.structInstField| $id:ident := $id:ident) let fields ← fieldsStx.toList.mapM fun fieldStx => do let val := fieldStx[2] let first ← toFieldLHS fieldStx[0][0] let rest ← fieldStx[0][1].getArgs.toList.mapM toFieldLHS pure { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct } pure ⟨stx, structName, fields, source⟩ def Struct.modifyFieldsM {m : Type β†’ Type} [Monad m] (s : Struct) (f : Fields β†’ m Fields) : m Struct := match s with | ⟨ref, structName, fields, source⟩ => return ⟨ref, structName, (← f fields), source⟩ def Struct.modifyFields (s : Struct) (f : Fields β†’ Fields) : Struct := Id.run <| s.modifyFieldsM f def Struct.setFields (s : Struct) (fields : Fields) : Struct := s.modifyFields fun _ => fields private def expandCompositeFields (s : Struct) : Struct := s.modifyFields fun fields => fields.map fun field => match field with | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } => let newEntries := n.components.map <| FieldLHS.fieldName ref { field with lhs := newEntries ++ rest } | _ => field private def expandNumLitFields (s : Struct) : TermElabM Struct := s.modifyFieldsM fun fields => do let env ← getEnv let fieldNames := getStructureFields env s.structName fields.mapM fun field => match field with | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } => if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0" else if idx > fieldNames.size then throwErrorAt ref "invalid field index, structure has only #{fieldNames.size} fields" else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest } | _ => pure field /- For example, consider the following structures: ``` structure A where x : Nat structure B extends A where y : Nat structure C extends B where z : Bool ``` This method expands parent structure fields using the path to the parent structure. For example, ``` { x := 0, y := 0, z := true : C } ``` is expanded into ``` { toB.toA.x := 0, toB.y := 0, z := true : C } ``` -/ private def expandParentFields (s : Struct) : TermElabM Struct := do let env ← getEnv s.modifyFieldsM fun fields => fields.mapM fun field => match field with | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } => match findField? env s.structName fieldName with | none => throwErrorAt ref "'{fieldName}' is not a field of structure '{s.structName}'" | some baseStructName => if baseStructName == s.structName then pure field else match getPathToBaseStructure? env baseStructName s.structName with | some path => do let path := path.map fun funName => match funName with | Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s) | _ => unreachable! pure { field with lhs := path ++ field.lhs } | _ => throwErrorAt ref "failed to access field '{fieldName}' in parent structure" | _ => pure field private abbrev FieldMap := HashMap Name Fields private def mkFieldMap (fields : Fields) : TermElabM FieldMap := fields.foldlM (init := {}) fun fieldMap field => match field.lhs with | FieldLHS.fieldName _ fieldName :: rest => match fieldMap.find? fieldName with | some (prevField::restFields) => if field.isSimple || prevField.isSimple then throwErrorAt field.ref "field '{fieldName}' has already beed specified" else return fieldMap.insert fieldName (field::prevField::restFields) | _ => return fieldMap.insert fieldName [field] | _ => unreachable! private def isSimpleField? : Fields β†’ Option (Field Struct) | [field] => if field.isSimple then some field else none | _ => none private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do match fieldNames.findIdx? fun n => n == fieldName with | some idx => pure idx | none => throwError "field '{fieldName}' is not a valid field of '{structName}'" private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax := Syntax.node ``Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName] private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source := match src with | Source.explicit stx src => do let idx ← getFieldIdx structName fieldNames fieldName let stx := stx.modifyArg 0 fun stx => mkProjStx stx fieldName return Source.explicit stx (mkProj structName idx src) | s => return s private def groupFields (expandStruct : Struct β†’ TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName withRef s.ref do s.modifyFieldsM fun fields => do let fieldMap ← mkFieldMap fields fieldMap.toList.mapM fun ⟨fieldName, fields⟩ => do match isSimpleField? fields with | some field => pure field | none => let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! } let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let field := fields.head! match Lean.isSubobjectField? env s.structName fieldName with | some substructName => let substruct := Struct.mk s.ref substructName substructFields substructSource let substruct ← expandStruct substruct pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct } | none => do -- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them. let valStx := s.ref -- construct substructure syntax using s.ref as template let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type let args := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode] let valStx := valStx.setArg 2 (mkNullNode args) let valStx := setStructSourceSyntax valStx substructSource pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx } def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) := fields.find? fun field => match field.lhs with | [FieldLHS.fieldName _ n] => n == fieldName | _ => false private def addMissingFields (expandStruct : Struct β†’ TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName let ref := s.ref withRef ref do let fields ← fieldNames.foldlM (init := []) fun fields fieldName => do match findField? s.fields fieldName with | some field => return field::fields | none => let addField (val : FieldVal Struct) : TermElabM Fields := do return { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields match Lean.isSubobjectField? env s.structName fieldName with | some substructName => do let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let substruct := Struct.mk s.ref substructName [] substructSource let substruct ← expandStruct substruct addField (FieldVal.nested substruct) | none => match s.source with | Source.none => addField FieldVal.default | Source.implicit _ => addField (FieldVal.term (mkHole s.ref)) | Source.explicit stx _ => -- stx is of the form `optional (try (termParser >> "with"))` let src := stx[0] let val := mkProjStx src fieldName addField (FieldVal.term val) return s.setFields fields.reverse private partial def expandStruct (s : Struct) : TermElabM Struct := do let s := expandCompositeFields s let s ← expandNumLitFields s let s ← expandParentFields s let s ← groupFields expandStruct s addMissingFields expandStruct s structure CtorHeaderResult where ctorFn : Expr ctorFnType : Expr instMVars : Array MVarId := #[] private def mkCtorHeaderAux : Nat β†’ Expr β†’ Expr β†’ Array MVarId β†’ TermElabM CtorHeaderResult | 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars } | n+1, type, ctorFn, instMVars => do let type ← whnfForall type match type with | Expr.forallE _ d b c => match c.binderInfo with | BinderInfo.instImplicit => let a ← mkFreshExprMVar d MetavarKind.synthetic mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!) | _ => let a ← mkFreshExprMVar d mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars | _ => throwError "unexpected constructor type" private partial def getForallBody : Nat β†’ Expr β†’ Option Expr | i+1, Expr.forallE _ _ b _ => getForallBody i b | i+1, _ => none | 0, type => type private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit := match expectedType? with | none => pure () | some expectedType => do match getForallBody numFields type with | none => pure () | some typeBody => unless typeBody.hasLooseBVars do discard <| isDefEq expectedType typeBody private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do let us ← mkFreshLevelMVars ctorVal.levelParams.length let val := Lean.mkConst ctorVal.name us let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams us let r ← mkCtorHeaderAux ctorVal.numParams type val #[] propagateExpectedType r.ctorFnType ctorVal.numFields expectedType? synthesizeAppInstMVars r.instMVars pure r def markDefaultMissing (e : Expr) : Expr := mkAnnotation `structInstDefault e def defaultMissing? (e : Expr) : Option Expr := annotation? `structInstDefault e def throwFailedToElabField {Ξ±} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM Ξ± := throwError "failed to elaborate field '{fieldName}' of '{structName}, {msgData}" def trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do if !s.allDefault then pure none else try synthInstance? expectedType catch _ => pure none private partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr Γ— Struct) := withRef s.ref do let env ← getEnv let ctorVal := getStructureCtor env s.structName let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType? let (e, _, fields) ← s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field => match field.lhs with | [FieldLHS.fieldName ref fieldName] => do let type ← whnfForall type trace[Elab.struct] "elabStruct {field}, {type}" match type with | Expr.forallE _ d b _ => let cont (val : Expr) (field : Field Struct) : TermElabM (Expr Γ— Expr Γ— Fields) := do pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo { projName := s.structName.append fieldName, fieldName, lctx := (← getLCtx), val, stx := ref } let e := mkApp e val let type := b.instantiate1 val let field := { field with expr? := some val } pure (e, type, field::fields) match field.val with | FieldVal.term stx => cont (← elabTermEnsuringType stx d) field | FieldVal.nested s => do -- if all fields of `s` are marked as `default`, then try to synthesize instance match (← trySynthStructInstance? s d) with | some val => cont val { field with val := FieldVal.term (mkHole field.ref) } | none => do let (val, sNew) ← elabStruct s (some d); let val ← ensureHasType d val; cont val { field with val := FieldVal.nested sNew } | FieldVal.default => do match d.getAutoParamTactic? with | some (Expr.const tacticDecl ..) => match evalSyntaxConstant env (← getOptions) tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => let stx ← `(by $tacticSyntax) cont (← elabTermEnsuringType stx (d.getArg! 0)) field | _ => let val ← withRef field.ref <| mkFreshExprMVar (some d) cont (markDefaultMissing val) field | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!"unexpected constructor type{indentExpr type}" | _ => throwErrorAt field.ref "unexpected unexpanded structure field" pure (e, s.setFields fields.reverse) namespace DefaultFields structure Context where -- We must search for default values overriden in derived structures structs : Array Struct := #[] allStructNames : Array Name := #[] /-- Consider the following example: ``` structure A where x : Nat := 1 structure B extends A where y : Nat := x + 1 x := y + 1 structure C extends B where z : Nat := 2*y x := z + 3 ``` And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`. We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2. The field `maxDistance` specifies the maximum distance considered in a round of Default field computation. Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0. The fixpoint for setting default values works in the following way. - Keep computing default values using `maxDistance == 0`. - We increase `maxDistance` whenever we failed to compute a new default value in a round. - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value. We use depth-first search. - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above). -/ maxDistance : Nat := 0 structure State where progress : Bool := false partial def collectStructNames (struct : Struct) (names : Array Name) : Array Name := let names := names.push struct.structName struct.fields.foldl (init := names) fun names field => match field.val with | FieldVal.nested struct => collectStructNames struct names | _ => names partial def getHierarchyDepth (struct : Struct) : Nat := struct.fields.foldl (init := 0) fun max field => match field.val with | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1) | _ => max partial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) := struct.fields.findSome? fun field => match field.val with | FieldVal.nested struct => findDefaultMissing? mctx struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field | _ => none def getFieldName (field : Field Struct) : Name := match field.lhs with | [FieldLHS.fieldName _ fieldName] => fieldName | _ => unreachable! abbrev M := ReaderT Context (StateRefT State TermElabM) def isRoundDone : M Bool := do return (← get).progress && (← read).maxDistance > 0 def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr := struct.fields.findSome? fun field => if getFieldName field == fieldName then field.expr? else none partial def mkDefaultValueAux? (struct : Struct) : Expr β†’ TermElabM (Option Expr) | Expr.lam n d b c => withRef struct.ref do if c.binderInfo.isExplicit then let fieldName := n match getFieldValue? struct fieldName with | none => pure none | some val => let valType ← inferType val if (← isDefEq valType d) then mkDefaultValueAux? struct (b.instantiate1 val) else pure none else let arg ← mkFreshExprMVar d mkDefaultValueAux? struct (b.instantiate1 arg) | e => if e.isAppOfArity ``id 2 then pure (some e.appArg!) else pure (some e) def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) := withRef struct.ref do let us ← mkFreshLevelMVarsFor cinfo mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us) /-- If `e` is a projection function of one of the given structures, then reduce it -/ def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name .. => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if structNames.contains structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none /-- Reduce default value. It performs beta reduction and projections of the given structures. -/ partial def reduce (structNames : Array Name) (e : Expr) : MetaM Expr := do -- trace[Elab.struct] "reduce {e}" match e with | Expr.lam .. => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (← reduce structNames b) | Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← reduce structNames b) | Expr.letE .. => lambdaLetTelescope e fun xs b => do mkLetFVars xs (← reduce structNames b) | Expr.proj _ i b _ => do match (← Meta.project? b i) with | some r => reduce structNames r | none => return e.updateProj! (← reduce structNames b) | Expr.app f .. => do match (← reduceProjOf? structNames e) with | some r => reduce structNames r | none => let f := f.getAppFn let f' ← reduce structNames f if f'.isLambda then let revArgs := e.getAppRevArgs reduce structNames (f'.betaRev revArgs) else let args ← e.getAppArgs.mapM (reduce structNames) return (mkAppN f' args) | Expr.mdata _ b _ => do let b ← reduce structNames b if (defaultMissing? e).isSome && !b.isMVar then return b else return e.updateMData! b | Expr.mvar mvarId _ => do match (← getExprMVarAssignment? mvarId) with | some val => if val.isMVar then pure val else reduce structNames val | none => return e | e => return e partial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool := let rec loop (i : Nat) (dist : Nat) := do if dist > maxDistance then pure false else if h : i < structs.size then do let struct := structs.get ⟨i, h⟩ let defaultName := struct.structName ++ fieldName ++ `_default let env ← getEnv match env.find? defaultName with | some cinfo@(ConstantInfo.defnInfo defVal) => do let mctx ← getMCtx let val? ← mkDefaultValue? struct cinfo match val? with | none => do setMCtx mctx; loop (i+1) (dist+1) | some val => do let val ← reduce allStructNames val match val.find? fun e => (defaultMissing? e).isSome with | some _ => setMCtx mctx; loop (i+1) (dist+1) | none => let mvarDecl ← getMVarDecl mvarId let val ← ensureHasType mvarDecl.type val assignExprMVar mvarId val pure true | _ => loop (i+1) dist else pure false loop 0 0 partial def step (struct : Struct) : M Unit := unless (← isRoundDone) do withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do for field in struct.fields do match field.val with | FieldVal.nested struct => step struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => unless (← isExprMVarAssigned mvarId) do let ctx ← read if (← withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then modify fun s => { s with progress := true } | _ => pure () partial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do match findDefaultMissing? (← getMCtx) struct with | none => pure () -- Done | some field => trace[Elab.struct] "propagate [{d}] [field := {field}]: {struct}" if d > hierarchyDepth then throwErrorAt field.ref "field '{getFieldName field}' is missing" else withReader (fun ctx => { ctx with maxDistance := d }) do modify fun s => { s with progress := false } step struct if (← get).progress then do propagateLoop hierarchyDepth 0 struct else propagateLoop hierarchyDepth (d+1) struct def propagate (struct : Struct) : TermElabM Unit := let hierarchyDepth := getHierarchyDepth struct let structNames := collectStructNames struct #[] (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {} end DefaultFields private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do let (structName, structType) ← getStructName stx expectedType? source unless isStructure (← getEnv) structName do throwError "invalid \{...} notation, structure type expected{indentExpr structType}" let struct ← liftMacroM <| mkStructView stx structName source let struct ← expandStruct struct trace[Elab.struct] "{struct}" let (r, struct) ← elabStruct struct expectedType? DefaultFields.propagate struct return r @[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do match (← expandNonAtomicExplicitSource stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let sourceView ← getStructSource stx match (← isModifyOp? stx), sourceView with | some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType? | some _, _ => throwError "invalid \{...} notation, explicit source is required when using '[<index>] := <value>'" | _, _ => elabStructInstAux stx expectedType? sourceView builtin_initialize registerTraceClass `Elab.struct end Lean.Elab.Term.StructInst
8390b32ceb092beeac02e03e0eff1e90b57b20d2
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/opposites.lean
31ab835673e81034add706633bdfab7e2f7046eb
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
5,779
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Opposites. -/ import data.opposite import algebra.field namespace opposite universes u variables (Ξ± : Type u) instance [has_add Ξ±] : has_add (opposite Ξ±) := { add := Ξ» x y, op (unop x + unop y) } instance [add_semigroup Ξ±] : add_semigroup (opposite Ξ±) := { add_assoc := Ξ» x y z, unop_inj $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add Ξ± } instance [add_left_cancel_semigroup Ξ±] : add_left_cancel_semigroup (opposite Ξ±) := { add_left_cancel := Ξ» x y z H, unop_inj $ add_left_cancel $ op_inj H, .. opposite.add_semigroup Ξ± } instance [add_right_cancel_semigroup Ξ±] : add_right_cancel_semigroup (opposite Ξ±) := { add_right_cancel := Ξ» x y z H, unop_inj $ add_right_cancel $ op_inj H, .. opposite.add_semigroup Ξ± } instance [add_comm_semigroup Ξ±] : add_comm_semigroup (opposite Ξ±) := { add_comm := Ξ» x y, unop_inj $ add_comm (unop x) (unop y), .. opposite.add_semigroup Ξ± } instance [has_zero Ξ±] : has_zero (opposite Ξ±) := { zero := op 0 } instance [add_monoid Ξ±] : add_monoid (opposite Ξ±) := { zero_add := Ξ» x, unop_inj $ zero_add $ unop x, add_zero := Ξ» x, unop_inj $ add_zero $ unop x, .. opposite.add_semigroup Ξ±, .. opposite.has_zero Ξ± } instance [add_comm_monoid Ξ±] : add_comm_monoid (opposite Ξ±) := { .. opposite.add_monoid Ξ±, .. opposite.add_comm_semigroup Ξ± } instance [has_neg Ξ±] : has_neg (opposite Ξ±) := { neg := Ξ» x, op $ -(unop x) } instance [add_group Ξ±] : add_group (opposite Ξ±) := { add_left_neg := Ξ» x, unop_inj $ add_left_neg $ unop x, .. opposite.add_monoid Ξ±, .. opposite.has_neg Ξ± } instance [add_comm_group Ξ±] : add_comm_group (opposite Ξ±) := { .. opposite.add_group Ξ±, .. opposite.add_comm_monoid Ξ± } instance [has_mul Ξ±] : has_mul (opposite Ξ±) := { mul := Ξ» x y, op (unop y * unop x) } instance [semigroup Ξ±] : semigroup (opposite Ξ±) := { mul_assoc := Ξ» x y z, unop_inj $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul Ξ± } instance [right_cancel_semigroup Ξ±] : left_cancel_semigroup (opposite Ξ±) := { mul_left_cancel := Ξ» x y z H, unop_inj $ mul_right_cancel $ op_inj H, .. opposite.semigroup Ξ± } instance [left_cancel_semigroup Ξ±] : right_cancel_semigroup (opposite Ξ±) := { mul_right_cancel := Ξ» x y z H, unop_inj $ mul_left_cancel $ op_inj H, .. opposite.semigroup Ξ± } instance [comm_semigroup Ξ±] : comm_semigroup (opposite Ξ±) := { mul_comm := Ξ» x y, unop_inj $ mul_comm (unop y) (unop x), .. opposite.semigroup Ξ± } instance [has_one Ξ±] : has_one (opposite Ξ±) := { one := op 1 } instance [monoid Ξ±] : monoid (opposite Ξ±) := { one_mul := Ξ» x, unop_inj $ mul_one $ unop x, mul_one := Ξ» x, unop_inj $ one_mul $ unop x, .. opposite.semigroup Ξ±, .. opposite.has_one Ξ± } instance [comm_monoid Ξ±] : comm_monoid (opposite Ξ±) := { .. opposite.monoid Ξ±, .. opposite.comm_semigroup Ξ± } instance [has_inv Ξ±] : has_inv (opposite Ξ±) := { inv := Ξ» x, op $ (unop x)⁻¹ } instance [group Ξ±] : group (opposite Ξ±) := { mul_left_inv := Ξ» x, unop_inj $ mul_inv_self $ unop x, .. opposite.monoid Ξ±, .. opposite.has_inv Ξ± } instance [comm_group Ξ±] : comm_group (opposite Ξ±) := { .. opposite.group Ξ±, .. opposite.comm_monoid Ξ± } instance [distrib Ξ±] : distrib (opposite Ξ±) := { left_distrib := Ξ» x y z, unop_inj $ add_mul (unop y) (unop z) (unop x), right_distrib := Ξ» x y z, unop_inj $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add Ξ±, .. opposite.has_mul Ξ± } instance [semiring Ξ±] : semiring (opposite Ξ±) := { zero_mul := Ξ» x, unop_inj $ mul_zero $ unop x, mul_zero := Ξ» x, unop_inj $ zero_mul $ unop x, .. opposite.add_comm_monoid Ξ±, .. opposite.monoid Ξ±, .. opposite.distrib Ξ± } instance [ring Ξ±] : ring (opposite Ξ±) := { .. opposite.add_comm_group Ξ±, .. opposite.monoid Ξ±, .. opposite.semiring Ξ± } instance [comm_ring Ξ±] : comm_ring (opposite Ξ±) := { .. opposite.ring Ξ±, .. opposite.comm_semigroup Ξ± } instance [zero_ne_one_class Ξ±] : zero_ne_one_class (opposite Ξ±) := { zero_ne_one := Ξ» h, zero_ne_one $ op_inj h, .. opposite.has_zero Ξ±, .. opposite.has_one Ξ± } instance [integral_domain Ξ±] : integral_domain (opposite Ξ±) := { eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» x y (H : op (_ * _) = op (0:Ξ±)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_inj H) (Ξ» hy, or.inr $ unop_inj $ hy) (Ξ» hx, or.inl $ unop_inj $ hx), .. opposite.comm_ring Ξ±, .. opposite.zero_ne_one_class Ξ± } instance [field Ξ±] : field (opposite Ξ±) := { mul_inv_cancel := Ξ» x hx, unop_inj $ inv_mul_cancel $ Ξ» hx', hx $ unop_inj hx', inv_zero := unop_inj inv_zero, .. opposite.comm_ring Ξ±, .. opposite.zero_ne_one_class Ξ±, .. opposite.has_inv Ξ± } @[simp] lemma op_zero [has_zero Ξ±] : op (0 : Ξ±) = 0 := rfl @[simp] lemma unop_zero [has_zero Ξ±] : unop (0 : Ξ±α΅’α΅–) = 0 := rfl @[simp] lemma op_one [has_one Ξ±] : op (1 : Ξ±) = 1 := rfl @[simp] lemma unop_one [has_one Ξ±] : unop (1 : Ξ±α΅’α΅–) = 1 := rfl variable {Ξ±} @[simp] lemma op_add [has_add Ξ±] (x y : Ξ±) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add Ξ±] (x y : Ξ±α΅’α΅–) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg Ξ±] (x : Ξ±) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg Ξ±] (x : Ξ±α΅’α΅–) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul Ξ±] (x y : Ξ±) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul Ξ±] (x y : Ξ±α΅’α΅–) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv Ξ±] (x : Ξ±) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv Ξ±] (x : Ξ±α΅’α΅–) : unop (x⁻¹) = (unop x)⁻¹ := rfl end opposite
2a45dea74f08af7cd0880194062107f19d3b13b8
abd85493667895c57a7507870867b28124b3998f
/src/analysis/convex/basic.lean
15c4d5b0533632365c9314076e03e50896cfb020
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
38,838
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.set.intervals.unordered_interval import data.set.intervals.image_preimage import data.complex.module import algebra.pointwise /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E Γ— ℝ | p.1 ∈ s ∧ f p.1 ≀ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ΞΉ [fintype ΞΉ]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ΞΉ β†’ ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v w x variables {E : Type u} {F : Type v} {ΞΉ : Type w} {ΞΉ' : Type x} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} open set open_locale classical local notation `I` := (Icc 0 1 : set ℝ) local attribute [instance] set.pointwise_add set.smul_set section sets /-! ### Segment -/ /-- Segments in a vector space -/ def segment (x y : E) : set E := {z : E | βˆƒ (a b : ℝ) (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1), a β€’ x + b β€’ y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ Ξ» z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, Ξ» ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x β–Έ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ Ξ» z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, Ξ» h, mem_singleton_iff.1 h β–Έ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : segment x y = (Ξ» (ΞΈ : ℝ), (1 - ΞΈ) β€’ x + ΞΈ β€’ y) '' I := set.ext $ Ξ» z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab β–Έ le_add_of_nonneg_left ha⟩, hab β–Έ hz β–Έ by simp only [add_sub_cancel]⟩, Ξ» ⟨θ, ⟨hΞΈβ‚€, hΞΈβ‚βŸ©, hz⟩, ⟨1-ΞΈ, ΞΈ, sub_nonneg.2 hθ₁, hΞΈβ‚€, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : segment x y = (Ξ» (ΞΈ : ℝ), x + ΞΈ β€’ (y - x)) '' I := by { convert segment_eq_image x y, ext ΞΈ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_imageβ‚‚ (x y : E) : segment x y = (Ξ» p:ℝ×ℝ, p.1 β€’ x + p.2 β€’ y) '' {p | 0 ≀ p.1 ∧ 0 ≀ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≀ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (Ξ» t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (Ξ» ΞΈ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (Ξ» x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ Ξ» x, mem_segment_translate a lemma segment_translate_image (a b c: E) : (Ξ»x, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c β–Έ image_preimage_eq $ add_left_surjective a /-! ### Convexity of sets -/ /-- Convexity of sets -/ def convex (s : set E) := βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ a β€’ x + b β€’ y ∈ s lemma convex_iff_forall_pos : convex s ↔ βˆ€ ⦃x y⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ a β€’ x + b β€’ y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ βˆ€ ⦃x y⦄, x ∈ s β†’ y ∈ s β†’ [x, y] βŠ† s := by simp only [convex, segment_eq_imageβ‚‚, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] βŠ† s := convex_iff_segment_subset.1 h hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ a β€’ s + b β€’ s βŠ† s := iff.intro begin rintros hA a b ha hb hab w ⟨au, ⟨u, hu, rfl⟩, bv, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (Ξ» h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_pointwise_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division -/ lemma convex_iff_div: convex s ↔ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ 0 < a + b β†’ (a/(a+b)) β€’ x + (b/(a+b)) β€’ y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (βˆ… : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := Ξ» _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := Ξ» x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : βˆ€ s ∈ S, convex s) : convex (β‹‚β‚€ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ΞΉ : Sort*} {s: ΞΉ β†’ set E} (h: βˆ€ i : ΞΉ, convex (s i)) : convex (β‹‚ i, s i) := (sInter_range s) β–Έ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex.is_linear_image (hs : convex s) {f : E β†’ F} (hf : is_linear_map ℝ f) : convex (f '' s) := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩ a b ha hb hab, exact ⟨a β€’ x + b β€’ y, hs hx hy ha hb hab, by simp only [hf.add,hf.smul]⟩ end lemma convex.linear_image (hs : convex s) (f : E β†’β‚—[ℝ] F) : convex (image f s) := hs.is_linear_image f.is_linear lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E β†’ F} (hf : is_linear_map ℝ f) : convex (preimage f s) := begin intros x y hx hy a b ha hb hab, convert hs hx hy ha hb hab, simp only [mem_preimage, hf.add, hf.smul] end lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E β†’β‚—[ℝ] F) : convex (preimage f s) := hs.is_linear_preimage f.is_linear lemma convex.neg (hs : convex s) : convex ((Ξ» z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((Ξ» z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c β€’ s) := begin rw smul_set_eq_image, exact hs.is_linear_image (is_linear_map.is_linear_map_smul c) end lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((Ξ» z, c β€’ z) ⁻¹' s) := hs.is_linear_preimage (is_linear_map.is_linear_map_smul c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw pointwise_add_eq_image, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((Ξ»x : E Γ— E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((Ξ»x, z + x) '' s) := begin convert (convex_singleton z).add hs, ext x, simp [set.mem_image, mem_pointwise_add, eq_comm] end lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((Ξ»x, z + c β€’ x) '' s) := begin convert (hs.smul c).translate z using 1, erw [smul_set_eq_image, ←image_comp] end lemma convex_real_iff {s : set ℝ} : convex s ↔ βˆ€ {x y}, x ∈ s β†’ y ∈ s β†’ Icc x y βŠ† s := begin simp only [convex_iff_segment_subset, segment_eq_Icc'], split; intros h x y hx hy, { cases le_or_lt x y with hxy hxy, { simpa [hxy] using h hx hy }, { simp [hxy] } }, { apply h; cases le_total x y; simp [*] } end lemma convex_Iio (r : ℝ) : convex (Iio r) := convex_real_iff.2 $ Ξ» x y hx hy z hz, lt_of_le_of_lt hz.2 hy lemma convex_Ioi (r : ℝ) : convex (Ioi r) := convex_real_iff.2 $ Ξ» x y hx hy z hz, lt_of_lt_of_le hx hz.1 lemma convex_Iic (r : ℝ) : convex (Iic r) := convex_real_iff.2 $ Ξ» x y hx hy z hz, le_trans hz.2 hy lemma convex_Ici (r : ℝ) : convex (Ici r) := convex_real_iff.2 $ Ξ» x y hx hy z hz, le_trans hx hz.1 lemma convex_Ioo (r : ℝ) (s : ℝ) : convex (Ioo r s) := (convex_Ioi _).inter (convex_Iio _) lemma convex_Ico (r : ℝ) (s : ℝ) : convex (Ico r s) := (convex_Ici _).inter (convex_Iio _) lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := (convex_Ioi _).inter (convex_Iic _) lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := (convex_Ici _).inter (convex_Iic _) lemma convex_segment (a b : E) : convex [a, b] := begin have : (Ξ» (t : ℝ), a + t β€’ (b - a)) = (Ξ»z : E, a + z) ∘ (Ξ»t:ℝ, t β€’ (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≀ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≀ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : β„‚ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : β„‚ | c.re ≀ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : β„‚ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : β„‚ | r ≀ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : β„‚ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : β„‚ | c.im ≀ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : β„‚ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : β„‚ | r ≀ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets section functions local notation `[`x `, ` y `]` := segment x y /-! ### Convex functions -/ /-- Convexity of functions -/ def convex_on (s : set E) (f : E β†’ ℝ) : Prop := convex s ∧ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ f (a β€’ x + b β€’ y) ≀ a * f x + b * f y variables {t : set E} {f g : E β†’ ℝ} lemma convex_on_iff_div: convex_on s f ↔ convex s ∧ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ 0 < a + b β†’ f ((a/(a+b)) β€’ x + (b/(a+b)) β€’ y) ≀ (a/(a+b)) * f x + (b/(a+b)) * f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha hab) (div_nonneg hb hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a β€’ x + b β€’ y) ≀ a * f x + b * f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt [linear_order E] (hs : convex s) (hf : βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ x < y β†’ βˆ€ ⦃a b : ℝ⦄, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ f (a β€’ x + b β€’ y) ≀ a * f x + b * f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_mul, hab, one_smul, one_mul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ β†’ ℝ} (hf : βˆ€ {x y z : ℝ}, x ∈ s β†’ z ∈ s β†’ x < y β†’ y < z β†’ (f y - f x) / (y - x) ≀ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≀ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end lemma convex_on.subset (h_convex_on : convex_on t f) (h_subset : s βŠ† t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma convex_on.add (hf : convex_on s f) (hg : convex_on s g) : convex_on s (Ξ»x, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a β€’ x + b β€’ y) + g (a β€’ x + b β€’ y) ≀ (a * f x + b * f y) + (a * g x + b * g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a * f x + a * g x + b * f y + b * g y : by linarith ... = a * (f x + g x) + b * (f y + g y) : by simp [mul_add, add_assoc] end lemma convex_on.smul {c : ℝ} (hc : 0 ≀ c) (hf : convex_on s f) : convex_on s (Ξ»x, c * f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c * f (a β€’ x + b β€’ y) ≀ c * (a * f x + b * f y) : mul_le_mul_of_nonneg_left (hf.2 hx hy ha hb hab) hc ... = a * (c * f x) + b * (c * f y) : by rw mul_add; ac_refl end lemma convex_on.le_on_segment' {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1) : f (a β€’ x + b β€’ y) ≀ max (f x) (f y) := calc f (a β€’ x + b β€’ y) ≀ a * f x + b * f y : hf.2 hx hy ha hb hab ... ≀ a * max (f x) (f y) + b * max (f x) (f y) : add_le_add (mul_le_mul_of_nonneg_left (le_max_left _ _) ha) (mul_le_mul_of_nonneg_left (le_max_right _ _) hb) ... ≀ max (f x) (f y) : by rw [←add_mul, hab, one_mul] lemma convex_on.le_on_segment (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≀ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz β–Έ hf.le_on_segment' hx hy ha hb hab lemma convex_on.convex_le (hf : convex_on s f) (r : ℝ) : convex {x ∈ s | f x ≀ r} := convex_iff_segment_subset.2 $ Ξ» x y hx hy z hz, ⟨hf.1.segment_subset hx.1 hy.1 hz, le_trans (hf.le_on_segment hx.1 hy.1 hz) $ max_le hx.2 hy.2⟩ lemma convex_on.convex_lt (hf : convex_on s f) (r : ℝ) : convex {x ∈ s | f x < r} := convex_iff_segment_subset.2 $ Ξ» x y hx hy z hz, ⟨hf.1.segment_subset hx.1 hy.1 hz, lt_of_le_of_lt (hf.le_on_segment hx.1 hy.1 hz) $ max_lt hx.2 hy.2⟩ lemma convex_on.convex_epigraph (hf : convex_on s f) : convex {p : E Γ— ℝ | p.1 ∈ s ∧ f p.1 ≀ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a β€’ x + b β€’ y) ≀ a * f x + b * f y : hf.2 hx hy ha hb hab ... ≀ a * r + b * t : add_le_add (mul_le_mul_of_nonneg_left hr ha) (mul_le_mul_of_nonneg_left ht hb) end lemma convex_on_iff_convex_epigraph : convex_on s f ↔ convex {p : E Γ— ℝ | p.1 ∈ s ∧ f p.1 ≀ p.2} := begin refine ⟨convex_on.convex_epigraph, Ξ» h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end end functions section center_mass /-- Center mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≀ w i` nor `βˆ‘ w = 1`. -/ noncomputable def finset.center_mass (t : finset ΞΉ) (w : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) : E := (t.sum w)⁻¹ β€’ (t.sum (Ξ» i, w i β€’ z i)) variables (i j : ΞΉ) (c : ℝ) (t : finset ΞΉ) (w : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) open finset lemma finset.center_mass_empty : (βˆ… : finset ΞΉ).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i β‰  j) : ({i, j} : finset ΞΉ).center_mass w z = (w i / (w i + w j)) β€’ z i + (w j / (w i + w j)) β€’ z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i βˆ‰ t) (hw : t.sum w β‰  0) : (insert i t).center_mass w z = (w i / (w i + t.sum w)) β€’ z i + (t.sum w / (w i + t.sum w)) β€’ t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm], congr' 2, { apply mul_comm }, { rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div_eq_inv] } end lemma finset.center_mass_singleton (hw : w i β‰  0) : ({i} : finset ΞΉ).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : t.sum w = 1) : t.center_mass w z = t.sum (Ξ» i, w i β€’ z i) := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (Ξ» i, c β€’ z i) = c β€’ t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ΞΉ) (t : finset ΞΉ') (ws : ΞΉ β†’ ℝ) (zs : ΞΉ β†’ E) (wt : ΞΉ' β†’ ℝ) (zt : ΞΉ' β†’ E) (hws : s.sum ws = 1) (hwt : t.sum wt = 1) (a b : ℝ) (hab : a + b = 1): a β€’ s.center_mass ws zs + b β€’ t.center_mass wt zt = (s.image sum.inl βˆͺ t.image sum.inr).center_mass (sum.elim (Ξ» i, a * ws i) (Ξ» j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr, ext i, cases i; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ΞΉ) (w₁ wβ‚‚ : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) (hw₁ : s.sum w₁ = 1) (hwβ‚‚ : s.sum wβ‚‚ = 1) (a b : ℝ) (hab : a + b = 1): a β€’ s.center_mass w₁ z + b β€’ s.center_mass wβ‚‚ z = s.center_mass (Ξ» i, a * w₁ i + b * wβ‚‚ i) z := have hw : s.sum (Ξ» i, a * w₁ i + b * wβ‚‚ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (Ξ» j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity t.sum (Ξ» j, if (i = j) then z i else 0), { congr, ext i, split_ifs, exacts [h β–Έ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ΞΉ} (ht : t βŠ† t') (h : βˆ€ i ∈ t', i βˆ‰ t β†’ w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (Ξ» i, w i β‰  0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _) $ Ξ» i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- Center mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (βˆ€ i ∈ t, 0 ≀ w i) β†’ (0 < t.sum w) β†’ (βˆ€ i ∈ t, z i ∈ s) β†’ t.center_mass w z ∈ s := begin refine finset.induction (by simp [lt_irrefl]) (Ξ» i t hi ht hβ‚€ hpos hmem, _) t, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hsβ‚€ : βˆ€ j ∈ t, 0 ≀ w j, from Ξ» j hj, hβ‚€ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : t.sum w = 0, { have ws : βˆ€ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hsβ‚€).1 hsum_t, have wz : t.sum (Ξ» j, w j β€’ z j) = 0, from sum_eq_zero (Ξ» i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hsβ‚€ _ _) _ (sum_nonneg hsβ‚€) hpos, { exact lt_of_le_of_ne (sum_nonneg hsβ‚€) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact hβ‚€ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (hβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (h₁ : t.sum w = 1) (hz : βˆ€ i ∈ t, z i ∈ s) : t.sum (Ξ» i, w i β€’ z i) ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem hβ‚€ (h₁.symm β–Έ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (βˆ€ (t : finset E) (w : E β†’ ℝ), (βˆ€ i ∈ t, 0 ≀ w i) β†’ t.sum w = 1 β†’ (βˆ€ x ∈ t, x ∈ s) β†’ t.sum (Ξ»x, w x β€’ x) ∈ s ) := begin refine ⟨λ hs t w hwβ‚€ hw₁ hts, hs.sum_mem hwβ‚€ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (Ξ» z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E β†’ ℝ} (hf : convex_on s f) (hβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hpos : 0 < t.sum w) (hmem : βˆ€ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≀ t.center_mass w (f ∘ z) := begin have hmem' : βˆ€ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E Γ— ℝ | p.1 ∈ s ∧ f p.1 ≀ p.2}, from Ξ» i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem hβ‚€ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E β†’ ℝ} (hf : convex_on s f) (hβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (h₁ : t.sum w = 1) (hmem : βˆ€ i ∈ t, z i ∈ s) : f (t.sum (Ξ» i, w i β€’ z i)) ≀ t.sum (Ξ» i, w i * (f (z i))) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le hβ‚€ (h₁.symm β–Έ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center mass of some points `z i ∈ s`, then for some `i` we have `y ≀ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E β†’ ℝ} (h : convex_on s f) (hwβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hws : 0 < t.sum w) (hz : βˆ€ i ∈ t, z i ∈ s) : βˆƒ i ∈ t, f (t.center_mass w z) ≀ f (z i) := begin set y := t.center_mass w z, have : f y ≀ t.center_mass w (f ∘ z) := h.map_center_mass_le hwβ‚€ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : βˆƒ i ∈ t.filter (Ξ» i, w i β‰  0), f y * w i ≀ w i β€’ (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hwβ‚€ i hi.1) hi.2.symm end end center_mass section convex_hull variable {t : set E} /-- Convex hull of a set `s` is the minimal convex set that includes `s` -/ def convex_hull (s : set E) : set E := β‹‚ (t : set E) (hst : s βŠ† t) (ht : convex t), t variable (s) lemma subset_convex_hull : s βŠ† convex_hull s := set.subset_Inter $ Ξ» t, set.subset_Inter $ Ξ» hst, set.subset_Inter $ Ξ» ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ Ξ» t, convex_Inter $ Ξ» ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s βŠ† t) (ht : convex t) : convex_hull s βŠ† t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s βŠ† t) : convex_hull s βŠ† convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma is_linear_map.image_convex_hull {f : E β†’ F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E β†’β‚—[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ΞΉ) {w : ΞΉ β†’ ℝ} (hwβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hws : 0 < t.sum w) {z : ΞΉ β†’ E} (hz : βˆ€ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hwβ‚€ hws (Ξ» i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t βŠ† s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | βˆƒ (ΞΉ : Type u') (t : finset ΞΉ) (w : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) (hwβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hw₁ : t.sum w = 1) (hz : βˆ€ i ∈ t, z i ∈ s) , t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, Ξ» _, 1, Ξ» _, x, Ξ» _ _, zero_le_one, finset.sum_singleton, Ξ» _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwxβ‚€, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwyβ‚€, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwxβ‚€, hwyβ‚€] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hwβ‚€, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hwβ‚€ (hw₁.symm β–Έ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E β†’ ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : βˆƒ y ∈ s, f x ≀ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hwβ‚€, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hwβ‚€ (hw₁.symm β–Έ zero_lt_one) (Ξ» i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | βˆƒ (w : E β†’ ℝ) (hwβ‚€ : βˆ€ y ∈ s, 0 ≀ w y) (hw₁ : s.sum w = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwxβ‚€, hwx₁, rfl⟩ ⟨wy, hwyβ‚€, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwxβ‚€, hwyβ‚€], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hwβ‚€, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (Ξ» x hx, hwβ‚€ _ hx) (hw₁.symm β–Έ zero_lt_one) (Ξ» x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | βˆƒ (w : E β†’ ℝ) (hwβ‚€ : βˆ€ y ∈ s, 0 ≀ w y) (hw₁ : hs.to_finset.sum w = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t βŠ† s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hwβ‚€, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hwβ‚€, { simp only [hw₁, zero_lt_one] }, { exact Ξ» i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (Ξ» i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E β†’ F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E β†’β‚—[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ΞΉ) [fintype ΞΉ] {f : ΞΉ β†’ ℝ} /-- Standard simplex in the space of functions `ΞΉ β†’ ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ΞΉ : Type*) [fintype ΞΉ] : set (ΞΉ β†’ ℝ) := { f | (βˆ€ x, 0 ≀ f x) ∧ finset.univ.sum f = 1 } lemma std_simplex_eq_inter : std_simplex ΞΉ = (β‹‚ x, {f | 0 ≀ f x}) ∩ {f | finset.univ.sum f = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ΞΉ) := begin refine Ξ» f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ΞΉ} lemma ite_eq_mem_std_simplex (i : ΞΉ) : (Ξ» j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ΞΉ := ⟨λ j, by simp only []; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)] ⟩ /-- `std_simplex ΞΉ` is the convex hull of the canonical basis in `ΞΉ β†’ ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ Ξ»(i j:ΞΉ), if i = j then (1:ℝ) else 0) = std_simplex ΞΉ := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ΞΉ)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hwβ‚€, hwβ‚βŸ©, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (Ξ» i hi, hwβ‚€ i) (hw₁.symm β–Έ zero_lt_one) (Ξ» i hi, mem_range_self i) } end variable {ΞΉ} /-- Convex hull of a finite set is the image of the standard simplex in `s β†’ ℝ` under the linear map sending each function `w` to `s.sum (Ξ» x, w x β€’ x)`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s β†’ ℝ) β†’β‚—[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = (⇑((@finset.univ _ hs.fintype).sum (Ξ» x, (@linear_map.proj ℝ s _ (Ξ» i, ℝ) _ _ x).smul_right x.1))) '' (@std_simplex _ hs.fintype) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← range_comp, (∘)], apply congr_arg, convert (subtype.range_val s).symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ΞΉ` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ΞΉ) (x) : f x ∈ I := ⟨hf.1 x, hf.2 β–Έ finset.single_le_sum (Ξ» y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
c4b830a89ac040bc3398e19c33341b357f6289ab
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/real/ereal_auto.lean
73f2f02a0a95b4ba41d2475f66a09ac43065384a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,495
lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.real.basic import Mathlib.PostPort namespace Mathlib /-! # The extended reals [-∞, ∞]. This file defines `ereal`, the real numbers together with a top and bottom element, referred to as ⊀ and βŠ₯. It is implemented as `with_top (with_bot ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An addition is derived, but `ereal` is not even a monoid (there is no identity). `ereal` is a `complete_lattice`; this is now deduced by type class inference from the fact that `with_top (with_bot L)` is a complete lattice if `L` is a conditionally complete lattice. ## Tags real, ereal, complete lattice ## TODO abs : ereal β†’ ennreal In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞) and then prove whatever bits of the ordered ring/field axioms still hold. They also do some limits stuff (liminf/limsup etc). See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html -/ /-- ereal : The type `[-∞, ∞]` -/ def ereal := with_top (with_bot ℝ) namespace ereal protected instance has_coe : has_coe ℝ ereal := has_coe.mk (some ∘ some) @[simp] protected theorem coe_real_le {x : ℝ} {y : ℝ} : ↑x ≀ ↑y ↔ x ≀ y := sorry @[simp] protected theorem coe_real_lt {x : ℝ} {y : ℝ} : ↑x < ↑y ↔ x < y := sorry @[simp] protected theorem coe_real_inj' {x : ℝ} {y : ℝ} : ↑x = ↑y ↔ x = y := sorry protected instance has_zero : HasZero ereal := { zero := ↑0 } protected instance inhabited : Inhabited ereal := { default := 0 } /-! ### Negation -/ /-- negation on ereal -/ protected def neg : ereal β†’ ereal := sorry protected instance has_neg : Neg ereal := { neg := ereal.neg } protected theorem neg_def (x : ℝ) : ↑(-x) = -↑x := rfl /-- - -a = a on ereal -/ protected theorem neg_neg (a : ereal) : --a = a := sorry theorem neg_inj (a : ereal) (b : ereal) (h : -a = -b) : a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (Eq.symm (ereal.neg_neg a)))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --a = b)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl ( --b = b)) (ereal.neg_neg b))) (Eq.refl b))) /-- Even though ereal is not an additive group, -a = b ↔ -b = a still holds -/ theorem neg_eq_iff_neg_eq {a : ereal} {b : ereal} : -a = b ↔ -b = a := { mp := fun (h : -a = b) => eq.mpr (id (Eq._oldrec (Eq.refl (-b = a)) (Eq.symm h))) (ereal.neg_neg a), mpr := fun (h : -b = a) => eq.mpr (id (Eq._oldrec (Eq.refl (-a = b)) (Eq.symm h))) (ereal.neg_neg b) } /-- if -a ≀ b then -b ≀ a on ereal -/ protected theorem neg_le_of_neg_le {a : ereal} {b : ereal} (h : -a ≀ b) : -b ≀ a := sorry /-- -a ≀ b ↔ -b ≀ a on ereal-/ protected theorem neg_le {a : ereal} {b : ereal} : -a ≀ b ↔ -b ≀ a := { mp := ereal.neg_le_of_neg_le, mpr := ereal.neg_le_of_neg_le } /-- a ≀ -b β†’ b ≀ -a on ereal -/ theorem le_neg_of_le_neg {a : ereal} {b : ereal} (h : a ≀ -b) : b ≀ -a := eq.mpr (id (Eq._oldrec (Eq.refl (b ≀ -a)) (Eq.symm (ereal.neg_neg b)))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --b ≀ -a)) (propext ereal.neg_le))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --a ≀ -b)) (ereal.neg_neg a))) h)) end Mathlib
86634bd8da954f5597eaa3eaff6c790fa925ac89
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/pnat/basic.lean
7265ebe1c5cbedaeae67d470105e1bc7a52329a4
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
14,799
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import data.nat.basic import algebra.group_power.basic /-! # The positive natural numbers This file defines the type `β„•+` or `pnat`, the subtype of natural numbers that are positive. -/ /-- `β„•+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `β„•+` is the same as `β„•` because the proof is not stored. -/ def pnat := {n : β„• // 0 < n} notation `β„•+` := pnat instance coe_pnat_nat : has_coe β„•+ β„• := ⟨subtype.val⟩ instance : has_repr β„•+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `β„•+`, as a `β„•`. -/ def pnat.nat_pred (i : β„•+) : β„• := i - 1 namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : β„•) (h : 0 < n . tactic.exact_dec_trivial) : β„•+ := ⟨n, h⟩ /-- Write a successor as an element of `β„•+`. -/ def succ_pnat (n : β„•) : β„•+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : β„•) : (succ_pnat n : β„•) = succ n := rfl theorem succ_pnat_inj {n m : β„•} : succ_pnat n = succ_pnat m β†’ n = m := Ξ» h, by { let h' := congr_arg (coe : β„•+ β†’ β„•) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : β„•) : β„•+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : βˆ€ (n : β„•), ((to_pnat' n) : β„•) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on β„•+ induced by similar structures on β„•. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq β„•+ := Ξ» (a b : β„•+), by apply_instance instance : linear_order β„•+ := subtype.linear_order _ @[simp] lemma mk_le_mk (n k : β„•) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : β„•+) ≀ ⟨k, hk⟩ ↔ n ≀ k := iff.rfl @[simp] lemma mk_lt_mk (n k : β„•) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : β„•+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : β„•+) : (n:β„•) ≀ k ↔ n ≀ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : β„•+) : (n:β„•) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : β„•+) : 0 < (n : β„•) := n.2 theorem eq {m n : β„•+} : (m : β„•) = n β†’ m = n := subtype.eq @[simp] lemma coe_inj {m n : β„•+} : (m : β„•) = n ↔ m = n := set_coe.ext_iff lemma coe_injective : function.injective (coe : β„•+ β†’ β„•) := subtype.coe_injective @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : β„•+) : β„•) = n := rfl instance : has_add β„•+ := ⟨λ a b, ⟨(a + b : β„•), add_pos a.pos b.pos⟩⟩ instance : add_comm_semigroup β„•+ := coe_injective.add_comm_semigroup coe (Ξ» _ _, rfl) @[simp] theorem add_coe (m n : β„•+) : ((m + n : β„•+) : β„•) = m + n := rfl instance coe_add_hom : is_add_hom (coe : β„•+ β†’ β„•) := ⟨add_coe⟩ instance : add_left_cancel_semigroup β„•+ := coe_injective.add_left_cancel_semigroup coe (Ξ» _ _, rfl) instance : add_right_cancel_semigroup β„•+ := coe_injective.add_right_cancel_semigroup coe (Ξ» _ _, rfl) @[simp] theorem ne_zero (n : β„•+) : (n : β„•) β‰  0 := ne_of_gt n.2 theorem to_pnat'_coe {n : β„•} : 0 < n β†’ (n.to_pnat' : β„•) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : β„•+) : (n : β„•).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : has_mul β„•+ := ⟨λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩⟩ instance : has_one β„•+ := ⟨succ_pnat 0⟩ instance : comm_monoid β„•+ := coe_injective.comm_monoid coe rfl (Ξ» _ _, rfl) theorem lt_add_one_iff : βˆ€ {a b : β„•+}, a < b + 1 ↔ a ≀ b := Ξ» a b, nat.lt_add_one_iff theorem add_one_le_iff : βˆ€ {a b : β„•+}, a + 1 ≀ b ↔ a < b := Ξ» a b, nat.add_one_le_iff @[simp] lemma one_le (n : β„•+) : (1 : β„•+) ≀ n := n.2 instance : order_bot β„•+ := { bot := 1, bot_le := Ξ» a, a.property, .. pnat.linear_order } @[simp] lemma bot_eq_zero : (βŠ₯ : β„•+) = 1 := rfl instance : inhabited β„•+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : β„•+) = (1 : β„•+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : β„•+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : β„•+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : β„•+) = (bit1 ⟨n, k⟩ : β„•+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `pnat` -- into the corresponding inequalities in `nat`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : β„•+) : (bit0 n) ≀ (bit0 m) ↔ (bit0 (n : β„•)) ≀ (bit0 (m : β„•)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : β„•+) : (bit0 n) ≀ (bit1 m) ↔ (bit0 (n : β„•)) ≀ (bit1 (m : β„•)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : β„•+) : (bit1 n) ≀ (bit0 m) ↔ (bit1 (n : β„•)) ≀ (bit0 (m : β„•)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : β„•+) : (bit1 n) ≀ (bit1 m) ↔ (bit1 (n : β„•)) ≀ (bit1 (m : β„•)) := iff.rfl @[simp] theorem one_coe : ((1 : β„•+) : β„•) = 1 := rfl @[simp] theorem mul_coe (m n : β„•+) : ((m * n : β„•+) : β„•) = m * n := rfl instance coe_mul_hom : is_monoid_hom (coe : β„•+ β†’ β„•) := {map_one := one_coe, map_mul := mul_coe} @[simp] lemma coe_eq_one_iff {m : β„•+} : (m : β„•) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma coe_bit0 (a : β„•+) : ((bit0 a : β„•+) : β„•) = bit0 (a : β„•) := rfl @[simp] lemma coe_bit1 (a : β„•+) : ((bit1 a : β„•+) : β„•) = bit1 (a : β„•) := rfl @[simp] theorem pow_coe (m : β„•+) (n : β„•) : ((m ^ n : β„•+) : β„•) = (m : β„•) ^ n := by induction n with n ih; [refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]] instance : ordered_cancel_comm_monoid β„•+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, mul_left_cancel := Ξ» a b c h, by { replace h := congr_arg (coe : β„•+ β†’ β„•) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. pnat.comm_monoid, .. pnat.linear_order } instance : distrib β„•+ := coe_injective.distrib coe (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≀ b. -/ instance : has_sub β„•+ := ⟨λ a b, to_pnat' (a - b : β„•)⟩ theorem sub_coe (a b : β„•+) : ((a - b : β„•+) : β„•) = ite (b < a) (a - b : β„•) 1 := begin change ((to_pnat' ((a : β„•) - (b : β„•)) : β„•)) = ite ((a : β„•) > (b : β„•)) ((a : β„•) - (b : β„•)) 1, split_ifs with h, { exact to_pnat'_coe (nat.sub_pos_of_lt h) }, { rw [nat.sub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl } end theorem add_sub_of_lt {a b : β„•+} : a < b β†’ a + (b - a) = b := Ξ» h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact nat.add_sub_of_le (le_of_lt h) } instance : has_well_founded β„•+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `pnat`. -/ lemma strong_induction_on {p : pnat β†’ Prop} : βˆ€ (n : pnat) (h : βˆ€ k, (βˆ€ m, m < k β†’ p m) β†’ p k), p n | n := Ξ» IH, IH _ (Ξ» a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- If `(n : pnat)` is different from `1`, then it is the successor of some `(k : pnat)`. -/ lemma exists_eq_succ_of_ne_one : βˆ€ {n : pnat} (h1 : n β‰  1), βˆƒ (k : pnat), n = k + 1 | ⟨1, _⟩ h1 := false.elim $ h1 rfl | ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩ lemma case_strong_induction_on {p : pnat β†’ Prop} (a : pnat) (hz : p 1) (hi : βˆ€ n, (βˆ€ m, m ≀ n β†’ p m) β†’ p (n + 1)) : p a := begin apply strong_induction_on a, intros k hk, by_cases h1 : k = 1, { rwa h1 }, obtain ⟨b, rfl⟩ := exists_eq_succ_of_ne_one h1, simp only [lt_add_one_iff] at hk, exact hi b hk end /-- An induction principle for `pnat`: it takes values in `Sort*`, so it applies also to Types, not only to `Prop`. -/ @[elab_as_eliminator] def rec_on (n : pnat) {p : pnat β†’ Sort*} (p1 : p 1) (hp : βˆ€ n, p n β†’ p (n + 1)) : p n := begin rcases n with ⟨n, h⟩, induction n with n IH, { exact absurd h dec_trivial }, { cases n with n, { exact p1 }, { exact hp _ (IH n.succ_pos) } } end @[simp] theorem rec_on_one {p} (p1 hp) : @pnat.rec_on 1 p p1 hp = p1 := rfl @[simp] theorem rec_on_succ (n : pnat) {p : pnat β†’ Sort*} (p1 hp) : @pnat.rec_on (n + 1) p p1 hp = hp n (@pnat.rec_on n p p1 hp) := by { cases n with n h, cases n; [exact absurd h dec_trivial, refl] } /-- We define `m % k` and `m / k` in the same way as for `β„•` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : β„•+ β†’ β„• β†’ β„• β†’ β„•+ Γ— β„• | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : βˆ€ (k : β„•+) (r q : β„•) (h : Β¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : β„•) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : β„•) + (k : β„•) * (q + 1).pred = 0 + (k : β„•) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `β„•` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : β„•+) : β„•+ Γ— β„• := mod_div_aux k ((m : β„•) % (k : β„•)) ((m : β„•) / (k : β„•)) /-- We define `m % k` in the same way as for `β„•` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : β„•+) : β„•+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `β„•` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : β„•+) : β„• := (mod_div m k).2 theorem mod_add_div (m k : β„•+) : ((mod m k) + k * (div m k) : β„•) = m := begin let hβ‚€ := nat.mod_add_div (m : β„•) (k : β„•), have : Β¬ ((m : β„•) % (k : β„•) = 0 ∧ (m : β„•) / (k : β„•) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at hβ‚€, exact (m.ne_zero hβ‚€.symm).elim }, have := mod_div_aux_spec k ((m : β„•) % (k : β„•)) ((m : β„•) / (k : β„•)) this, exact (this.trans hβ‚€), end theorem div_add_mod (m k : β„•+) : (k * (div m k) + mod m k : β„•) = m := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : β„•+) : ((mod m k) + (div m k) * k : β„•) = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : β„•+) : ((div m k) * k + mod m k : β„•) = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_coe (m k : β„•+) : ((mod m k) : β„•) = ite ((m : β„•) % (k : β„•) = 0) (k : β„•) ((m : β„•) % (k : β„•)) := begin dsimp [mod, mod_div], cases (m : β„•) % (k : β„•), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : β„•+) : ((div m k) : β„•) = ite ((m : β„•) % (k : β„•) = 0) ((m : β„•) / (k : β„•)).pred ((m : β„•) / (k : β„•)) := begin dsimp [div, mod_div], cases (m : β„•) % (k : β„•), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : β„•+) : mod m k ≀ m ∧ mod m k ≀ k := begin change ((mod m k) : β„•) ≀ (m : β„•) ∧ ((mod m k) : β„•) ≀ (k : β„•), rw [mod_coe], split_ifs, { have hm : (m : β„•) > 0 := m.pos, rw [← nat.mod_add_div (m : β„•) (k : β„•), h, zero_add] at hm ⊒, by_cases h' : ((m : β„•) / (k : β„•)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : β„•) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : β„•)⟩ } }, { exact ⟨nat.mod_le (m : β„•) (k : β„•), le_of_lt (nat.mod_lt (m : β„•) k.pos)⟩ } end theorem dvd_iff {k m : β„•+} : k ∣ m ↔ (k : β„•) ∣ (m : β„•) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : β„•+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : β„•) % (k : β„•) = 0, { exact h'}, { replace h : ((mod m k) : β„•) = (k : β„•) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact (ne_of_lt (nat.mod_lt (m : β„•) k.pos) h).elim } } end lemma le_of_dvd {m n : β„•+} : m ∣ n β†’ m ≀ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : β„•+) : β„•+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : β„•+} (h : k ∣ m) : k * (div_exact m k) = m := begin apply eq, rw [mul_coe], change (k : β„•) * (div m k).succ = m, rw [← div_add_mod m k, dvd_iff'.mp h, nat.mul_succ] end theorem dvd_antisymm {m n : β„•+} : m ∣ n β†’ n ∣ m β†’ m = n := Ξ» hmn hnm, le_antisymm (le_of_dvd hmn) (le_of_dvd hnm) theorem dvd_one_iff (n : β„•+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), Ξ» h, h.symm β–Έ (dvd_refl 1)⟩ lemma pos_of_div_pos {n : β„•+} {a : β„•} (h : a ∣ n) : 0 < a := begin apply pos_iff_ne_zero.2, intro hzero, rw hzero at h, exact pnat.ne_zero n (eq_zero_of_zero_dvd h) end end pnat section can_lift instance nat.can_lift_pnat : can_lift β„• β„•+ := ⟨coe, Ξ» n, 0 < n, Ξ» n hn, ⟨nat.to_pnat' n, pnat.to_pnat'_coe hn⟩⟩ instance int.can_lift_pnat : can_lift β„€ β„•+ := ⟨coe, Ξ» n, 0 < n, Ξ» n hn, ⟨nat.to_pnat' (int.nat_abs n), by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero (ne_of_gt hn)), int.nat_abs_of_nonneg hn.le]⟩⟩ end can_lift
33234b0557664dc31b76fdc36f538d81cdae28c2
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Attributes.lean
91256bfa081fbf1914e5393d70bf038fa5dfab04
[ "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
17,274
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.Syntax import Lean.CoreM import Lean.ResolveName namespace Lean inductive AttributeApplicationTime := | afterTypeChecking | afterCompilation | beforeElaboration def AttributeApplicationTime.beq : AttributeApplicationTime β†’ AttributeApplicationTime β†’ Bool | AttributeApplicationTime.afterTypeChecking, AttributeApplicationTime.afterTypeChecking => true | AttributeApplicationTime.afterCompilation, AttributeApplicationTime.afterCompilation => true | AttributeApplicationTime.beforeElaboration, AttributeApplicationTime.beforeElaboration => true | _, _ => false instance : BEq AttributeApplicationTime := ⟨AttributeApplicationTime.beq⟩ abbrev AttrM := CoreM instance : MonadLift ImportM AttrM := { monadLift := fun x => do liftM (m := IO) (x { env := (← getEnv), opts := (← getOptions) }) } structure AttributeImplCore := (name : Name) (descr : String) (applicationTime := AttributeApplicationTime.afterTypeChecking) structure AttributeImpl extends AttributeImplCore := (add (decl : Name) (args : Syntax) (persistent : Bool) : AttrM Unit) instance : Inhabited AttributeImpl := ⟨{ name := arbitrary, descr := arbitrary, add := fun env _ _ _ => pure () }⟩ open Std (PersistentHashMap) builtin_initialize attributeMapRef : IO.Ref (PersistentHashMap Name AttributeImpl) ← IO.mkRef {} /- Low level attribute registration function. -/ def registerBuiltinAttribute (attr : AttributeImpl) : IO Unit := do let m ← attributeMapRef.get if m.contains attr.name then throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attr.name ++ "' has already been used")) unless (← IO.initializing) do throw (IO.userError "failed to register attribute, attributes can only be registered during initialization") attributeMapRef.modify fun m => m.insert attr.name attr abbrev AttributeImplBuilder := List DataValue β†’ Except String AttributeImpl abbrev AttributeImplBuilderTable := Std.HashMap Name AttributeImplBuilder builtin_initialize attributeImplBuilderTableRef : IO.Ref AttributeImplBuilderTable ← IO.mkRef {} def registerAttributeImplBuilder (builderId : Name) (builder : AttributeImplBuilder) : IO Unit := do let table ← attributeImplBuilderTableRef.get if table.contains builderId then throw (IO.userError ("attribute implementation builder '" ++ toString builderId ++ "' has already been declared")) attributeImplBuilderTableRef.modify fun table => table.insert builderId builder def mkAttributeImplOfBuilder (builderId : Name) (args : List DataValue) : IO AttributeImpl := do let table ← attributeImplBuilderTableRef.get match table.find? builderId with | none => throw (IO.userError ("unknown attribute implementation builder '" ++ toString builderId ++ "'")) | some builder => IO.ofExcept $ builder args inductive AttributeExtensionOLeanEntry := | decl (declName : Name) -- `declName` has type `AttributeImpl` | builder (builderId : Name) (args : List DataValue) structure AttributeExtensionState := (newEntries : List AttributeExtensionOLeanEntry := []) (map : PersistentHashMap Name AttributeImpl) abbrev AttributeExtension := PersistentEnvExtension AttributeExtensionOLeanEntry (AttributeExtensionOLeanEntry Γ— AttributeImpl) AttributeExtensionState instance : Inhabited AttributeExtensionState := ⟨{ map := {} }⟩ private def AttributeExtension.mkInitial : IO AttributeExtensionState := do let map ← attributeMapRef.get pure { map := map } unsafe def mkAttributeImplOfConstantUnsafe (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl := match env.find? declName with | none => throw ("unknow constant '" ++ toString declName ++ "'") | some info => match info.type with | Expr.const `Lean.AttributeImpl _ _ => env.evalConst AttributeImpl opts declName | _ => throw ("unexpected attribute implementation type at '" ++ toString declName ++ "' (`AttributeImpl` expected") @[implementedBy mkAttributeImplOfConstantUnsafe] constant mkAttributeImplOfConstant (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl def mkAttributeImplOfEntry (env : Environment) (opts : Options) (e : AttributeExtensionOLeanEntry) : IO AttributeImpl := match e with | AttributeExtensionOLeanEntry.decl declName => IO.ofExcept $ mkAttributeImplOfConstant env opts declName | AttributeExtensionOLeanEntry.builder builderId args => mkAttributeImplOfBuilder builderId args private def AttributeExtension.addImported (es : Array (Array AttributeExtensionOLeanEntry)) : ImportM AttributeExtensionState := do let ctx ← read let map ← attributeMapRef.get let map ← es.foldlM (fun map entries => entries.foldlM (fun (map : PersistentHashMap Name AttributeImpl) entry => do let attrImpl ← liftM $ mkAttributeImplOfEntry ctx.env ctx.opts entry pure $ map.insert attrImpl.name attrImpl) map) map pure { map := map } private def addAttrEntry (s : AttributeExtensionState) (e : AttributeExtensionOLeanEntry Γ— AttributeImpl) : AttributeExtensionState := { s with map := s.map.insert e.2.name e.2, newEntries := e.1 :: s.newEntries } builtin_initialize attributeExtension : AttributeExtension ← registerPersistentEnvExtension { name := `attrExt, mkInitial := AttributeExtension.mkInitial, addImportedFn := AttributeExtension.addImported, addEntryFn := addAttrEntry, exportEntriesFn := fun s => s.newEntries.reverse.toArray, statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length } /- Return true iff `n` is the name of a registered attribute. -/ @[export lean_is_attribute] def isBuiltinAttribute (n : Name) : IO Bool := do let m ← attributeMapRef.get; pure (m.contains n) /- Return the name of all registered attributes. -/ def getBuiltinAttributeNames : IO (List Name) := do let m ← attributeMapRef.get; pure $ m.foldl (fun r n _ => n::r) [] def getBuiltinAttributeImpl (attrName : Name) : IO AttributeImpl := do let m ← attributeMapRef.get match m.find? attrName with | some attr => pure attr | none => throw (IO.userError ("unknown attribute '" ++ toString attrName ++ "'")) @[export lean_attribute_application_time] def getBuiltinAttributeApplicationTime (n : Name) : IO AttributeApplicationTime := do let attr ← getBuiltinAttributeImpl n pure attr.applicationTime def isAttribute (env : Environment) (attrName : Name) : Bool := (attributeExtension.getState env).map.contains attrName def getAttributeNames (env : Environment) : List Name := let m := (attributeExtension.getState env).map m.foldl (fun r n _ => n::r) [] def getAttributeImpl (env : Environment) (attrName : Name) : Except String AttributeImpl := let m := (attributeExtension.getState env).map match m.find? attrName with | some attr => pure attr | none => throw ("unknown attribute '" ++ toString attrName ++ "'") def registerAttributeOfDecl (env : Environment) (opts : Options) (attrDeclName : Name) : Except String Environment := do let attrImpl ← mkAttributeImplOfConstant env opts attrDeclName if isAttribute env attrImpl.name then throw ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used") else pure $ attributeExtension.addEntry env (AttributeExtensionOLeanEntry.decl attrDeclName, attrImpl) def registerAttributeOfBuilder (env : Environment) (builderId : Name) (args : List DataValue) : IO Environment := do let attrImpl ← mkAttributeImplOfBuilder builderId args if isAttribute env attrImpl.name then throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used")) else pure $ attributeExtension.addEntry env (AttributeExtensionOLeanEntry.builder builderId args, attrImpl) def addAttribute (decl : Name) (attrName : Name) (args : Syntax) (persistent : Bool := true) : AttrM Unit := do let env ← getEnv let attr ← ofExcept $ getAttributeImpl env attrName attr.add decl args persistent /-- Tag attributes are simple and efficient. They are useful for marking declarations in the modules where they were defined. The startup cost for this kind of attribute is very small since `addImportedFn` is a constant function. They provide the predicate `tagAttr.hasTag env decl` which returns true iff declaration `decl` is tagged in the environment `env`. -/ structure TagAttribute := (attr : AttributeImpl) (ext : PersistentEnvExtension Name Name NameSet) def registerTagAttribute (name : Name) (descr : String) (validate : Name β†’ AttrM Unit := fun _ => pure ()) : IO TagAttribute := do let ext : PersistentEnvExtension Name Name NameSet ← registerPersistentEnvExtension { name := name, mkInitial := pure {}, addImportedFn := fun _ _ => pure {}, addEntryFn := fun (s : NameSet) n => s.insert n, exportEntriesFn := fun es => let r : Array Name := es.fold (fun a e => a.push e) #[] r.qsort Name.quickLt, statsFn := fun s => "tag attribute" ++ Format.line ++ "number of local entries: " ++ format s.size } let attrImpl : AttributeImpl := { name := name, descr := descr, add := fun decl args persistent => do if args.hasArgs then throwError! "invalid attribute '{name}', unexpected argument" unless persistent do throwError! "invalid attribute '{name}', must be persistent" let env ← getEnv unless (env.getModuleIdxFor? decl).isNone do throwError! "invalid attribute '{name}', declaration is in an imported module" validate decl let env ← getEnv setEnv $ ext.addEntry env decl } registerBuiltinAttribute attrImpl pure { attr := attrImpl, ext := ext } namespace TagAttribute instance : Inhabited TagAttribute := ⟨{ attr := arbitrary, ext := arbitrary }⟩ def hasTag (attr : TagAttribute) (env : Environment) (decl : Name) : Bool := match env.getModuleIdxFor? decl with | some modIdx => (attr.ext.getModuleEntries env modIdx).binSearchContains decl Name.quickLt | none => (attr.ext.getState env).contains decl end TagAttribute /-- A `TagAttribute` variant where we can attach parameters to attributes. It is slightly more expensive and consumes a little bit more memory than `TagAttribute`. They provide the function `pAttr.getParam env decl` which returns `some p` iff declaration `decl` contains the attribute `pAttr` with parameter `p`. -/ structure ParametricAttribute (Ξ± : Type) := (attr : AttributeImpl) (ext : PersistentEnvExtension (Name Γ— Ξ±) (Name Γ— Ξ±) (NameMap Ξ±)) structure ParametricAttributeImpl (Ξ± : Type) extends AttributeImplCore := (getParam : Name β†’ Syntax β†’ AttrM Ξ±) (afterSet : Name β†’ Ξ± β†’ AttrM Unit := fun env _ _ => pure ()) (afterImport : Array (Array (Name Γ— Ξ±)) β†’ ImportM Unit := fun _ => pure ()) def registerParametricAttribute {Ξ± : Type} [Inhabited Ξ±] (impl : ParametricAttributeImpl Ξ±) : IO (ParametricAttribute Ξ±) := do let ext : PersistentEnvExtension (Name Γ— Ξ±) (Name Γ— Ξ±) (NameMap Ξ±) ← registerPersistentEnvExtension { name := impl.name, mkInitial := pure {}, addImportedFn := fun s => impl.afterImport s *> pure {}, addEntryFn := fun (s : NameMap Ξ±) (p : Name Γ— Ξ±) => s.insert p.1 p.2, exportEntriesFn := fun m => let r : Array (Name Γ— Ξ±) := m.fold (fun a n p => a.push (n, p)) #[] r.qsort (fun a b => Name.quickLt a.1 b.1), statsFn := fun s => "parametric attribute" ++ Format.line ++ "number of local entries: " ++ format s.size } let attrImpl : AttributeImpl := { impl with add := fun decl args persistent => do unless persistent do throwError! "invalid attribute '{impl.name}', must be persistent" let env ← getEnv unless (env.getModuleIdxFor? decl).isNone do throwError! "invalid attribute '{impl.name}', declaration is in an imported module" let val ← impl.getParam decl args let env' := ext.addEntry env (decl, val) setEnv env' try impl.afterSet decl val catch _ => setEnv env } registerBuiltinAttribute attrImpl pure { attr := attrImpl, ext := ext } namespace ParametricAttribute instance {Ξ± : Type} : Inhabited (ParametricAttribute Ξ±) := ⟨{attr := arbitrary, ext := arbitrary }⟩ def getParam {Ξ± : Type} [Inhabited Ξ±] (attr : ParametricAttribute Ξ±) (env : Environment) (decl : Name) : Option Ξ± := match env.getModuleIdxFor? decl with | some modIdx => match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some (_, val) => some val | none => none | none => (attr.ext.getState env).find? decl def setParam {Ξ± : Type} (attr : ParametricAttribute Ξ±) (env : Environment) (decl : Name) (param : Ξ±) : Except String Environment := if (env.getModuleIdxFor? decl).isSome then Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, declaration is in an imported module") else if ((attr.ext.getState env).find? decl).isSome then Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, attribute has already been set") else Except.ok (attr.ext.addEntry env (decl, param)) end ParametricAttribute /- Given a list `[a₁, ..., a_n]` of elements of type `Ξ±`, `EnumAttributes` provides an attribute `Attr_i` for associating a value `a_i` with an declaration. `Ξ±` is usually an enumeration type. Note that whenever we register an `EnumAttributes`, we create `n` attributes, but only one environment extension. -/ structure EnumAttributes (Ξ± : Type) := (attrs : List AttributeImpl) (ext : PersistentEnvExtension (Name Γ— Ξ±) (Name Γ— Ξ±) (NameMap Ξ±)) def registerEnumAttributes {Ξ± : Type} [Inhabited Ξ±] (extName : Name) (attrDescrs : List (Name Γ— String Γ— Ξ±)) (validate : Name β†’ Ξ± β†’ AttrM Unit := fun _ _ => pure ()) (applicationTime := AttributeApplicationTime.afterTypeChecking) : IO (EnumAttributes Ξ±) := do let ext : PersistentEnvExtension (Name Γ— Ξ±) (Name Γ— Ξ±) (NameMap Ξ±) ← registerPersistentEnvExtension { name := extName, mkInitial := pure {}, addImportedFn := fun _ _ => pure {}, addEntryFn := fun (s : NameMap Ξ±) (p : Name Γ— Ξ±) => s.insert p.1 p.2, exportEntriesFn := fun m => let r : Array (Name Γ— Ξ±) := m.fold (fun a n p => a.push (n, p)) #[] r.qsort (fun a b => Name.quickLt a.1 b.1), statsFn := fun s => "enumeration attribute extension" ++ Format.line ++ "number of local entries: " ++ format s.size } let attrs := attrDescrs.map fun (name, descr, val) => { name := name, descr := descr, add := fun decl args persistent => do unless persistent do throwError! "invalid attribute '{name}', must be persistent" let env ← getEnv unless (env.getModuleIdxFor? decl).isNone do throwError! "invalid attribute '{name}', declaration is in an imported module" validate decl val setEnv $ ext.addEntry env (decl, val), applicationTime := applicationTime : AttributeImpl } attrs.forM registerBuiltinAttribute pure { ext := ext, attrs := attrs } namespace EnumAttributes instance {Ξ± : Type} : Inhabited (EnumAttributes Ξ±) := ⟨{attrs := [], ext := arbitrary }⟩ def getValue {Ξ± : Type} [Inhabited Ξ±] (attr : EnumAttributes Ξ±) (env : Environment) (decl : Name) : Option Ξ± := match env.getModuleIdxFor? decl with | some modIdx => match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some (_, val) => some val | none => none | none => (attr.ext.getState env).find? decl def setValue {Ξ± : Type} (attrs : EnumAttributes Ξ±) (env : Environment) (decl : Name) (val : Ξ±) : Except String Environment := if (env.getModuleIdxFor? decl).isSome then Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, declaration is in an imported module") else if ((attrs.ext.getState env).find? decl).isSome then Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, attribute has already been set") else Except.ok (attrs.ext.addEntry env (decl, val)) end EnumAttributes /-- Helper function for converting a Syntax object representing attribute parameters into an identifier. It returns `none` if the parameter is not a simple identifier. Remark: in the future, attributes should define their own parsers, and we should use `match_syntax` to decode the Syntax object. -/ def attrParamSyntaxToIdentifier (s : Syntax) : Option Name := match s with | Syntax.node k args => if k == nullKind && args.size == 1 then match args.get! 0 with | Syntax.ident _ _ id _ => some id | _ => none else none | _ => none end Lean
feb50699ae1296fbddb6f68555da11b022fee16e
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/field.lean
0a762a9c8b96d02a907cd60df88b94bf906ff87f
[ "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
14,070
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 has_inv] 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' {K : Type*} [division_ring K] (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 division_ring comm_ring] class field (K : Type u) extends comm_ring K, has_inv 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β€Ί } 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 [add_comm, ← div_mul_left ha, ← div_mul_right _ hb, division_def, division_def, division_def, ← right_distrib, mul_comm a] 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] @[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 [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. -/ 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_div f zero one mul inv div, .. hf.ring_sub f zero one add mul neg sub } /-- Pullback a `field` along an injective function. -/ 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_div f zero one mul inv div, .. hf.comm_ring_sub f zero one add mul neg sub }
dc3c8ce2b976f2b339f1a66e1c1ca3e4d69feb1c
0d19caa7d4fa8370c14061de04a835cb13b84e87
/06-formalizacija-dokazov/lambda.lean
c19161cbfa5ae0d63e945301be77c093546f0751
[]
no_license
natasataskov/teorija-programskih-jezikov
dfc285ce4980f9e24e745677a69f39c5d20bd512
82022713f0f5d946b1e59e51d69ab15d518eb07a
refs/heads/master
1,599,537,599,218
1,575,240,132,000
1,575,240,132,000
221,009,337
0
0
null
1,573,485,567,000
1,573,485,566,000
null
UTF-8
Lean
false
false
5,084
lean
inductive ty : Type | unit : ty | bool : ty | arrow : ty -> ty -> ty def nm := string inductive tm : Type | var : nm -> tm | unit : tm | true : tm | false : tm | app : tm -> tm -> tm | lam : nm -> tm -> tm | if_then_else : tm -> tm -> tm -> tm inductive value : tm -> Prop | unit : value tm.unit | true : value tm.true | false : value tm.false | lam {x : nm} {N : tm} : value (tm.lam x N) def subst (x : nm) (M : tm) : tm -> tm | (tm.var y) := if x = y then M else tm.var y | tm.unit := tm.unit | tm.true := tm.true | tm.false := tm.false | (tm.app N1 N2) := tm.app (subst N1) (subst N2) | (tm.lam y N) := if x = y then tm.lam y N else tm.lam y (subst N) | (tm.if_then_else N N1 N2) := tm.if_then_else (subst N) (subst N1) (subst N2) inductive step : tm -> tm -> Prop | step1 {M M' N : tm} : step M M' -> step (tm.app M N) (tm.app M' N) | step2 {V N N' : tm} : value V -> step N N' -> step (tm.app V N) (tm.app V N') | beta {x} {M V : tm} : value V -> step (tm.app (tm.lam x M) V) (subst x V M) | test {M M' N1 N2 : tm} : step M M' -> step (tm.if_then_else M N1 N2) (tm.if_then_else M' N1 N2) | true {N1 N2 : tm} : step (tm.if_then_else tm.true N1 N2) N1 | false {N1 N2 : tm} : step (tm.if_then_else tm.false N1 N2) N2 inductive ctx : Type | nil : ctx | cons : nm -> ty -> ctx -> ctx inductive lookup : nm -> ctx -> ty -> Prop | here {x A Ξ“} : lookup x (ctx.cons x A Ξ“) A | there {x y : nm} {A B : ty} {Ξ“ : ctx} : x β‰  y -> lookup x Ξ“ A -> lookup x (ctx.cons y B Ξ“) A inductive of : ctx -> tm -> ty -> Prop | var {x Ξ“ A}: lookup x Ξ“ A -> of Ξ“ (tm.var x) A | unit {Ξ“}: of Ξ“ tm.unit ty.unit | true {Ξ“}: of Ξ“ tm.true ty.bool | false {Ξ“}: of Ξ“ tm.false ty.bool | app {Ξ“ M N A B} : of Ξ“ M (ty.arrow A B) -> of Ξ“ N A -> of Ξ“ (tm.app M N) B | lam {Ξ“ x M A B} : of (ctx.cons x A Ξ“) M B -> of Ξ“ (tm.lam x M) (ty.arrow A B) | if_then_else {Ξ“ M N1 N2 A} : of Ξ“ M ty.bool -> of Ξ“ N1 A -> of Ξ“ N2 A -> of Ξ“ (tm.if_then_else M N1 N2) A theorem substitution (Ξ“ x A M M' A') : of Ξ“ M A -> of (ctx.cons x A Ξ“) M' A' -> of Ξ“ (subst x M M') A' := sorry theorem preservation (Ξ“ M M') : step M M' -> forall A, of Ξ“ M A -> of Ξ“ M' A := begin intros Hstep, induction Hstep, repeat {intros A Hof}, case step.beta {cases Hof, cases Hof_a, apply substitution _ _ _ _ _ _ Hof_a_1 Hof_a_a }, case step.step1 {cases Hof, apply of.app, apply Hstep_ih _ Hof_a, apply Hof_a_1}, case step.step2 {cases Hof, apply of.app, apply Hof_a, apply Hstep_ih _ Hof_a_1}, case step.test { cases Hof, apply of.if_then_else, apply Hstep_ih _ Hof_a, apply Hof_a_1, apply Hof_a_2 }, case step.true { cases Hof, apply Hof_a_1 }, case step.false { cases Hof, apply Hof_a_2 } end theorem progress (M A) : of ctx.nil M A -> (value M) ∨ (exists M', step M M') := begin generalize empty : ctx.nil = Ξ“, intros H, induction H, case of.var {rewrite ←empty at H_a, cases H_a}, case of.unit {left, exact value.unit}, case of.app { cases H_ih_a empty, case or.inl { cases H_a, case of.var {rw ←empty at H_a_a, cases H_a_a}, case of.app {cases h}, case of.lam { cases H_ih_a_1 empty, right, existsi (subst H_a_x H_N H_a_M), apply step.beta, assumption, right, cases h_1, existsi (tm.app (tm.lam H_a_x H_a_M) h_1_w), eapply step.step2, exact value.lam, assumption }, case of.if_then_else { cases h } }, case or.inr { cases h with M H_step, right, existsi (tm.app M H_N), apply step.step1, assumption } }, case of.lam {left, exact value.lam}, case of.true {left, exact value.true}, case of.false {left, exact value.false}, case of.if_then_else { cases H_ih_a empty, case or.inl { cases H_a, case of.var {rw ←empty at H_a_a, cases H_a_a}, case of.true { right, existsi H_N1, exact step.true }, case of.false { right, existsi H_N2, exact step.false }, cases h, cases h }, case or.inr { cases h, right, existsi (tm.if_then_else h_w H_N1 H_N2), exact (step.test h_h), } } end
623e6fc1afca8b3063a98fb0f9f1f5006e93a9d8
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/continued_fractions/continuants_recurrence.lean
0ad5fa1c03ce4a289766b3181e7b88ac992da0b8
[ "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
3,439
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.translations /-! # Recurrence Lemmas for the `continuants` Function of Continued Fractions. ## Summary Given a generalized continued fraction `g`, for all `n β‰₯ 1`, we prove that the `continuants` function indeed satisfies the following recurrences: `Aβ‚™ = bβ‚™ * Aₙ₋₁ + aβ‚™ * Aβ‚™β‚‹β‚‚`, and `Bβ‚™ = bβ‚™ * Bₙ₋₁ + aβ‚™ * Bβ‚™β‚‹β‚‚`. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {Ξ± : Type*} {g : gcf Ξ±} {n : β„•} [division_ring Ξ±] lemma continuants_aux_recurrence {gp ppred pred : gcf.pair Ξ±} (nth_s_eq : g.s.nth n = some gp) (nth_conts_aux_eq : g.continuants_aux n = ppred) (succ_nth_conts_aux_eq : g.continuants_aux (n + 1) = pred) : g.continuants_aux (n + 2) = ⟨gp.b * pred.a + gp.a * ppred.a, gp.b * pred.b + gp.a * ppred.b⟩ := by simp [*, continuants_aux, next_continuants, next_denominator, next_numerator] lemma continuants_recurrence_aux {gp ppred pred : gcf.pair Ξ±} (nth_s_eq : g.s.nth n = some gp) (nth_conts_aux_eq : g.continuants_aux n = ppred) (succ_nth_conts_aux_eq : g.continuants_aux (n + 1) = pred) : g.continuants (n + 1) = ⟨gp.b * pred.a + gp.a * ppred.a, gp.b * pred.b + gp.a * ppred.b⟩ := by simp [nth_cont_eq_succ_nth_cont_aux, (continuants_aux_recurrence nth_s_eq nth_conts_aux_eq succ_nth_conts_aux_eq)] theorem continuants_recurrence {gp ppred pred : gcf.pair Ξ±} (succ_nth_s_eq : g.s.nth (n + 1) = some gp) (nth_conts_eq : g.continuants n = ppred) (succ_nth_conts_eq : g.continuants (n + 1) = pred) : g.continuants (n + 2) = ⟨gp.b * pred.a + gp.a * ppred.a, gp.b * pred.b + gp.a * ppred.b⟩ := begin rw [nth_cont_eq_succ_nth_cont_aux] at nth_conts_eq succ_nth_conts_eq, exact (continuants_recurrence_aux succ_nth_s_eq nth_conts_eq succ_nth_conts_eq) end lemma numerators_recurrence {gp : gcf.pair Ξ±} {ppredA predA : Ξ±} (succ_nth_s_eq : g.s.nth (n + 1) = some gp) (nth_num_eq : g.numerators n = ppredA) (succ_nth_num_eq : g.numerators (n + 1) = predA) : g.numerators (n + 2) = gp.b * predA + gp.a * ppredA := begin obtain ⟨ppredConts, nth_conts_eq, ⟨rfl⟩⟩ : βˆƒ conts, g.continuants n = conts ∧ conts.a = ppredA, from obtain_conts_a_of_num nth_num_eq, obtain ⟨predConts, succ_nth_conts_eq, ⟨rfl⟩⟩ : βˆƒ conts, g.continuants (n + 1) = conts ∧ conts.a = predA, from obtain_conts_a_of_num succ_nth_num_eq, rw [num_eq_conts_a, (continuants_recurrence succ_nth_s_eq nth_conts_eq succ_nth_conts_eq)] end lemma denominators_recurrence {gp : gcf.pair Ξ±} {ppredB predB : Ξ±} (succ_nth_s_eq : g.s.nth (n + 1) = some gp) (nth_denom_eq : g.denominators n = ppredB) (succ_nth_denom_eq : g.denominators (n + 1) = predB) : g.denominators (n + 2) = gp.b * predB + gp.a * ppredB := begin obtain ⟨ppredConts, nth_conts_eq, ⟨rfl⟩⟩ : βˆƒ conts, g.continuants n = conts ∧ conts.b = ppredB, from obtain_conts_b_of_denom nth_denom_eq, obtain ⟨predConts, succ_nth_conts_eq, ⟨rfl⟩⟩ : βˆƒ conts, g.continuants (n + 1) = conts ∧ conts.b = predB, from obtain_conts_b_of_denom succ_nth_denom_eq, rw [denom_eq_conts_b, (continuants_recurrence succ_nth_s_eq nth_conts_eq succ_nth_conts_eq)] end end generalized_continued_fraction
1f625fd88e13282a549b078d6a7a5039b6c95648
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/real/sqrt.lean
4e8295d94dd417abb047d787a223fe7fd8eb62c5
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
12,510
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov -/ import topology.instances.nnreal import topology.algebra.ordered.monotone_continuity /-! # Square root of a real number In this file we define * `nnreal.sqrt` to be the square root of a nonnegative real number. * `real.sqrt` to be the square root of a real number, defined to be zero on negative numbers. Then we prove some basic properties of these functions. ## Implementation notes We define `nnreal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general theory of inverses of strictly monotone functions to prove that `nnreal.sqrt x` exists. As a side effect, `nnreal.sqrt` is a bundled `order_iso`, so for `nnreal` numbers we get continuity as well as theorems like `sqrt x ≀ y ↔ x * x ≀ y` for free. Then we define `real.sqrt x` to be `nnreal.sqrt (real.to_nnreal x)`. We also define a Cauchy sequence `real.sqrt_aux (f : cau_seq β„š abs)` which converges to `sqrt (mk f)` but do not prove (yet) that this sequence actually converges to `sqrt (mk f)`. ## Tags square root -/ open set filter open_locale filter nnreal topological_space namespace nnreal variables {x y : ℝβ‰₯0} /-- Square root of a nonnegative real number. -/ @[pp_nodot] noncomputable def sqrt : ℝβ‰₯0 ≃o ℝβ‰₯0 := order_iso.symm $ strict_mono.order_iso_of_surjective (Ξ» x, x * x) (Ξ» x y h, mul_self_lt_mul_self x.2 h) $ (continuous_id.mul continuous_id).surjective tendsto_mul_self_at_top $ by simp [order_bot.at_bot_eq] lemma sqrt_le_sqrt_iff : sqrt x ≀ sqrt y ↔ x ≀ y := sqrt.le_iff_le lemma sqrt_lt_sqrt_iff : sqrt x < sqrt y ↔ x < y := sqrt.lt_iff_lt lemma sqrt_eq_iff_sq_eq : sqrt x = y ↔ y * y = x := sqrt.to_equiv.apply_eq_iff_eq_symm_apply.trans eq_comm lemma sqrt_le_iff : sqrt x ≀ y ↔ x ≀ y * y := sqrt.to_galois_connection _ _ lemma le_sqrt_iff : x ≀ sqrt y ↔ x * x ≀ y := (sqrt.symm.to_galois_connection _ _).symm @[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 := sqrt_eq_iff_sq_eq.trans $ by rw [eq_comm, zero_mul] @[simp] lemma sqrt_zero : sqrt 0 = 0 := sqrt_eq_zero.2 rfl @[simp] lemma sqrt_one : sqrt 1 = 1 := sqrt_eq_iff_sq_eq.2 $ mul_one 1 @[simp] lemma mul_self_sqrt (x : ℝβ‰₯0) : sqrt x * sqrt x = x := sqrt.symm_apply_apply x @[simp] lemma sqrt_mul_self (x : ℝβ‰₯0) : sqrt (x * x) = x := sqrt.apply_symm_apply x @[simp] lemma sq_sqrt (x : ℝβ‰₯0) : (sqrt x)^2 = x := by rw [sq, mul_self_sqrt x] @[simp] lemma sqrt_sq (x : ℝβ‰₯0) : sqrt (x^2) = x := by rw [sq, sqrt_mul_self x] lemma sqrt_mul (x y : ℝβ‰₯0) : sqrt (x * y) = sqrt x * sqrt y := by rw [sqrt_eq_iff_sq_eq, mul_mul_mul_comm, mul_self_sqrt, mul_self_sqrt] /-- `nnreal.sqrt` as a `monoid_with_zero_hom`. -/ noncomputable def sqrt_hom : ℝβ‰₯0 β†’*β‚€ ℝβ‰₯0 := ⟨sqrt, sqrt_zero, sqrt_one, sqrt_mul⟩ lemma sqrt_inv (x : ℝβ‰₯0) : sqrt (x⁻¹) = (sqrt x)⁻¹ := sqrt_hom.map_inv x lemma sqrt_div (x y : ℝβ‰₯0) : sqrt (x / y) = sqrt x / sqrt y := sqrt_hom.map_div x y lemma continuous_sqrt : continuous sqrt := sqrt.continuous end nnreal namespace real /-- An auxiliary sequence of rational numbers that converges to `real.sqrt (mk f)`. Currently this sequence is not used in `mathlib`. -/ def sqrt_aux (f : cau_seq β„š abs) : β„• β†’ β„š | 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt | (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2 theorem sqrt_aux_nonneg (f : cau_seq β„š abs) : βˆ€ i : β„•, 0 ≀ sqrt_aux f i | 0 := by rw [sqrt_aux, rat.mk_nat_eq, rat.mk_eq_div]; apply div_nonneg; exact int.cast_nonneg.2 (int.of_nat_nonneg _) | (n + 1) := le_max_left _ _ /- TODO(Mario): finish the proof theorem sqrt_aux_converges (f : cau_seq β„š abs) : βˆƒ h x, 0 ≀ x ∧ x * x = max 0 (mk f) ∧ mk ⟨sqrt_aux f, h⟩ = x := begin rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩, suffices : βˆƒ h, mk ⟨sqrt_aux f, h⟩ = x, { exact this.imp (Ξ» h e, ⟨x, x0, hx, e⟩) }, apply of_near, suffices : βˆƒ Ξ΄ > 0, βˆ€ i, abs (↑(sqrt_aux f i) - x) < Ξ΄ / 2 ^ i, { rcases this with ⟨δ, Ξ΄0, hδ⟩, intros } end -/ /-- The square root of a real number. This returns 0 for negative inputs. -/ @[pp_nodot] noncomputable def sqrt (x : ℝ) : ℝ := nnreal.sqrt (real.to_nnreal x) /-quotient.lift_on x (Ξ» f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (Ξ» f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ variables {x y : ℝ} @[simp, norm_cast] lemma coe_sqrt {x : ℝβ‰₯0} : (nnreal.sqrt x : ℝ) = real.sqrt x := by rw [real.sqrt, real.to_nnreal_coe] @[continuity] lemma continuous_sqrt : continuous sqrt := nnreal.continuous_coe.comp $ nnreal.sqrt.continuous.comp nnreal.continuous_of_real theorem sqrt_eq_zero_of_nonpos (h : x ≀ 0) : sqrt x = 0 := by simp [sqrt, real.to_nnreal_eq_zero.2 h] theorem sqrt_nonneg (x : ℝ) : 0 ≀ sqrt x := nnreal.coe_nonneg _ @[simp] theorem mul_self_sqrt (h : 0 ≀ x) : sqrt x * sqrt x = x := by rw [sqrt, ← nnreal.coe_mul, nnreal.mul_self_sqrt, real.coe_to_nnreal _ h] @[simp] theorem sqrt_mul_self (h : 0 ≀ x) : sqrt (x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_cases : sqrt x = y ↔ y * y = x ∧ 0 ≀ y ∨ x < 0 ∧ y = 0 := begin split, { rintro rfl, cases le_or_lt 0 x with hle hlt, { exact or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ }, { exact or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ } }, { rintro (⟨rfl, hy⟩|⟨hx, rfl⟩), exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] } end theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≀ x) (hy : 0 ≀ y) : sqrt x = y ↔ y * y = x := ⟨λ h, by rw [← h, mul_self_sqrt hx], Ξ» h, by rw [← h, sqrt_mul_self hy]⟩ theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) : sqrt x = y ↔ y * y = x := by simp [sqrt_eq_cases, h.ne', h.le] @[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 := calc sqrt x = 1 ↔ 1 * 1 = x : sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one ... ↔ x = 1 : by rw [eq_comm, mul_one] @[simp] theorem sq_sqrt (h : 0 ≀ x) : (sqrt x)^2 = x := by rw [sq, mul_self_sqrt h] @[simp] theorem sqrt_sq (h : 0 ≀ x) : sqrt (x ^ 2) = x := by rw [sq, sqrt_mul_self h] theorem sqrt_eq_iff_sq_eq (hx : 0 ≀ x) (hy : 0 ≀ y) : sqrt x = y ↔ y ^ 2 = x := by rw [sq, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = |x| := by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)] theorem sqrt_sq_eq_abs (x : ℝ) : sqrt (x ^ 2) = |x| := by rw [sq, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : sqrt 0 = 0 := by simp [sqrt] @[simp] theorem sqrt_one : sqrt 1 = 1 := by simp [sqrt] @[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≀ y) : sqrt x ≀ sqrt y ↔ x ≀ y := by rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff, real.to_nnreal_le_to_nnreal_iff hy] @[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≀ x) : sqrt x < sqrt y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx) theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : sqrt x < sqrt y ↔ x < y := by rw [sqrt, sqrt, nnreal.coe_lt_coe, nnreal.sqrt_lt_sqrt_iff, to_nnreal_lt_to_nnreal_iff hy] theorem sqrt_le_sqrt (h : x ≀ y) : sqrt x ≀ sqrt y := by { rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff], exact to_nnreal_le_to_nnreal h } theorem sqrt_lt_sqrt (hx : 0 ≀ x) (h : x < y) : sqrt x < sqrt y := (sqrt_lt_sqrt_iff hx).2 h theorem sqrt_le_left (hy : 0 ≀ y) : sqrt x ≀ y ↔ x ≀ y ^ 2 := by rw [sqrt, ← real.le_to_nnreal_iff_coe_le hy, nnreal.sqrt_le_iff, ← real.to_nnreal_mul hy, real.to_nnreal_le_to_nnreal_iff (mul_self_nonneg y), sq] theorem sqrt_le_iff : sqrt x ≀ y ↔ 0 ≀ y ∧ x ≀ y ^ 2 := begin rw [← and_iff_right_of_imp (Ξ» h, (sqrt_nonneg x).trans h), and.congr_right_iff], exact sqrt_le_left end /- note: if you want to conclude `x ≀ sqrt y`, then use `le_sqrt_of_sq_le`. if you have `x > 0`, consider using `le_sqrt'` -/ theorem le_sqrt (hx : 0 ≀ x) (hy : 0 ≀ y) : x ≀ sqrt y ↔ x ^ 2 ≀ y := by rw [mul_self_le_mul_self_iff hx (sqrt_nonneg _), sq, mul_self_sqrt hy] theorem le_sqrt' (hx : 0 < x) : x ≀ sqrt y ↔ x ^ 2 ≀ y := by { rw [sqrt, ← nnreal.coe_mk x hx.le, nnreal.coe_le_coe, nnreal.le_sqrt_iff, real.le_to_nnreal_iff_coe_le', sq, nnreal.coe_mul], exact mul_pos hx hx } theorem abs_le_sqrt (h : x^2 ≀ y) : |x| ≀ sqrt y := by rw ← sqrt_sq_eq_abs; exact sqrt_le_sqrt h theorem sq_le (h : 0 ≀ y) : x^2 ≀ y ↔ -sqrt y ≀ x ∧ x ≀ sqrt y := begin split, { simpa only [abs_le] using abs_le_sqrt }, { rw [← abs_le, ← sq_abs], exact (le_sqrt (abs_nonneg x) h).mp }, end theorem neg_sqrt_le_of_sq_le (h : x^2 ≀ y) : -sqrt y ≀ x := ((sq_le ((sq_nonneg x).trans h)).mp h).1 theorem le_sqrt_of_sq_le (h : x^2 ≀ y) : x ≀ sqrt y := ((sq_le ((sq_nonneg x).trans h)).mp h).2 @[simp] theorem sqrt_inj (hx : 0 ≀ x) (hy : 0 ≀ y) : sqrt x = sqrt y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero (h : 0 ≀ x) : sqrt x = 0 ↔ x = 0 := by simpa using sqrt_inj h le_rfl theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≀ 0 := by rw [sqrt, nnreal.coe_eq_zero, nnreal.sqrt_eq_zero, real.to_nnreal_eq_zero] theorem sqrt_ne_zero (h : 0 ≀ x) : sqrt x β‰  0 ↔ x β‰  0 := by rw [not_iff_not, sqrt_eq_zero h] theorem sqrt_ne_zero' : sqrt x β‰  0 ↔ 0 < x := by rw [← not_le, not_iff_not, sqrt_eq_zero'] @[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x := lt_iff_lt_of_le_iff_le (iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') @[simp] theorem sqrt_mul (hx : 0 ≀ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y := by simp_rw [sqrt, ← nnreal.coe_mul, nnreal.coe_eq, real.to_nnreal_mul hx, nnreal.sqrt_mul] @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≀ y) : sqrt (x * y) = sqrt x * sqrt y := by rw [mul_comm, sqrt_mul hy, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ := by rw [sqrt, real.to_nnreal_inv, nnreal.sqrt_inv, nnreal.coe_inv, sqrt] @[simp] theorem sqrt_div (hx : 0 ≀ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y := by rw [division_def, sqrt_mul hx, sqrt_inv, division_def] @[simp] theorem div_sqrt : x / sqrt x = sqrt x := begin cases le_or_lt x 0, { rw [sqrt_eq_zero'.mpr h, div_zero] }, { rw [div_eq_iff (sqrt_ne_zero'.mpr h), mul_self_sqrt h.le] }, end theorem sqrt_div_self' : sqrt x / x = 1 / sqrt x := by rw [←div_sqrt, one_div_div, div_sqrt] theorem sqrt_div_self : sqrt x / x = (sqrt x)⁻¹ := by rw [sqrt_div_self', one_div] theorem lt_sqrt (hx : 0 ≀ x) (hy : 0 ≀ y) : x < sqrt y ↔ x ^ 2 < y := by rw [mul_self_lt_mul_self_iff hx (sqrt_nonneg y), sq, mul_self_sqrt hy] theorem sq_lt : x^2 < y ↔ -sqrt y < x ∧ x < sqrt y := begin split, { simpa only [← sqrt_lt_sqrt_iff (sq_nonneg x), sqrt_sq_eq_abs] using abs_lt.mp }, { rw [← abs_lt, ← sq_abs], exact Ξ» h, (lt_sqrt (abs_nonneg x) (sqrt_pos.mp (lt_of_le_of_lt (abs_nonneg x) h)).le).mp h }, end theorem neg_sqrt_lt_of_sq_lt (h : x^2 < y) : -sqrt y < x := (sq_lt.mp h).1 theorem lt_sqrt_of_sq_lt (h : x^2 < y) : x < sqrt y := (sq_lt.mp h).2 instance : star_ordered_ring ℝ := { nonneg_iff := Ξ» r, by { refine ⟨λ hr, ⟨sqrt r, show r = sqrt r * sqrt r, by rw [←sqrt_mul hr, sqrt_mul_self hr]⟩, _⟩, rintros ⟨s, rfl⟩, exact mul_self_nonneg s }, ..real.ordered_add_comm_group } end real open real variables {Ξ± : Type*} lemma filter.tendsto.sqrt {f : Ξ± β†’ ℝ} {l : filter Ξ±} {x : ℝ} (h : tendsto f l (𝓝 x)) : tendsto (Ξ» x, sqrt (f x)) l (𝓝 (sqrt x)) := (continuous_sqrt.tendsto _).comp h variables [topological_space Ξ±] {f : Ξ± β†’ ℝ} {s : set Ξ±} {x : Ξ±} lemma continuous_within_at.sqrt (h : continuous_within_at f s x) : continuous_within_at (Ξ» x, sqrt (f x)) s x := h.sqrt lemma continuous_at.sqrt (h : continuous_at f x) : continuous_at (Ξ» x, sqrt (f x)) x := h.sqrt lemma continuous_on.sqrt (h : continuous_on f s) : continuous_on (Ξ» x, sqrt (f x)) s := Ξ» x hx, (h x hx).sqrt @[continuity] lemma continuous.sqrt (h : continuous f) : continuous (Ξ» x, sqrt (f x)) := continuous_sqrt.comp h
0826f04276d69c37ed060c1bc89f7d4a1a51d288
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/monoid_localization_auto.lean
e8323902666a2066eb1f246a5184e5779be67b27
[]
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
72,068
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.congruence import Mathlib.group_theory.submonoid.default import Mathlib.algebra.group.units import Mathlib.algebra.punit_instances import Mathlib.PostPort universes u_1 u_2 l u_3 u_4 u_5 u_6 namespace Mathlib /-! # Localizations of commutative monoids Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so we can generalize localizations to commutative monoids. We characterize the localization of a commutative monoid `M` at a submonoid `S` up to isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a monoid homomorphism `f : M β†’* N` satisfying 3 properties: 1. For all `y ∈ S`, `f y` is a unit; 2. For all `z : N`, there exists `(x, y) : M Γ— S` such that `z * f y = f x`; 3. For all `x, y : M`, `f x = f y` iff there exists `c ∈ S` such that `x * c = y * c`. Given such a localization map `f : M β†’* N`, we can define the surjection `localization_map.mk'` sending `(x, y) : M Γ— S` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `N` induced by a homomorphism from `M` which maps elements of `S` to invertible elements of the codomain. Similarly, given commutative monoids `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : M β†’* P` such that `g(S) βŠ† T` induces a homomorphism of localizations, `localization_map.map`, from `N` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We also define the quotient of `M Γ— S` by the unique congruence relation (equivalence relation preserving a binary operation) `r` such that for any other congruence relation `s` on `M Γ— S` satisfying '`βˆ€ y ∈ S`, `(1, 1) ∼ (y, y)` under `s`', we have that `(x₁, y₁) ∼ (xβ‚‚, yβ‚‚)` by `s` whenever `(x₁, y₁) ∼ (xβ‚‚, yβ‚‚)` by `r`. We show this relation is equivalent to the standard localization relation. This defines the localization as a quotient type, `localization`, but the majority of subsequent lemmas in the file are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic predicate. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. The infimum form of the localization congruence relation is chosen as 'canonical' here, since it shortens some proofs. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_monoid_of_mk'` and associated lemmas. These show the quotient map `mk : M β†’ S β†’ localization S` equals the surjection `localization_map.mk'` induced by the map `monoid_of : localization_map S (localization S)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_monoid_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. ## Tags localization, monoid localization, quotient monoid, congruence relation, characteristic predicate, commutative monoid -/ namespace add_submonoid /-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M β†’+ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ structure localization_map {M : Type u_1} [add_comm_monoid M] (S : add_submonoid M) (N : Type u_2) [add_comm_monoid N] extends M β†’+ N where map_add_units' : βˆ€ (y : β†₯S), is_add_unit (to_fun ↑y) surj' : βˆ€ (z : N), βˆƒ (x : M Γ— β†₯S), z + to_fun ↑(prod.snd x) = to_fun (prod.fst x) eq_iff_exists' : βˆ€ (x y : M), to_fun x = to_fun y ↔ βˆƒ (c : β†₯S), x + ↑c = y + ↑c /-- The add_monoid hom underlying a `localization_map` of `add_comm_monoid`s. -/ end add_submonoid namespace submonoid /-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M β†’* N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ structure localization_map {M : Type u_1} [comm_monoid M] (S : submonoid M) (N : Type u_2) [comm_monoid N] extends M β†’* N where map_units' : βˆ€ (y : β†₯S), is_unit (to_fun ↑y) surj' : βˆ€ (z : N), βˆƒ (x : M Γ— β†₯S), z * to_fun ↑(prod.snd x) = to_fun (prod.fst x) eq_iff_exists' : βˆ€ (x y : M), to_fun x = to_fun y ↔ βˆƒ (c : β†₯S), x * ↑c = y * ↑c /-- The monoid hom underlying a `localization_map`. -/ end submonoid namespace localization /-- The congruence relation on `M Γ— S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M Γ— S` such that for any other congruence relation `s` on `M Γ— S` where for all `y ∈ S`, `(1, 1) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (xβ‚‚, yβ‚‚)` by `r` implies `(x₁, y₁) ∼ (xβ‚‚, yβ‚‚)` by `s`. -/ def Mathlib.add_localization.r {M : Type u_1} [add_comm_monoid M] (S : add_submonoid M) : add_con (M Γ— β†₯S) := Inf (set_of fun (c : add_con (M Γ— β†₯S)) => βˆ€ (y : β†₯S), coe_fn c 0 (↑y, y)) /-- An alternate form of the congruence relation on `M Γ— S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. -/ def Mathlib.add_localization.r' {M : Type u_1} [add_comm_monoid M] (S : add_submonoid M) : add_con (M Γ— β†₯S) := add_con.mk (fun (a b : M Γ— β†₯S) => βˆƒ (c : β†₯S), prod.fst a + ↑(prod.snd b) + ↑c = prod.fst b + ↑(prod.snd a) + ↑c) sorry sorry /-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`). -/ theorem r_eq_r' {M : Type u_1} [comm_monoid M] (S : submonoid M) : r S = r' S := sorry theorem Mathlib.add_localization.r_iff_exists {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {x : M Γ— β†₯S} {y : M Γ— β†₯S} : coe_fn (add_localization.r S) x y ↔ βˆƒ (c : β†₯S), prod.fst x + ↑(prod.snd y) + ↑c = prod.fst y + ↑(prod.snd x) + ↑c := sorry end localization /-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/ def localization {M : Type u_1} [comm_monoid M] (S : submonoid M) := con.quotient sorry namespace localization protected instance inhabited {M : Type u_1} [comm_monoid M] (S : submonoid M) : Inhabited (localization S) := con.quotient.inhabited protected instance comm_monoid {M : Type u_1} [comm_monoid M] (S : submonoid M) : comm_monoid (localization S) := con.comm_monoid (r S) /-- Given a `comm_monoid` `M` and submonoid `S`, `mk` sends `x : M`, `y ∈ S` to the equivalence class of `(x, y)` in the localization of `M` at `S`. -/ def Mathlib.add_localization.mk {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} (x : M) (y : β†₯S) : add_localization S := coe_fn (add_con.mk' (add_localization.r S)) (x, y) theorem Mathlib.add_localization.ind {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {p : add_localization S β†’ Prop} (H : βˆ€ (y : M Γ— β†₯S), p (add_localization.mk (prod.fst y) (prod.snd y))) (x : add_localization S) : p x := sorry theorem Mathlib.add_localization.induction_on {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {p : add_localization S β†’ Prop} (x : add_localization S) (H : βˆ€ (y : M Γ— β†₯S), p (add_localization.mk (prod.fst y) (prod.snd y))) : p x := add_localization.ind H x theorem induction_onβ‚‚ {M : Type u_1} [comm_monoid M] {S : submonoid M} {p : localization S β†’ localization S β†’ Prop} (x : localization S) (y : localization S) (H : βˆ€ (x y : M Γ— β†₯S), p (mk (prod.fst x) (prod.snd x)) (mk (prod.fst y) (prod.snd y))) : p x y := induction_on x fun (x : M Γ— β†₯S) => induction_on y (H x) theorem induction_on₃ {M : Type u_1} [comm_monoid M] {S : submonoid M} {p : localization S β†’ localization S β†’ localization S β†’ Prop} (x : localization S) (y : localization S) (z : localization S) (H : βˆ€ (x y z : M Γ— β†₯S), p (mk (prod.fst x) (prod.snd x)) (mk (prod.fst y) (prod.snd y)) (mk (prod.fst z) (prod.snd z))) : p x y z := induction_onβ‚‚ x y fun (x y : M Γ— β†₯S) => induction_on z (H x y) theorem one_rel {M : Type u_1} [comm_monoid M] {S : submonoid M} (y : β†₯S) : coe_fn (r S) 1 (↑y, y) := fun (b : con (M Γ— β†₯S)) (hb : b ∈ set_of fun (c : con (M Γ— β†₯S)) => βˆ€ (y : β†₯S), coe_fn c 1 (↑y, y)) => hb y theorem Mathlib.add_localization.r_of_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {x : M Γ— β†₯S} {y : M Γ— β†₯S} (h : prod.fst y + ↑(prod.snd x) = prod.fst x + ↑(prod.snd y)) : coe_fn (add_localization.r S) x y := sorry end localization namespace monoid_hom /-- Makes a localization map from a `comm_monoid` hom satisfying the characteristic predicate. -/ def Mathlib.add_monoid_hom.to_localization_map {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : M β†’+ N) (H1 : βˆ€ (y : β†₯S), is_add_unit (coe_fn f ↑y)) (H2 : βˆ€ (z : N), βˆƒ (x : M Γ— β†₯S), z + coe_fn f ↑(prod.snd x) = coe_fn f (prod.fst x)) (H3 : βˆ€ (x y : M), coe_fn f x = coe_fn f y ↔ βˆƒ (c : β†₯S), x + ↑c = y + ↑c) : add_submonoid.localization_map S N := add_submonoid.localization_map.mk (add_monoid_hom.to_fun f) sorry sorry H1 H2 H3 end monoid_hom namespace submonoid namespace localization_map /-- Short for `to_monoid_hom`; used to apply a localization map as a function. -/ def to_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) : M β†’* N := to_monoid_hom f theorem Mathlib.add_submonoid.localization_map.ext {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} {g : add_submonoid.localization_map S N} (h : βˆ€ (x : M), coe_fn (add_submonoid.localization_map.to_map f) x = coe_fn (add_submonoid.localization_map.to_map g) x) : f = g := sorry theorem ext_iff {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : localization_map S N} {g : localization_map S N} : f = g ↔ βˆ€ (x : M), coe_fn (to_map f) x = coe_fn (to_map g) x := { mp := fun (h : f = g) (x : M) => h β–Έ rfl, mpr := ext } theorem to_map_injective {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] : function.injective to_map := fun (_x _x_1 : localization_map S N) (h : to_map _x = to_map _x_1) => ext (iff.mp monoid_hom.ext_iff h) theorem map_units {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (y : β†₯S) : is_unit (coe_fn (to_map f) ↑y) := map_units' f y theorem surj {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (z : N) : βˆƒ (x : M Γ— β†₯S), z * coe_fn (to_map f) ↑(prod.snd x) = coe_fn (to_map f) (prod.fst x) := surj' f z theorem eq_iff_exists {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {x : M} {y : M} : coe_fn (to_map f) x = coe_fn (to_map f) y ↔ βˆƒ (c : β†₯S), x * ↑c = y * ↑c := eq_iff_exists' f x y /-- Given a localization map `f : M β†’* N`, a section function sending `z : N` to some `(x, y) : M Γ— S` such that `f x * (f y)⁻¹ = z`. -/ def sec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (z : N) : M Γ— β†₯S := classical.some (surj f z) theorem Mathlib.add_submonoid.localization_map.sec_spec {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (z : N) : z + coe_fn (add_submonoid.localization_map.to_map f) ↑(prod.snd (add_submonoid.localization_map.sec f z)) = coe_fn (add_submonoid.localization_map.to_map f) (prod.fst (add_submonoid.localization_map.sec f z)) := classical.some_spec (add_submonoid.localization_map.surj f z) theorem Mathlib.add_submonoid.localization_map.sec_spec' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (z : N) : coe_fn (add_submonoid.localization_map.to_map f) (prod.fst (add_submonoid.localization_map.sec f z)) = coe_fn (add_submonoid.localization_map.to_map f) ↑(prod.snd (add_submonoid.localization_map.sec f z)) + z := sorry /-- Given a monoid hom `f : M β†’* N` and submonoid `S βŠ† M` such that `f(S) βŠ† units N`, for all `w : M, z : N` and `y ∈ S`, we have `w * (f y)⁻¹ = z ↔ w = f y * z`. -/ theorem Mathlib.add_submonoid.localization_map.add_neg_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : M β†’+ N} (h : βˆ€ (y : β†₯S), is_add_unit (coe_fn f ↑y)) (y : β†₯S) (w : N) (z : N) : w + ↑(-coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) h) y) = z ↔ w = coe_fn f ↑y + z := sorry /-- Given a monoid hom `f : M β†’* N` and submonoid `S βŠ† M` such that `f(S) βŠ† units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w * (f y)⁻¹ ↔ z * f y = w`. -/ theorem mul_inv_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : M β†’* N} (h : βˆ€ (y : β†₯S), is_unit (coe_fn f ↑y)) (y : β†₯S) (w : N) (z : N) : z = w * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict f S) h) y⁻¹) ↔ z * coe_fn f ↑y = w := sorry /-- Given a monoid hom `f : M β†’* N` and submonoid `S βŠ† M` such that `f(S) βŠ† units N`, for all `x₁ xβ‚‚ : M` and `y₁, yβ‚‚ ∈ S`, we have `f x₁ * (f y₁)⁻¹ = f xβ‚‚ * (f yβ‚‚)⁻¹ ↔ f (x₁ * yβ‚‚) = f (xβ‚‚ * y₁)`. -/ @[simp] theorem mul_inv {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : M β†’* N} (h : βˆ€ (y : β†₯S), is_unit (coe_fn f ↑y)) {x₁ : M} {xβ‚‚ : M} {y₁ : β†₯S} {yβ‚‚ : β†₯S} : coe_fn f x₁ * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict f S) h) y₁⁻¹) = coe_fn f xβ‚‚ * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict f S) h) y₂⁻¹) ↔ coe_fn f (x₁ * ↑yβ‚‚) = coe_fn f (xβ‚‚ * ↑y₁) := sorry /-- Given a monoid hom `f : M β†’* N` and submonoid `S βŠ† M` such that `f(S) βŠ† units N`, for all `y, z ∈ S`, we have `(f y)⁻¹ = (f z)⁻¹ β†’ f y = f z`. -/ theorem Mathlib.add_submonoid.localization_map.neg_inj {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : M β†’+ N} (hf : βˆ€ (y : β†₯S), is_add_unit (coe_fn f ↑y)) {y : β†₯S} {z : β†₯S} (h : -coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) hf) y = -coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) hf) z) : coe_fn f ↑y = coe_fn f ↑z := sorry /-- Given a monoid hom `f : M β†’* N` and submonoid `S βŠ† M` such that `f(S) βŠ† units N`, for all `y ∈ S`, `(f y)⁻¹` is unique. -/ theorem Mathlib.add_submonoid.localization_map.neg_unique {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : M β†’+ N} (h : βˆ€ (y : β†₯S), is_add_unit (coe_fn f ↑y)) {y : β†₯S} {z : N} (H : coe_fn f ↑y + z = 0) : ↑(-coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) h) y) = z := sorry theorem map_right_cancel {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {x : M} {y : M} {c : β†₯S} (h : coe_fn (to_map f) (↑c * x) = coe_fn (to_map f) (↑c * y)) : coe_fn (to_map f) x = coe_fn (to_map f) y := sorry theorem Mathlib.add_submonoid.localization_map.map_left_cancel {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) {x : M} {y : M} {c : β†₯S} (h : coe_fn (add_submonoid.localization_map.to_map f) (x + ↑c) = coe_fn (add_submonoid.localization_map.to_map f) (y + ↑c)) : coe_fn (add_submonoid.localization_map.to_map f) x = coe_fn (add_submonoid.localization_map.to_map f) y := sorry /-- Given a localization map `f : M β†’* N`, the surjection sending `(x, y) : M Γ— S` to `f x * (f y)⁻¹`. -/ def mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : β†₯S) : N := coe_fn (to_map f) x * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict (to_map f) S) (map_units f)) y⁻¹) theorem Mathlib.add_submonoid.localization_map.mk'_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x₁ : M) (xβ‚‚ : M) (y₁ : β†₯S) (yβ‚‚ : β†₯S) : add_submonoid.localization_map.mk' f (x₁ + xβ‚‚) (y₁ + yβ‚‚) = add_submonoid.localization_map.mk' f x₁ y₁ + add_submonoid.localization_map.mk' f xβ‚‚ yβ‚‚ := sorry theorem mk'_one {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) : mk' f x 1 = coe_fn (to_map f) x := sorry /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z * f y = f x`, then `f x * (f y)⁻¹ = z`. -/ @[simp] theorem Mathlib.add_submonoid.localization_map.mk'_sec {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (z : N) : add_submonoid.localization_map.mk' f (prod.fst (add_submonoid.localization_map.sec f z)) (prod.snd (add_submonoid.localization_map.sec f z)) = z := sorry theorem mk'_surjective {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (z : N) : βˆƒ (x : M), βˆƒ (y : β†₯S), mk' f x y = z := Exists.intro (prod.fst (sec f z)) (Exists.intro (prod.snd (sec f z)) (mk'_sec f z)) theorem mk'_spec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : β†₯S) : mk' f x y * coe_fn (to_map f) ↑y = coe_fn (to_map f) x := sorry theorem mk'_spec' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : β†₯S) : coe_fn (to_map f) ↑y * mk' f x y = coe_fn (to_map f) x := sorry theorem eq_mk'_iff_mul_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {x : M} {y : β†₯S} {z : N} : z = mk' f x y ↔ z * coe_fn (to_map f) ↑y = coe_fn (to_map f) x := sorry theorem Mathlib.add_submonoid.localization_map.mk'_eq_iff_eq_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) {x : M} {y : β†₯S} {z : N} : add_submonoid.localization_map.mk' f x y = z ↔ coe_fn (add_submonoid.localization_map.to_map f) x = z + coe_fn (add_submonoid.localization_map.to_map f) ↑y := sorry theorem Mathlib.add_submonoid.localization_map.mk'_eq_iff_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) {x₁ : M} {xβ‚‚ : M} {y₁ : β†₯S} {yβ‚‚ : β†₯S} : add_submonoid.localization_map.mk' f x₁ y₁ = add_submonoid.localization_map.mk' f xβ‚‚ yβ‚‚ ↔ coe_fn (add_submonoid.localization_map.to_map f) (x₁ + ↑yβ‚‚) = coe_fn (add_submonoid.localization_map.to_map f) (xβ‚‚ + ↑y₁) := sorry protected theorem eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {a₁ : M} {b₁ : M} {aβ‚‚ : β†₯S} {bβ‚‚ : β†₯S} : mk' f a₁ aβ‚‚ = mk' f b₁ bβ‚‚ ↔ βˆƒ (c : β†₯S), a₁ * ↑bβ‚‚ * ↑c = b₁ * ↑aβ‚‚ * ↑c := iff.trans (mk'_eq_iff_eq f) (eq_iff_exists f) protected theorem eq' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {a₁ : M} {b₁ : M} {aβ‚‚ : β†₯S} {bβ‚‚ : β†₯S} : mk' f a₁ aβ‚‚ = mk' f b₁ bβ‚‚ ↔ coe_fn (localization.r S) (a₁, aβ‚‚) (b₁, bβ‚‚) := sorry theorem Mathlib.add_submonoid.localization_map.eq_iff_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) (g : add_submonoid.localization_map S P) {x : M} {y : M} : coe_fn (add_submonoid.localization_map.to_map f) x = coe_fn (add_submonoid.localization_map.to_map f) y ↔ coe_fn (add_submonoid.localization_map.to_map g) x = coe_fn (add_submonoid.localization_map.to_map g) y := iff.trans (add_submonoid.localization_map.eq_iff_exists f) (iff.symm (add_submonoid.localization_map.eq_iff_exists g)) theorem mk'_eq_iff_mk'_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (g : localization_map S P) {x₁ : M} {xβ‚‚ : M} {y₁ : β†₯S} {yβ‚‚ : β†₯S} : mk' f x₁ y₁ = mk' f xβ‚‚ yβ‚‚ ↔ mk' g x₁ y₁ = mk' g xβ‚‚ yβ‚‚ := iff.trans (localization_map.eq' f) (iff.symm (localization_map.eq' g)) /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M`, for all `x₁ : M` and `y₁ ∈ S`, if `xβ‚‚ : M, yβ‚‚ ∈ S` are such that `f x₁ * (f y₁)⁻¹ * f yβ‚‚ = f xβ‚‚`, then there exists `c ∈ S` such that `x₁ * yβ‚‚ * c = xβ‚‚ * y₁ * c`. -/ theorem Mathlib.add_submonoid.localization_map.exists_of_sec_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : M) (y : β†₯S) : βˆƒ (c : β†₯S), x + ↑(prod.snd (add_submonoid.localization_map.sec f (add_submonoid.localization_map.mk' f x y))) + ↑c = prod.fst (add_submonoid.localization_map.sec f (add_submonoid.localization_map.mk' f x y)) + ↑y + ↑c := iff.mp (add_submonoid.localization_map.eq_iff_exists f) (iff.mp (add_submonoid.localization_map.mk'_eq_iff_eq f) (Eq.symm (add_submonoid.localization_map.mk'_sec f (add_submonoid.localization_map.mk' f x y)))) theorem mk'_eq_of_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {a₁ : M} {b₁ : M} {aβ‚‚ : β†₯S} {bβ‚‚ : β†₯S} (H : b₁ * ↑aβ‚‚ = a₁ * ↑bβ‚‚) : mk' f a₁ aβ‚‚ = mk' f b₁ bβ‚‚ := iff.mpr (mk'_eq_iff_eq f) (H β–Έ rfl) @[simp] theorem Mathlib.add_submonoid.localization_map.mk'_self' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (y : β†₯S) : add_submonoid.localization_map.mk' f (↑y) y = 0 := sorry @[simp] theorem mk'_self {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (H : x ∈ S) : mk' f x { val := x, property := H } = 1 := sorry theorem mul_mk'_eq_mk'_of_mul {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x₁ : M) (xβ‚‚ : M) (y : β†₯S) : coe_fn (to_map f) x₁ * mk' f xβ‚‚ y = mk' f (x₁ * xβ‚‚) y := sorry theorem Mathlib.add_submonoid.localization_map.mk'_add_eq_mk'_of_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x₁ : M) (xβ‚‚ : M) (y : β†₯S) : add_submonoid.localization_map.mk' f xβ‚‚ y + coe_fn (add_submonoid.localization_map.to_map f) x₁ = add_submonoid.localization_map.mk' f (x₁ + xβ‚‚) y := sorry theorem Mathlib.add_submonoid.localization_map.add_mk'_zero_eq_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : M) (y : β†₯S) : coe_fn (add_submonoid.localization_map.to_map f) x + add_submonoid.localization_map.mk' f 0 y = add_submonoid.localization_map.mk' f x y := sorry @[simp] theorem mk'_mul_cancel_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : β†₯S) : mk' f (x * ↑y) y = coe_fn (to_map f) x := sorry theorem Mathlib.add_submonoid.localization_map.mk'_add_cancel_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : M) (y : β†₯S) : add_submonoid.localization_map.mk' f (↑y + x) y = coe_fn (add_submonoid.localization_map.to_map f) x := sorry theorem is_unit_comp {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (j : N β†’* P) (y : β†₯S) : is_unit (coe_fn (monoid_hom.comp j (to_map f)) ↑y) := sorry /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M` and a map of `comm_monoid`s `g : M β†’* P` such that `g(S) βŠ† units P`, `f x = f y β†’ g x = g y` for all `x y : M`. -/ theorem eq_of_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) {x : M} {y : M} (h : coe_fn (to_map f) x = coe_fn (to_map f) y) : coe_fn g x = coe_fn g y := sorry /-- Given `comm_monoid`s `M, P`, localization maps `f : M β†’* N, k : P β†’* Q` for submonoids `S, T` respectively, and `g : M β†’* P` such that `g(S) βŠ† T`, `f x = f y` implies `k (g x) = k (g y)`. -/ theorem comp_eq_of_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} {T : submonoid P} {Q : Type u_4} [comm_monoid Q] (hg : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) (k : localization_map T Q) {x : M} {y : M} (h : coe_fn (to_map f) x = coe_fn (to_map f) y) : coe_fn (to_map k) (coe_fn g x) = coe_fn (to_map k) (coe_fn g y) := sorry /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M` and a map of `comm_monoid`s `g : M β†’* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x * (g y)⁻¹`, where `(x, y) : M Γ— S` are such that `z = f x * (f y)⁻¹`. -/ def lift {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) : N β†’* P := monoid_hom.mk (fun (z : N) => coe_fn g (prod.fst (sec f z)) * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict g S) hg) (prod.snd (sec f z))⁻¹)) sorry sorry /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M` and a map of `comm_monoid`s `g : M β†’* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : M, y ∈ S`. -/ theorem lift_mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) (x : M) (y : β†₯S) : coe_fn (lift f hg) (mk' f x y) = coe_fn g x * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict g S) hg) y⁻¹) := sorry /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M`, if a `comm_monoid` map `g : M β†’* P` induces a map `f.lift hg : N β†’* P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.lift_spec {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} (hg : βˆ€ (y : β†₯S), is_add_unit (coe_fn g ↑y)) (z : N) (v : P) : coe_fn (add_submonoid.localization_map.lift f hg) z = v ↔ coe_fn g (prod.fst (add_submonoid.localization_map.sec f z)) = coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z)) + v := add_submonoid.localization_map.add_neg_left hg (prod.snd (add_submonoid.localization_map.sec f z)) (coe_fn g (prod.fst (add_submonoid.localization_map.sec f z))) v /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M`, if a `comm_monoid` map `g : M β†’* P` induces a map `f.lift hg : N β†’* P` then for all `z : N, v w : P`, we have `f.lift hg z * w = v ↔ g x * w = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.lift_spec_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} (hg : βˆ€ (y : β†₯S), is_add_unit (coe_fn g ↑y)) (z : N) (w : P) (v : P) : coe_fn (add_submonoid.localization_map.lift f hg) z + w = v ↔ coe_fn g (prod.fst (add_submonoid.localization_map.sec f z)) + w = coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z)) + v := sorry theorem lift_mk'_spec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) (x : M) (v : P) (y : β†₯S) : coe_fn (lift f hg) (mk' f x y) = v ↔ coe_fn g x = coe_fn g ↑y * v := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (lift f hg) (mk' f x y) = v ↔ coe_fn g x = coe_fn g ↑y * v)) (lift_mk' f hg x y))) (mul_inv_left hg y (coe_fn g x) v) /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M`, if a `comm_monoid` map `g : M β†’* P` induces a map `f.lift hg : N β†’* P` then for all `z : N`, we have `f.lift hg z * g y = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem lift_mul_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) (z : N) : coe_fn (lift f hg) z * coe_fn g ↑(prod.snd (sec f z)) = coe_fn g (prod.fst (sec f z)) := sorry /-- Given a localization map `f : M β†’* N` for a submonoid `S βŠ† M`, if a `comm_monoid` map `g : M β†’* P` induces a map `f.lift hg : N β†’* P` then for all `z : N`, we have `g y * f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.lift_add_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} (hg : βˆ€ (y : β†₯S), is_add_unit (coe_fn g ↑y)) (z : N) : coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z)) + coe_fn (add_submonoid.localization_map.lift f hg) z = coe_fn g (prod.fst (add_submonoid.localization_map.sec f z)) := sorry @[simp] theorem lift_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) (x : M) : coe_fn (lift f hg) (coe_fn (to_map f) x) = coe_fn g x := sorry theorem Mathlib.add_submonoid.localization_map.lift_eq_iff {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} (hg : βˆ€ (y : β†₯S), is_add_unit (coe_fn g ↑y)) {x : M Γ— β†₯S} {y : M Γ— β†₯S} : coe_fn (add_submonoid.localization_map.lift f hg) (add_submonoid.localization_map.mk' f (prod.fst x) (prod.snd x)) = coe_fn (add_submonoid.localization_map.lift f hg) (add_submonoid.localization_map.mk' f (prod.fst y) (prod.snd y)) ↔ coe_fn g (prod.fst x + ↑(prod.snd y)) = coe_fn g (prod.fst y + ↑(prod.snd x)) := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.lift_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} (hg : βˆ€ (y : β†₯S), is_add_unit (coe_fn g ↑y)) : add_monoid_hom.comp (add_submonoid.localization_map.lift f hg) (add_submonoid.localization_map.to_map f) = g := add_monoid_hom.ext fun (x : M) => add_submonoid.localization_map.lift_eq f hg x @[simp] theorem lift_of_comp {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (j : N β†’* P) : lift f (is_unit_comp f j) = j := sorry theorem epic_of_localization_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {j : N β†’* P} {k : N β†’* P} (h : βˆ€ (a : M), coe_fn (monoid_hom.comp j (to_map f)) a = coe_fn (monoid_hom.comp k (to_map f)) a) : j = k := sorry theorem Mathlib.add_submonoid.localization_map.lift_unique {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} (hg : βˆ€ (y : β†₯S), is_add_unit (coe_fn g ↑y)) {j : N β†’+ P} (hj : βˆ€ (x : M), coe_fn j (coe_fn (add_submonoid.localization_map.to_map f) x) = coe_fn g x) : add_submonoid.localization_map.lift f hg = j := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.lift_id {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : N) : coe_fn (add_submonoid.localization_map.lift f (add_submonoid.localization_map.map_units f)) x = x := iff.mp add_monoid_hom.ext_iff (add_submonoid.localization_map.lift_of_comp f (add_monoid_hom.id N)) x /-- Given two localization maps `f : M β†’* N, k : M β†’* P` for a submonoid `S βŠ† M`, the hom from `P` to `N` induced by `f` is left inverse to the hom from `N` to `P` induced by `k`. -/ @[simp] theorem lift_left_inverse {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : localization_map S P} (z : N) : coe_fn (lift k (map_units f)) (coe_fn (lift f (map_units k)) z) = z := sorry theorem lift_surjective_iff {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) : function.surjective ⇑(lift f hg) ↔ βˆ€ (v : P), βˆƒ (x : M Γ— β†₯S), v * coe_fn g ↑(prod.snd x) = coe_fn g (prod.fst x) := sorry theorem lift_injective_iff {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} (hg : βˆ€ (y : β†₯S), is_unit (coe_fn g ↑y)) : function.injective ⇑(lift f hg) ↔ βˆ€ (x y : M), coe_fn (to_map f) x = coe_fn (to_map f) y ↔ coe_fn g x = coe_fn g y := sorry /-- Given a `comm_monoid` homomorphism `g : M β†’* P` where for submonoids `S βŠ† M, T βŠ† P` we have `g(S) βŠ† T`, the induced monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M β†’* N` and `k : P β†’* Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : M Γ— S` are such that `z = f x * (f y)⁻¹`. -/ def map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} {T : submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] (k : localization_map T Q) : N β†’* Q := lift f sorry theorem Mathlib.add_submonoid.localization_map.map_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} {T : add_submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} (x : M) : coe_fn (add_submonoid.localization_map.map f hy k) (coe_fn (add_submonoid.localization_map.to_map f) x) = coe_fn (add_submonoid.localization_map.to_map k) (coe_fn g x) := add_submonoid.localization_map.lift_eq f (fun (y : β†₯S) => add_submonoid.localization_map.map_units k { val := coe_fn g ↑y, property := hy y }) x @[simp] theorem Mathlib.add_submonoid.localization_map.map_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} {T : add_submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} : add_monoid_hom.comp (add_submonoid.localization_map.map f hy k) (add_submonoid.localization_map.to_map f) = add_monoid_hom.comp (add_submonoid.localization_map.to_map k) g := add_submonoid.localization_map.lift_comp f fun (y : β†₯S) => add_submonoid.localization_map.map_units k { val := coe_fn g ↑y, property := hy y } theorem map_mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} {T : submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} (x : M) (y : β†₯S) : coe_fn (map f hy k) (mk' f x y) = mk' k (coe_fn g x) { val := coe_fn g ↑y, property := hy y } := sorry /-- Given localization maps `f : M β†’* N, k : P β†’* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M β†’* P` induces a `f.map hy k : N β†’* Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) * u` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem map_spec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} {T : submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} (z : N) (u : Q) : coe_fn (map f hy k) z = u ↔ coe_fn (to_map k) (coe_fn g (prod.fst (sec f z))) = coe_fn (to_map k) (coe_fn g ↑(prod.snd (sec f z))) * u := lift_spec f (fun (y : β†₯S) => map_units k { val := coe_fn g ↑y, property := hy y }) z u /-- Given localization maps `f : M β†’* N, k : P β†’* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M β†’* P` induces a `f.map hy k : N β†’* Q`, then for all `z : N`, we have `f.map hy k z * k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem map_mul_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} {T : submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} (z : N) : coe_fn (map f hy k) z * coe_fn (to_map k) (coe_fn g ↑(prod.snd (sec f z))) = coe_fn (to_map k) (coe_fn g (prod.fst (sec f z))) := lift_mul_right f (fun (y : β†₯S) => map_units k { val := coe_fn g ↑y, property := hy y }) z /-- Given localization maps `f : M β†’* N, k : P β†’* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M β†’* P` induces a `f.map hy k : N β†’* Q`, then for all `z : N`, we have `k (g y) * f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.map_add_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} {T : add_submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} (z : N) : coe_fn (add_submonoid.localization_map.to_map k) (coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z))) + coe_fn (add_submonoid.localization_map.map f hy k) z = coe_fn (add_submonoid.localization_map.to_map k) (coe_fn g (prod.fst (add_submonoid.localization_map.sec f z))) := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.map_id {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (z : N) : coe_fn (add_submonoid.localization_map.map f (fun (y : β†₯S) => (fun (this : coe_fn (add_monoid_hom.id M) ↑y ∈ S) => this) (subtype.property y)) f) z = z := add_submonoid.localization_map.lift_id f z /-- If `comm_monoid` homs `g : M β†’* P, l : P β†’* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ theorem map_comp_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M β†’* P} {T : submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} {A : Type u_5} [comm_monoid A] {U : submonoid A} {R : Type u_6} [comm_monoid R] (j : localization_map U R) {l : P β†’* A} (hl : βˆ€ (w : β†₯T), coe_fn l ↑w ∈ U) : monoid_hom.comp (map k hl j) (map f hy k) = map f (fun (x : β†₯S) => (fun (this : coe_fn (monoid_hom.comp l g) ↑x ∈ U) => this) (hl { val := coe_fn g ↑x, property := hy x })) j := sorry /-- If `comm_monoid` homs `g : M β†’* P, l : P β†’* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ theorem Mathlib.add_submonoid.localization_map.map_map {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M β†’+ P} {T : add_submonoid P} (hy : βˆ€ (y : β†₯S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {A : Type u_5} [add_comm_monoid A] {U : add_submonoid A} {R : Type u_6} [add_comm_monoid R] (j : add_submonoid.localization_map U R) {l : P β†’+ A} (hl : βˆ€ (w : β†₯T), coe_fn l ↑w ∈ U) (x : N) : coe_fn (add_submonoid.localization_map.map k hl j) (coe_fn (add_submonoid.localization_map.map f hy k) x) = coe_fn (add_submonoid.localization_map.map f (fun (x : β†₯S) => (fun (this : coe_fn (add_monoid_hom.comp l g) ↑x ∈ U) => this) (hl { val := coe_fn g ↑x, property := hy x })) j) x := sorry /-- Given `x : M`, the type of `comm_monoid` homomorphisms `f : M β†’* N` such that `N` is isomorphic to the localization of `M` at the submonoid generated by `x`. -/ def away_map {M : Type u_1} [comm_monoid M] (x : M) (N' : Type u_2) [comm_monoid N'] := localization_map (powers x) N' /-- Given `x : M` and a localization map `F : M β†’* N` away from `x`, `inv_self` is `(F x)⁻¹`. -/ def away_map.inv_self {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] (x : M) (F : away_map x N) : N := mk' F 1 { val := x, property := sorry } /-- Given `x : M`, a localization map `F : M β†’* N` away from `x`, and a map of `comm_monoid`s `g : M β†’* P` such that `g x` is invertible, the homomorphism induced from `N` to `P` sending `z : N` to `g y * (g x)⁻ⁿ`, where `y : M, n : β„•` are such that `z = F y * (F x)⁻ⁿ`. -/ def away_map.lift {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] {g : M β†’* P} (x : M) (F : away_map x N) (hg : is_unit (coe_fn g x)) : N β†’* P := lift F sorry @[simp] theorem away_map.lift_eq {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] {g : M β†’* P} (x : M) (F : away_map x N) (hg : is_unit (coe_fn g x)) (a : M) : coe_fn (away_map.lift x F hg) (coe_fn (to_map F) a) = coe_fn g a := lift_eq F (away_map.lift._proof_1 x hg) a @[simp] theorem away_map.lift_comp {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] {g : M β†’* P} (x : M) (F : away_map x N) (hg : is_unit (coe_fn g x)) : monoid_hom.comp (away_map.lift x F hg) (to_map F) = g := lift_comp F (away_map.lift._proof_1 x hg) /-- Given `x y : M` and localization maps `F : M β†’* N, G : M β†’* P` away from `x` and `x * y` respectively, the homomorphism induced from `N` to `P`. -/ def away_to_away_right {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (x : M) (F : away_map x N) (y : M) (G : away_map (x * y) P) : N β†’* P := away_map.lift x F sorry end localization_map end submonoid namespace add_submonoid namespace localization_map /-- Given `x : A` and a localization map `F : A β†’+ B` away from `x`, `neg_self` is `- (F x)`. -/ def away_map.neg_self {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) : B := mk' F 0 { val := x, property := sorry } /-- Given `x : A`, a localization map `F : A β†’+ B` away from `x`, and a map of `add_comm_monoid`s `g : A β†’+ C` such that `g x` is invertible, the homomorphism induced from `B` to `C` sending `z : B` to `g y - n β€’ g x`, where `y : A, n : β„•` are such that `z = F y - n β€’ F x`. -/ def away_map.lift {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] {g : A β†’+ C} (hg : is_add_unit (coe_fn g x)) : B β†’+ C := lift F sorry @[simp] theorem away_map.lift_eq {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] {g : A β†’+ C} (hg : is_add_unit (coe_fn g x)) (a : A) : coe_fn (away_map.lift x F hg) (coe_fn (to_map F) a) = coe_fn g a := lift_eq F (away_map.lift._proof_1 x hg) a @[simp] theorem away_map.lift_comp {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] {g : A β†’+ C} (hg : is_add_unit (coe_fn g x)) : add_monoid_hom.comp (away_map.lift x F hg) (to_map F) = g := lift_comp F (away_map.lift._proof_1 x hg) /-- Given `x y : A` and localization maps `F : A β†’+ B, G : A β†’+ C` away from `x` and `x + y` respectively, the homomorphism induced from `B` to `C`. -/ def away_to_away_right {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] (y : A) (G : away_map (x + y) C) : B β†’+ C := away_map.lift x F sorry end localization_map end add_submonoid namespace submonoid namespace localization_map /-- If `f : M β†’* N` and `k : M β†’* P` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `P`. -/ def mul_equiv_of_localizations {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (k : localization_map S P) : N ≃* P := mul_equiv.mk (⇑(lift f (map_units k))) (⇑(lift k (map_units f))) (lift_left_inverse f) (lift_left_inverse k) sorry @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} {x : N} : coe_fn (add_submonoid.localization_map.add_equiv_of_localizations f k) x = coe_fn (add_submonoid.localization_map.lift f (add_submonoid.localization_map.map_units k)) x := rfl @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_symm_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} {x : P} : coe_fn (add_equiv.symm (add_submonoid.localization_map.add_equiv_of_localizations f k)) x = coe_fn (add_submonoid.localization_map.lift k (add_submonoid.localization_map.map_units f)) x := rfl theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_symm_eq_add_equiv_of_localizations {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} : add_equiv.symm (add_submonoid.localization_map.add_equiv_of_localizations k f) = add_submonoid.localization_map.add_equiv_of_localizations f k := rfl /-- If `f : M β†’* N` is a localization map for a submonoid `S` and `k : N ≃* P` is an isomorphism of `comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`. -/ def of_mul_equiv_of_localizations {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (k : N ≃* P) : localization_map S P := monoid_hom.to_localization_map (monoid_hom.comp (mul_equiv.to_monoid_hom k) (to_map f)) sorry sorry sorry @[simp] theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_localizations_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : N ≃+ P} (x : M) : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f k)) x = coe_fn k (coe_fn (add_submonoid.localization_map.to_map f) x) := rfl theorem of_mul_equiv_of_localizations_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} : to_map (of_mul_equiv_of_localizations f k) = monoid_hom.comp (mul_equiv.to_monoid_hom k) (to_map f) := rfl theorem symm_comp_of_mul_equiv_of_localizations_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} (x : M) : coe_fn (mul_equiv.symm k) (coe_fn (to_map (of_mul_equiv_of_localizations f k)) x) = coe_fn (to_map f) x := mul_equiv.symm_apply_apply k (coe_fn (to_map f) x) theorem symm_comp_of_mul_equiv_of_localizations_apply' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : P ≃* N} (x : M) : coe_fn k (coe_fn (to_map (of_mul_equiv_of_localizations f (mul_equiv.symm k))) x) = coe_fn (to_map f) x := mul_equiv.apply_symm_apply k (coe_fn (to_map f) x) theorem of_mul_equiv_of_localizations_eq_iff_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} {x : M} {y : P} : coe_fn (to_map (of_mul_equiv_of_localizations f k)) x = y ↔ coe_fn (to_map f) x = coe_fn (mul_equiv.symm k) y := iff.symm (equiv.eq_symm_apply (mul_equiv.to_equiv k)) theorem mul_equiv_of_localizations_right_inv {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (k : localization_map S P) : of_mul_equiv_of_localizations f (mul_equiv_of_localizations f k) = k := to_map_injective (lift_comp f (map_units k)) theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_right_inv_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} {x : M} : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_submonoid.localization_map.add_equiv_of_localizations f k))) x = coe_fn (add_submonoid.localization_map.to_map k) x := iff.mp add_submonoid.localization_map.ext_iff (add_submonoid.localization_map.add_equiv_of_localizations_right_inv f k) x theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_left_neg {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) (k : N ≃+ P) : add_submonoid.localization_map.add_equiv_of_localizations f (add_submonoid.localization_map.of_add_equiv_of_localizations f k) = k := add_equiv.ext (iff.mp add_monoid_hom.ext_iff (add_submonoid.localization_map.lift_of_comp f (add_equiv.to_add_monoid_hom k))) @[simp] theorem mul_equiv_of_localizations_left_inv_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} (x : N) : coe_fn (mul_equiv_of_localizations f (of_mul_equiv_of_localizations f k)) x = coe_fn k x := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_localizations_id {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) : add_submonoid.localization_map.of_add_equiv_of_localizations f (add_equiv.refl N) = f := sorry theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_localizations_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {Q : Type u_4} [add_comm_monoid Q] {k : N ≃+ P} {j : P ≃+ Q} : add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_equiv.trans k j)) = add_monoid_hom.comp (add_equiv.to_add_monoid_hom j) (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f k)) := sorry /-- Given `comm_monoid`s `M, P` and submonoids `S βŠ† M, T βŠ† P`, if `f : M β†’* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`. -/ def Mathlib.add_submonoid.localization_map.of_add_equiv_of_dom {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {k : P ≃+ M} (H : add_submonoid.map (add_equiv.to_add_monoid_hom k) T = S) : add_submonoid.localization_map T N := add_monoid_hom.to_localization_map (add_monoid_hom.comp (add_submonoid.localization_map.to_map f) (add_equiv.to_add_monoid_hom k)) sorry sorry sorry @[simp] theorem of_mul_equiv_of_dom_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {k : P ≃* M} (H : map (mul_equiv.to_monoid_hom k) T = S) (x : P) : coe_fn (to_map (of_mul_equiv_of_dom f H)) x = coe_fn (to_map f) (coe_fn k x) := rfl theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_dom_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {k : P ≃+ M} (H : add_submonoid.map (add_equiv.to_add_monoid_hom k) T = S) : add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_dom f H) = add_monoid_hom.comp (add_submonoid.localization_map.to_map f) (add_equiv.to_add_monoid_hom k) := rfl theorem of_mul_equiv_of_dom_comp_symm {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {k : P ≃* M} (H : map (mul_equiv.to_monoid_hom k) T = S) (x : M) : coe_fn (to_map (of_mul_equiv_of_dom f H)) (coe_fn (mul_equiv.symm k) x) = coe_fn (to_map f) x := congr_arg (⇑(to_map f)) (mul_equiv.apply_symm_apply k x) theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_dom_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {k : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom (add_equiv.symm k)) T = S) (x : M) : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_dom f H)) (coe_fn k x) = coe_fn (add_submonoid.localization_map.to_map f) x := congr_arg (⇑(add_submonoid.localization_map.to_map f)) (add_equiv.symm_apply_apply k x) /-- A special case of `f ∘ id = f`, `f` a localization map. -/ @[simp] theorem of_mul_equiv_of_dom_id {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) : of_mul_equiv_of_dom f ((fun (this : map (mul_equiv.to_monoid_hom (mul_equiv.refl M)) S = S) => this) (ext fun (x : M) => { mp := fun (_x : x ∈ map (mul_equiv.to_monoid_hom (mul_equiv.refl M)) S) => (fun (_a : x ∈ map (mul_equiv.to_monoid_hom (mul_equiv.refl M)) S) => Exists.dcases_on _a fun (w : M) (h : w ∈ ↑S ∧ coe_fn (mul_equiv.to_monoid_hom (mul_equiv.refl M)) w = x) => and.dcases_on h fun (h_left : w ∈ ↑S) (h_right : coe_fn (mul_equiv.to_monoid_hom (mul_equiv.refl M)) w = x) => idRhs ((fun (_x : M) => _x ∈ S) x) (h_right β–Έ h_left)) _x, mpr := fun (h : x ∈ S) => Exists.intro x { left := h, right := rfl } })) = f := sorry /-- Given localization maps `f : M β†’* N, k : P β†’* U` for submonoids `S, T` respectively, an isomorphism `j : M ≃* P` such that `j(S) = T` induces an isomorphism of localizations `N ≃* U`. -/ def Mathlib.add_submonoid.localization_map.add_equiv_of_add_equiv {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] (k : add_submonoid.localization_map T Q) {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) : N ≃+ Q := add_submonoid.localization_map.add_equiv_of_localizations f (add_submonoid.localization_map.of_add_equiv_of_dom k H) @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_add_equiv_eq_map_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) (x : N) : coe_fn (add_submonoid.localization_map.add_equiv_of_add_equiv f k H) x = coe_fn (add_submonoid.localization_map.map f (fun (y : β†₯S) => (fun (this : coe_fn (add_equiv.to_add_monoid_hom j) ↑y ∈ T) => this) (H β–Έ set.mem_image_of_mem (⇑j) (subtype.property y))) k) x := rfl theorem mul_equiv_of_mul_equiv_eq_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} {j : M ≃* P} (H : map (mul_equiv.to_monoid_hom j) S = T) : mul_equiv.to_monoid_hom (mul_equiv_of_mul_equiv f k H) = map f (fun (y : β†₯S) => (fun (this : coe_fn (mul_equiv.to_monoid_hom j) ↑y ∈ T) => this) (H β–Έ set.mem_image_of_mem (⇑j) (subtype.property y))) k := rfl @[simp] theorem mul_equiv_of_mul_equiv_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} {j : M ≃* P} (H : map (mul_equiv.to_monoid_hom j) S = T) (x : M) : coe_fn (mul_equiv_of_mul_equiv f k H) (coe_fn (to_map f) x) = coe_fn (to_map k) (coe_fn j x) := map_eq f (fun (y : β†₯S) => H β–Έ set.mem_image_of_mem (⇑j) (subtype.property y)) x @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_add_equiv_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) (x : M) (y : β†₯S) : coe_fn (add_submonoid.localization_map.add_equiv_of_add_equiv f k H) (add_submonoid.localization_map.mk' f x y) = add_submonoid.localization_map.mk' k (coe_fn j x) { val := coe_fn j ↑y, property := H β–Έ set.mem_image_of_mem (⇑j) (subtype.property y) } := add_submonoid.localization_map.map_mk' f (fun (y : β†₯S) => H β–Έ set.mem_image_of_mem (⇑j) (subtype.property y)) x y @[simp] theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_add_equiv_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) (x : M) : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_submonoid.localization_map.add_equiv_of_add_equiv f k H))) x = coe_fn (add_submonoid.localization_map.to_map k) (coe_fn j x) := sorry theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_add_equiv {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) : add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_submonoid.localization_map.add_equiv_of_add_equiv f k H)) = add_monoid_hom.comp (add_submonoid.localization_map.to_map k) (add_equiv.to_add_monoid_hom j) := add_monoid_hom.ext (add_submonoid.localization_map.of_add_equiv_of_add_equiv_apply f H) end localization_map end submonoid namespace localization /-- Natural hom sending `x : M`, `M` a `comm_monoid`, to the equivalence class of `(x, 1)` in the localization of `M` at a submonoid. -/ def monoid_of {M : Type u_1} [comm_monoid M] (S : submonoid M) : submonoid.localization_map S (localization S) := submonoid.localization_map.mk (monoid_hom.to_fun (monoid_hom.comp (con.mk' (r S)) (monoid_hom.inl M β†₯S))) sorry sorry sorry sorry sorry theorem Mathlib.add_localization.mk_zero_eq_add_monoid_of_mk {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} (x : M) : add_localization.mk x 0 = coe_fn (add_submonoid.localization_map.to_map (add_localization.add_monoid_of S)) x := rfl theorem Mathlib.add_localization.mk_eq_add_monoid_of_mk'_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} (x : M) (y : β†₯S) : add_localization.mk x y = add_submonoid.localization_map.mk' (add_localization.add_monoid_of S) x y := sorry @[simp] theorem Mathlib.add_localization.mk_eq_add_monoid_of_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} : add_localization.mk = add_submonoid.localization_map.mk' (add_localization.add_monoid_of S) := funext fun (_x : M) => funext fun (_x_1 : β†₯S) => add_localization.mk_eq_add_monoid_of_mk'_apply _x _x_1 /-- Given a localization map `f : M β†’* N` for a submonoid `S`, we get an isomorphism between the localization of `M` at `S` as a quotient type and `N`. -/ def mul_equiv_of_quotient {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : submonoid.localization_map S N) : localization S ≃* N := submonoid.localization_map.mul_equiv_of_localizations (monoid_of S) f @[simp] theorem mul_equiv_of_quotient_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : localization S) : coe_fn (mul_equiv_of_quotient f) x = coe_fn (submonoid.localization_map.lift (monoid_of S) (submonoid.localization_map.map_units f)) x := rfl @[simp] theorem mul_equiv_of_quotient_mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : M) (y : β†₯S) : coe_fn (mul_equiv_of_quotient f) (submonoid.localization_map.mk' (monoid_of S) x y) = submonoid.localization_map.mk' f x y := submonoid.localization_map.lift_mk' (monoid_of S) (submonoid.localization_map.map_units f) x y theorem mul_equiv_of_quotient_mk {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : M) (y : β†₯S) : coe_fn (mul_equiv_of_quotient f) (mk x y) = submonoid.localization_map.mk' f x y := sorry @[simp] theorem Mathlib.add_localization.add_equiv_of_quotient_add_monoid_of {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (x : M) : coe_fn (add_localization.add_equiv_of_quotient f) (coe_fn (add_submonoid.localization_map.to_map (add_localization.add_monoid_of S)) x) = coe_fn (add_submonoid.localization_map.to_map f) x := add_submonoid.localization_map.lift_eq (add_localization.add_monoid_of S) (add_submonoid.localization_map.map_units f) x @[simp] theorem Mathlib.add_localization.add_equiv_of_quotient_symm_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (x : M) (y : β†₯S) : coe_fn (add_equiv.symm (add_localization.add_equiv_of_quotient f)) (add_submonoid.localization_map.mk' f x y) = add_submonoid.localization_map.mk' (add_localization.add_monoid_of S) x y := add_submonoid.localization_map.lift_mk' f (add_submonoid.localization_map.map_units (add_localization.add_monoid_of S)) x y theorem Mathlib.add_localization.add_equiv_of_quotient_symm_mk {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (x : M) (y : β†₯S) : coe_fn (add_equiv.symm (add_localization.add_equiv_of_quotient f)) (add_submonoid.localization_map.mk' f x y) = add_localization.mk x y := sorry @[simp] theorem mul_equiv_of_quotient_symm_monoid_of {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : M) : coe_fn (mul_equiv.symm (mul_equiv_of_quotient f)) (coe_fn (submonoid.localization_map.to_map f) x) = coe_fn (submonoid.localization_map.to_map (monoid_of S)) x := submonoid.localization_map.lift_eq f (submonoid.localization_map.map_units (monoid_of S)) x /-- Given `x : M`, the localization of `M` at the submonoid generated by `x`, as a quotient. -/ def Mathlib.add_localization.away {M : Type u_1} [add_comm_monoid M] (x : M) := add_localization (add_submonoid.multiples x) /-- Given `x : M`, `inv_self` is `x⁻¹` in the localization (as a quotient type) of `M` at the submonoid generated by `x`. -/ def away.inv_self {M : Type u_1} [comm_monoid M] (x : M) : away x := mk 1 { val := x, property := sorry } /-- Given `x : M`, the natural hom sending `y : M`, `M` a `comm_monoid`, to the equivalence class of `(y, 1)` in the localization of `M` at the submonoid generated by `x`. -/ def away.monoid_of {M : Type u_1} [comm_monoid M] (x : M) : submonoid.localization_map.away_map x (away x) := monoid_of (submonoid.powers x) @[simp] theorem Mathlib.add_localization.away.mk_eq_add_monoid_of_mk' {M : Type u_1} [add_comm_monoid M] (x : M) : add_localization.mk = add_submonoid.localization_map.mk' (add_localization.away.add_monoid_of x) := add_localization.mk_eq_add_monoid_of_mk' /-- Given `x : M` and a localization map `f : M β†’* N` away from `x`, we get an isomorphism between the localization of `M` at the submonoid generated by `x` as a quotient type and `N`. -/ def away.mul_equiv_of_quotient {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] (x : M) (f : submonoid.localization_map.away_map x N) : away x ≃* N := mul_equiv_of_quotient f end Mathlib
99d48d26132e7ec8e4cd3e0a3ed9ec69758473a7
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/coeIssue1.lean
83c04e8215c52a86c44ec88b23b2beaf1ab5f2c2
[ "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
1,282
lean
-- From @joehendrix -- The imul doesn't type check as Lean won't try to coerce from a reg (bv 64) to a expr (bv ?u) inductive MCType | bv : Nat β†’ MCType open MCType inductive Reg : MCType β†’ Type | rax (n : Nat) : Reg (bv n) inductive Expr : MCType β†’ Type | r : βˆ€{tp:MCType}, Reg tp β†’ Expr tp | sextC {s:Nat} (x : Expr (bv s)) (t:Nat) : Expr (bv t) instance reg_is_expr {tp:MCType} : Coe (Reg tp) (Expr tp) := ⟨Expr.r⟩ def bvmul {w:Nat} (x y : Expr (bv w)) : Expr (bv w) := x /- Remark: Joe's original example used the following definition. ``` def sext {s:Nat} (x : Expr (bv s)) (t:Nat) : Expr (bv t) := Expr.sextC x t ``` This definition is bad because the parameter `s` is unconstrained. Type class resolution gets stuck at ``` CoeT (Reg (bv 64)) (Reg.rax 64) (Expr (bv ?m_1)) ``` It would have to set `?m_1 := 64` which is not allowed since TC should not change external TC metavariables. I fixed the problem by changing the definition. Now, type inference will enforce that `?m_1` must be 64, and TC will be able to synthesize the instance. -/ def sext {s:Nat} (x : Expr (bv s)) (n:Nat) : Expr (bv (s+n)) := Expr.sextC x (s+n) new_frontend open MCType variables {u:Nat} (e : Expr (bv 64)) #check (bvmul (sext (Reg.rax 64) 64) (sext e _) : Expr (bv 128))
fb781461e97cc00dd4b460da77f964d18d07f3a0
fbf512ee44de430e3d3c5869751ad95325c938d7
/rev.lean
f228565ecd5c8a2cddddb0b13abfc09fdf7d1e51
[]
no_license
skbaek/clausify
4858c9005fb86a5e410bfcaa77524f82d955f655
d09b071bdcce7577c3fffacd0893b776285b1590
refs/heads/master
1,588,360,590,818
1,553,553,880,000
1,553,553,880,000
177,644,542
0
0
null
null
null
null
UTF-8
Lean
false
false
1,159
lean
open expr tactic meta def revert_cond (t : expr β†’ tactic bool) (x : expr) : tactic unit := mcond (t x) (revert x >> skip) skip meta def revert_cond_all (t : expr β†’ tactic bool) : tactic unit := do hs ← local_context, mmap (revert_cond t) hs, skip meta def is_hyp (x : expr) : tactic bool := infer_type x >>= is_prop meta def revert_hyps : tactic unit := revert_cond_all is_hyp >> skip meta def has_type (tx x : expr) : tactic bool := do sx ← infer_type x, return (sx = tx) meta def is_func_type (dx : expr) : expr β†’ bool | `(%%x β†’ %%y) := (x = dx) && (is_func_type y) | x := x = dx meta def is_pred_type (dx : expr) : expr β†’ bool | `(%%x β†’ %%y) := (x = dx) && (is_pred_type y) | x := x = `(Prop) meta def is_func (dx x : expr) : tactic bool := do y ← infer_type x, return $ is_func_type dx y meta def is_pred (dx x : expr) : tactic bool := do y ← infer_type x, return $ is_pred_type dx y -- Generalizes all free variables and hypotheses, -- and returns the expr of the domain. meta def rev (dx : expr) : tactic unit := do revert_hyps, revert_cond_all (is_func dx), revert_cond_all (is_pred dx)
faffad42c749d1f9cd953d1a890e739b60d32cac
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_1172.lean
f0e1f6e017424e9b3b5916a523cc6b8a8906392b
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
716
lean
import analysis.special_functions.exp_log open real variables a b c d : ℝ #check (exp_le_exp : exp a ≀ exp b ↔ a ≀ b) #check (exp_lt_exp : exp a < exp b ↔ a < b) #check (log_le_log : 0 < a β†’ 0 < b β†’ (log a ≀ log b ↔ a ≀ b)) #check (log_lt_log : 0 < a β†’ a < b β†’ log a < log b) #check (add_le_add : a ≀ b β†’ c ≀ d β†’ a + c ≀ b + d) #check (add_lt_add_of_le_of_lt : a ≀ b β†’ c < d β†’ a + c < b + d) #check (add_lt_add_of_lt_of_le : a < b β†’ c ≀ d β†’ a + c < b + d) #check (add_nonneg : 0 ≀ a β†’ 0 ≀ b β†’ 0 ≀ a + b) #check (add_pos : 0 < a β†’ 0 < b β†’ 0 < a + b) #check (add_pos_of_pos_of_nonneg : 0 < a β†’ 0 ≀ b β†’ 0 < a + b) #check (exp_pos : βˆ€ a, 0 < exp a)
ae243eef2187836ab4ae428cd2d1a23c3eded97b
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_751.lean
260e66458f1b49d8977b6261dbc564ae1c1589ad
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
217
lean
variables {p : Prop} namespace hidden -- BEGIN theorem id : p β†’ p := begin assume h : p, -- Assume `h : p`. It suffices to prove `p`. show p, from h, -- We show `p` by reiteration on `h`. end -- END end hidden
dffeacb83fe07e33693e42e4a05c6bdd01a56a6d
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/algebra/ordered_group.lean
5682fa388ef5496ba8ea36ef06f4ac2744e87aa2
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
27,437
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes HΓΆlzl Ordered monoids and groups. -/ import algebra.group order.bounded_lattice tactic.basic universe u variable {Ξ± : Type u} section old_structure_cmd set_option old_structure_cmd true /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that addition is an order embedding, i.e. `a + b ≀ a + c ↔ b ≀ c`. These monoids are automatically cancellative. -/ class ordered_comm_monoid (Ξ± : Type*) extends add_comm_monoid Ξ±, partial_order Ξ± := (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) (lt_of_add_lt_add_left : βˆ€ a b c : Ξ±, a + b < a + c β†’ b < c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≀ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ class canonically_ordered_monoid (Ξ± : Type*) extends ordered_comm_monoid Ξ±, lattice.order_bot Ξ± := (le_iff_exists_add : βˆ€a b:Ξ±, a ≀ b ↔ βˆƒc, b = a + c) end old_structure_cmd section ordered_comm_monoid variables [ordered_comm_monoid Ξ±] {a b c d : Ξ±} lemma add_le_add_left' (h : a ≀ b) : c + a ≀ c + b := ordered_comm_monoid.add_le_add_left a b h c lemma add_le_add_right' (h : a ≀ b) : a + c ≀ b + c := add_comm c a β–Έ add_comm c b β–Έ add_le_add_left' h lemma lt_of_add_lt_add_left' : a + b < a + c β†’ b < c := ordered_comm_monoid.lt_of_add_lt_add_left a b c lemma add_le_add' (h₁ : a ≀ b) (hβ‚‚ : c ≀ d) : a + c ≀ b + d := le_trans (add_le_add_right' h₁) (add_le_add_left' hβ‚‚) lemma le_add_of_nonneg_right' (h : 0 ≀ b) : a ≀ a + b := have a + b β‰₯ a + 0, from add_le_add_left' h, by rwa add_zero at this lemma le_add_of_nonneg_left' (h : 0 ≀ b) : a ≀ b + a := have 0 + a ≀ b + a, from add_le_add_right' h, by rwa zero_add at this lemma lt_of_add_lt_add_right' (h : a + b < c + b) : a < c := lt_of_add_lt_add_left' (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) -- here we start using properties of zero. lemma le_add_of_nonneg_of_le' (ha : 0 ≀ a) (hbc : b ≀ c) : b ≀ a + c := zero_add b β–Έ add_le_add' ha hbc lemma le_add_of_le_of_nonneg' (hbc : b ≀ c) (ha : 0 ≀ a) : b ≀ c + a := add_zero b β–Έ add_le_add' hbc ha lemma add_nonneg' (ha : 0 ≀ a) (hb : 0 ≀ b) : 0 ≀ a + b := le_add_of_nonneg_of_le' ha hb lemma add_pos_of_pos_of_nonneg' (ha : 0 < a) (hb : 0 ≀ b) : 0 < a + b := lt_of_lt_of_le ha $ le_add_of_nonneg_right' hb lemma add_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a + b := add_pos_of_pos_of_nonneg' ha $ le_of_lt hb lemma add_pos_of_nonneg_of_pos' (ha : 0 ≀ a) (hb : 0 < b) : 0 < a + b := lt_of_lt_of_le hb $ le_add_of_nonneg_left' ha lemma add_nonpos' (ha : a ≀ 0) (hb : b ≀ 0) : a + b ≀ 0 := zero_add (0:Ξ±) β–Έ (add_le_add' ha hb) lemma add_le_of_nonpos_of_le' (ha : a ≀ 0) (hbc : b ≀ c) : a + b ≀ c := zero_add c β–Έ add_le_add' ha hbc lemma add_le_of_le_of_nonpos' (hbc : b ≀ c) (ha : a ≀ 0) : b + a ≀ c := add_zero c β–Έ add_le_add' hbc ha lemma add_neg_of_neg_of_nonpos' (ha : a < 0) (hb : b ≀ 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) hb) ha lemma add_neg_of_nonpos_of_neg' (ha : a ≀ 0) (hb : b < 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hb lemma add_neg' (ha : a < 0) (hb : b < 0) : a + b < 0 := add_neg_of_nonpos_of_neg' (le_of_lt ha) hb lemma lt_add_of_nonneg_of_lt' (ha : 0 ≀ a) (hbc : b < c) : b < a + c := lt_of_lt_of_le hbc $ le_add_of_nonneg_left' ha lemma lt_add_of_lt_of_nonneg' (hbc : b < c) (ha : 0 ≀ a) : b < c + a := lt_of_lt_of_le hbc $ le_add_of_nonneg_right' ha lemma lt_add_of_pos_of_lt' (ha : 0 < a) (hbc : b < c) : b < a + c := lt_add_of_nonneg_of_lt' (le_of_lt ha) hbc lemma lt_add_of_lt_of_pos' (hbc : b < c) (ha : 0 < a) : b < c + a := lt_add_of_lt_of_nonneg' hbc (le_of_lt ha) lemma add_lt_of_nonpos_of_lt' (ha : a ≀ 0) (hbc : b < c) : a + b < c := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hbc lemma add_lt_of_lt_of_nonpos' (hbc : b < c) (ha : a ≀ 0) : b + a < c := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) ha) hbc lemma add_lt_of_neg_of_lt' (ha : a < 0) (hbc : b < c) : a + b < c := add_lt_of_nonpos_of_lt' (le_of_lt ha) hbc lemma add_lt_of_lt_of_neg' (hbc : b < c) (ha : a < 0) : b + a < c := add_lt_of_lt_of_nonpos' hbc (le_of_lt ha) lemma add_eq_zero_iff' (ha : 0 ≀ a) (hb : 0 ≀ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume hab : a + b = 0, have a ≀ 0, from hab β–Έ le_add_of_le_of_nonneg' (le_refl _) hb, have a = 0, from le_antisymm this ha, have b ≀ 0, from hab β–Έ le_add_of_nonneg_of_le' ha (le_refl _), have b = 0, from le_antisymm this hb, and.intro β€Ήa = 0β€Ί β€Ήb = 0β€Ί) (assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero]) lemma bit0_pos {a : Ξ±} (h : 0 < a) : 0 < bit0 a := add_pos' h h end ordered_comm_monoid namespace units instance [monoid Ξ±] [i : preorder Ξ±] : preorder (units Ξ±) := preorder.lift (coe : units Ξ± β†’ Ξ±) i @[simp] theorem coe_le_coe [monoid Ξ±] [preorder Ξ±] {a b : units Ξ±} : (a : Ξ±) ≀ b ↔ a ≀ b := iff.rfl @[simp] theorem coe_lt_coe [monoid Ξ±] [preorder Ξ±] {a b : units Ξ±} : (a : Ξ±) < b ↔ a < b := iff.rfl instance [monoid Ξ±] [i : partial_order Ξ±] : partial_order (units Ξ±) := partial_order.lift (coe : units Ξ± β†’ Ξ±) (by ext) i instance [monoid Ξ±] [i : linear_order Ξ±] : linear_order (units Ξ±) := linear_order.lift (coe : units Ξ± β†’ Ξ±) (by ext) i instance [monoid Ξ±] [i : decidable_linear_order Ξ±] : decidable_linear_order (units Ξ±) := decidable_linear_order.lift (coe : units Ξ± β†’ Ξ±) (by ext) i theorem max_coe [monoid Ξ±] [decidable_linear_order Ξ±] {a b : units Ξ±} : (↑(max a b) : Ξ±) = max a b := by by_cases a ≀ b; simp [max, h] theorem min_coe [monoid Ξ±] [decidable_linear_order Ξ±] {a b : units Ξ±} : (↑(min a b) : Ξ±) = min a b := by by_cases a ≀ b; simp [min, h] end units namespace with_zero open lattice instance [preorder Ξ±] : preorder (with_zero Ξ±) := with_bot.preorder instance [partial_order Ξ±] : partial_order (with_zero Ξ±) := with_bot.partial_order instance [partial_order Ξ±] : order_bot (with_zero Ξ±) := with_bot.order_bot instance [lattice Ξ±] : lattice (with_zero Ξ±) := with_bot.lattice instance [linear_order Ξ±] : linear_order (with_zero Ξ±) := with_bot.linear_order instance [decidable_linear_order Ξ±] : decidable_linear_order (with_zero Ξ±) := with_bot.decidable_linear_order def ordered_comm_monoid [ordered_comm_monoid Ξ±] (zero_le : βˆ€ a : Ξ±, 0 ≀ a) : ordered_comm_monoid (with_zero Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊒, refine ⟨λ b hβ‚‚, _, Ξ» hβ‚‚, h'.2 $ this _ _ hβ‚‚ _⟩, cases hβ‚‚, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left' $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca hβ‚‚, cases b with b, { rw le_antisymm h bot_le at hβ‚‚, exact ⟨_, hβ‚‚, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at hβ‚‚, simp at hβ‚‚, simp [hβ‚‚], exact ⟨_, rfl, by simpa using add_le_add_left' (zero_le b)⟩ }, { simp at h, cases c with c; change some _ = _ at hβ‚‚; simp [-add_comm] at hβ‚‚; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left' h } } } end end with_zero namespace with_top open lattice instance [add_semigroup Ξ±] : add_semigroup (with_top Ξ±) := { add := Ξ» o₁ oβ‚‚, o₁.bind (Ξ» a, oβ‚‚.map (Ξ» b, a + b)), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative Ξ±) _ } lemma coe_add [add_semigroup Ξ±] {a b : Ξ±} : ((a + b : Ξ±) : with_top Ξ±) = a + b := rfl instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_top Ξ±) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative Ξ±) _ } instance [add_monoid Ξ±] : add_monoid (with_top Ξ±) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @with_zero.monoid (multiplicative Ξ±) _ } instance [add_comm_monoid Ξ±] : add_comm_monoid (with_top Ξ±) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @with_zero.comm_monoid (multiplicative Ξ±) _ } instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (with_top Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊒, refine ⟨λ c hβ‚‚, _, Ξ» hβ‚‚, h'.2 $ this _ _ hβ‚‚ _⟩, cases hβ‚‚, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca hβ‚‚, cases c with c, {cases hβ‚‚}, cases b with b; cases hβ‚‚, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left' h⟩, } end @[simp] lemma zero_lt_top [ordered_comm_monoid Ξ±] : (0 : with_top Ξ±) < ⊀ := coe_lt_top 0 @[simp] lemma zero_lt_coe [ordered_comm_monoid Ξ±] (a : Ξ±) : (0 : with_top Ξ±) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_comm_monoid Ξ±] : βˆ€{a : with_top Ξ±}, a + ⊀ = ⊀ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_comm_monoid Ξ±] {a : with_top Ξ±} : ⊀ + a = ⊀ := rfl lemma add_eq_top [ordered_comm_monoid Ξ±] (a b : with_top Ξ±) : a + b = ⊀ ↔ a = ⊀ ∨ b = ⊀ := by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm] lemma add_lt_top [ordered_comm_monoid Ξ±] (a b : with_top Ξ±) : a + b < ⊀ ↔ a < ⊀ ∧ b < ⊀ := begin apply not_iff_not.1, simp [lt_top_iff_ne_top, add_eq_top], finish, apply classical.dec _, apply classical.dec _, end instance [canonically_ordered_monoid Ξ±] : canonically_ordered_monoid (with_top Ξ±) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≀ ⊀ ↔ βˆƒc, ⊀ = a + c, by simp; refine ⟨⊀, _⟩; cases a; refl | (some a), (some b) := show (a:with_top Ξ±) ≀ ↑b ↔ βˆƒc:with_top Ξ±, ↑b = ↑a + c, begin simp [canonically_ordered_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, simp [coe_add] }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊀ : with_top Ξ±) ≀ b ↔ βˆƒc:with_top Ξ±, ↑b = ⊀ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_comm_monoid } end with_top namespace with_bot open lattice instance [add_semigroup Ξ±] : add_semigroup (with_bot Ξ±) := with_top.add_semigroup instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_bot Ξ±) := with_top.add_comm_semigroup instance [add_monoid Ξ±] : add_monoid (with_bot Ξ±) := with_top.add_monoid instance [add_comm_monoid Ξ±] : add_comm_monoid (with_bot Ξ±) := with_top.add_comm_monoid instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (with_bot Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊒, refine ⟨λ b hβ‚‚, _, Ξ» hβ‚‚, h'.2 $ this _ _ hβ‚‚ _⟩, cases hβ‚‚, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca hβ‚‚, cases c with c, {cases hβ‚‚}, cases a with a; cases hβ‚‚, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left' h⟩, } end @[simp] lemma coe_zero [add_monoid Ξ±] : ((0 : Ξ±) : with_bot Ξ±) = 0 := rfl @[simp] lemma coe_add [add_semigroup Ξ±] (a b : Ξ±) : ((a + b : Ξ±) : with_bot Ξ±) = a + b := rfl @[simp] lemma bot_add [ordered_comm_monoid Ξ±] (a : with_bot Ξ±) : βŠ₯ + a = βŠ₯ := rfl @[simp] lemma add_bot [ordered_comm_monoid Ξ±] (a : with_bot Ξ±) : a + βŠ₯ = βŠ₯ := by cases a; refl instance has_one [has_one Ξ±] : has_one (with_bot Ξ±) := ⟨(1 : Ξ±)⟩ @[simp] lemma coe_one [has_one Ξ±] : ((1 : Ξ±) : with_bot Ξ±) = 1 := rfl end with_bot section canonically_ordered_monoid variables [canonically_ordered_monoid Ξ±] {a b c d : Ξ±} lemma le_iff_exists_add : a ≀ b ↔ βˆƒc, b = a + c := canonically_ordered_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : Ξ±) : 0 ≀ a := le_iff_exists_add.mpr ⟨a, by simp⟩ lemma bot_eq_zero : (βŠ₯ : Ξ±) = 0 := le_antisymm lattice.bot_le (zero_le βŠ₯) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≀ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h β–Έ le_refl a) protected lemma zero_lt_iff_ne_zero : 0 < a ↔ a β‰  0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm lemma le_add_left (h : a ≀ c) : a ≀ b + c := calc a = 0 + a : by simp ... ≀ b + c : add_le_add' (zero_le _) h lemma le_add_right (h : a ≀ b) : a ≀ b + c := calc a = a + 0 : by simp ... ≀ b + c : add_le_add' h (zero_le _) instance with_zero.canonically_ordered_monoid : canonically_ordered_monoid (with_zero Ξ±) := { le_iff_exists_add := Ξ» a b, begin cases a with a, { exact iff_of_true lattice.bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm lattice.bot_le) (by simp)) (Ξ» ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_comm_monoid zero_le } end canonically_ordered_monoid instance ordered_cancel_comm_monoid.to_ordered_comm_monoid [H : ordered_cancel_comm_monoid Ξ±] : ordered_comm_monoid Ξ± := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, ..H } section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid Ξ±] {a b c x y : Ξ±} @[simp] lemma add_le_add_iff_left (a : Ξ±) {b c : Ξ±} : a + b ≀ a + c ↔ b ≀ c := ⟨le_of_add_le_add_left, Ξ» h, add_le_add_left h _⟩ @[simp] lemma add_le_add_iff_right (c : Ξ±) : a + c ≀ b + c ↔ a ≀ b := add_comm c a β–Έ add_comm c b β–Έ add_le_add_iff_left c @[simp] lemma add_lt_add_iff_left (a : Ξ±) {b c : Ξ±} : a + b < a + c ↔ b < c := ⟨lt_of_add_lt_add_left, Ξ» h, add_lt_add_left h _⟩ @[simp] lemma add_lt_add_iff_right (c : Ξ±) : a + c < b + c ↔ a < b := add_comm c a β–Έ add_comm c b β–Έ add_lt_add_iff_left c @[simp] lemma le_add_iff_nonneg_right (a : Ξ±) {b : Ξ±} : a ≀ a + b ↔ 0 ≀ b := have a + 0 ≀ a + b ↔ 0 ≀ b, from add_le_add_iff_left a, by rwa add_zero at this @[simp] lemma le_add_iff_nonneg_left (a : Ξ±) {b : Ξ±} : a ≀ b + a ↔ 0 ≀ b := by rw [add_comm, le_add_iff_nonneg_right] @[simp] lemma lt_add_iff_pos_right (a : Ξ±) {b : Ξ±} : a < a + b ↔ 0 < b := have a + 0 < a + b ↔ 0 < b, from add_lt_add_iff_left a, by rwa add_zero at this @[simp] lemma lt_add_iff_pos_left (a : Ξ±) {b : Ξ±} : a < b + a ↔ 0 < b := by rw [add_comm, lt_add_iff_pos_right] @[simp] lemma add_le_iff_nonpos_left : x + y ≀ y ↔ x ≀ 0 := by { convert add_le_add_iff_right y, rw [zero_add] } @[simp] lemma add_le_iff_nonpos_right : x + y ≀ x ↔ y ≀ 0 := by { convert add_le_add_iff_left x, rw [add_zero] } @[simp] lemma add_lt_iff_neg_right : x + y < y ↔ x < 0 := by { convert add_lt_add_iff_right y, rw [zero_add] } @[simp] lemma add_lt_iff_neg_left : x + y < x ↔ y < 0 := by { convert add_lt_add_iff_left x, rw [add_zero] } lemma add_eq_zero_iff_eq_zero_of_nonneg (ha : 0 ≀ a) (hb : 0 ≀ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ hab : a + b = 0, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], Ξ» ⟨ha', hb'⟩, by rw [ha', hb', add_zero]⟩ lemma with_top.add_lt_add_iff_left : βˆ€{a b c : with_top Ξ±}, a < ⊀ β†’ (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊀ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { rw [← with_top.coe_add], exact with_top.coe_lt_top _ }, { rw [← with_top.coe_add, ← with_top.coe_add, with_top.coe_lt_coe], exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top Ξ±} : a < ⊀ β†’ (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_comm_monoid section ordered_comm_group /-- The `add_lt_add_left` field of `ordered_comm_group` is redundant, but it is in core so we can't remove it for now. This alternative constructor is the best we can do. -/ def ordered_comm_group.mk' {Ξ± : Type u} [add_comm_group Ξ±] [partial_order Ξ±] (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) : ordered_comm_group Ξ± := { add_le_add_left := add_le_add_left, add_lt_add_left := Ξ» a b h c, begin rw lt_iff_le_not_le at h, rw lt_iff_le_not_le, split, { apply add_le_add_left _ _ h.1 }, { intro w, replace w : -c + (c + b) ≀ -c + (c + a) := add_le_add_left _ _ w _, simp only [add_zero, add_comm, add_left_neg, add_left_comm] at w, exact h.2 w }, end, ..(by apply_instance : add_comm_group Ξ±), ..(by apply_instance : partial_order Ξ±) } variables [ordered_comm_group Ξ±] {a b c : Ξ±} lemma neg_neg_iff_pos {Ξ± : Type} [_inst_1 : ordered_comm_group Ξ±] {a : Ξ±} : -a < 0 ↔ 0 < a := ⟨ pos_of_neg_neg, neg_neg_of_pos ⟩ @[simp] lemma neg_le_neg_iff : -a ≀ -b ↔ b ≀ a := have a + b + -a ≀ a + b + -b ↔ -a ≀ -b, from add_le_add_iff_left _, by simp at this; simp [this] lemma neg_le : -a ≀ b ↔ -b ≀ a := have -a ≀ -(-b) ↔ -b ≀ a, from neg_le_neg_iff, by rwa neg_neg at this lemma le_neg : a ≀ -b ↔ b ≀ -a := have -(-a) ≀ -b ↔ b ≀ -a, from neg_le_neg_iff, by rwa neg_neg at this @[simp] lemma neg_nonpos : -a ≀ 0 ↔ 0 ≀ a := have -a ≀ -0 ↔ 0 ≀ a, from neg_le_neg_iff, by rwa neg_zero at this @[simp] lemma neg_nonneg : 0 ≀ -a ↔ a ≀ 0 := have -0 ≀ -a ↔ a ≀ 0, from neg_le_neg_iff, by rwa neg_zero at this @[simp] lemma neg_lt_neg_iff : -a < -b ↔ b < a := have a + b + -a < a + b + -b ↔ -a < -b, from add_lt_add_iff_left _, by simp at this; simp [this] lemma neg_lt_zero : -a < 0 ↔ 0 < a := have -a < -0 ↔ 0 < a, from neg_lt_neg_iff, by rwa neg_zero at this lemma neg_pos : 0 < -a ↔ a < 0 := have -0 < -a ↔ a < 0, from neg_lt_neg_iff, by rwa neg_zero at this lemma neg_lt : -a < b ↔ -b < a := have -a < -(-b) ↔ -b < a, from neg_lt_neg_iff, by rwa neg_neg at this lemma lt_neg : a < -b ↔ b < -a := have -(-a) < -b ↔ b < -a, from neg_lt_neg_iff, by rwa neg_neg at this lemma sub_le_sub_iff_left (a : Ξ±) {b c : Ξ±} : a - b ≀ a - c ↔ c ≀ b := (add_le_add_iff_left _).trans neg_le_neg_iff lemma sub_le_sub_iff_right (c : Ξ±) : a - c ≀ b - c ↔ a ≀ b := add_le_add_iff_right _ lemma sub_lt_sub_iff_left (a : Ξ±) {b c : Ξ±} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff lemma sub_lt_sub_iff_right (c : Ξ±) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≀ a - b ↔ b ≀ a := have a - a ≀ a - b ↔ b ≀ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≀ 0 ↔ a ≀ b := have a - b ≀ b - b ↔ a ≀ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_neg_add_iff_add_le : b ≀ -a + c ↔ a + b ≀ c := have -a + (a + b) ≀ -a + c ↔ a + b ≀ c, from add_le_add_iff_left _, by rwa neg_add_cancel_left at this lemma le_sub_iff_add_le' : b ≀ c - a ↔ a + b ≀ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≀ c - b ↔ a + b ≀ c := by rw [le_sub_iff_add_le', add_comm] @[simp] lemma neg_add_le_iff_le_add : -b + a ≀ c ↔ a ≀ b + c := have -b + a ≀ -b + (b + c) ↔ a ≀ b + c, from add_le_add_iff_left _, by rwa neg_add_cancel_left at this lemma sub_le_iff_le_add' : a - b ≀ c ↔ a ≀ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≀ b ↔ a ≀ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma add_neg_le_iff_le_add : a + -c ≀ b ↔ a ≀ b + c := sub_le_iff_le_add @[simp] lemma add_neg_le_iff_le_add' : a + -b ≀ c ↔ a ≀ b + c := sub_le_iff_le_add' lemma neg_add_le_iff_le_add' : -c + a ≀ b ↔ a ≀ b + c := by rw [neg_add_le_iff_le_add, add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≀ a - c ↔ c ≀ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≀ b - c ↔ c ≀ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≀ c ↔ a - c ≀ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≀ b - c ↔ c ≀ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm @[simp] lemma lt_neg_add_iff_add_lt : b < -a + c ↔ a + b < c := have -a + (a + b) < -a + c ↔ a + b < c, from add_lt_add_iff_left _, by rwa neg_add_cancel_left at this lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] @[simp] lemma neg_add_lt_iff_lt_add : -b + a < c ↔ a < b + c := have -b + a < -b + (b + c) ↔ a < b + c, from add_lt_add_iff_left _, by rwa neg_add_cancel_left at this lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] lemma neg_add_lt_iff_lt_add_right : -c + a < b ↔ a < b + c := by rw [neg_add_lt_iff_lt_add, add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : Ξ±) {b : Ξ±} : a - b ≀ a ↔ 0 ≀ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : Ξ±) {b : Ξ±} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_comm_group namespace decidable_linear_ordered_comm_group variables [s : decidable_linear_ordered_comm_group Ξ±] include s instance : decidable_linear_ordered_cancel_comm_monoid Ξ± := { le_of_add_le_add_left := Ξ» x y z, le_of_add_le_add_left, add_left_cancel := Ξ» x y z, add_left_cancel, add_right_cancel := Ξ» x y z, add_right_cancel, ..s } lemma eq_of_abs_sub_nonpos {a b : Ξ±} (h : abs (a - b) ≀ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm _ _ h (abs_nonneg (a - b))) end decidable_linear_ordered_comm_group set_option old_structure_cmd true /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_comm_group (Ξ± : Type*) extends add_comm_group Ξ± := (nonneg : Ξ± β†’ Prop) (pos : Ξ± β†’ Prop := Ξ» a, nonneg a ∧ Β¬ nonneg (neg a)) (pos_iff : βˆ€ a, pos a ↔ nonneg a ∧ Β¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : βˆ€ {a b}, nonneg a β†’ nonneg b β†’ nonneg (a + b)) (nonneg_antisymm : βˆ€ {a}, nonneg a β†’ nonneg (-a) β†’ a = 0) namespace nonneg_comm_group variable [s : nonneg_comm_group Ξ±] include s @[reducible] instance to_ordered_comm_group : ordered_comm_group Ξ± := { le := Ξ» a b, nonneg (b - a), lt := Ξ» a b, pos (b - a), lt_iff_le_not_le := Ξ» a b, by simp; rw [pos_iff]; simp, le_refl := Ξ» a, by simp [zero_nonneg], le_trans := Ξ» a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := Ξ» a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := Ξ» a b nab c, by simpa [(≀), preorder.le] using nab, add_lt_add_left := Ξ» a b nab c, by simpa [(<), preorder.lt] using nab, ..s } theorem nonneg_def {a : Ξ±} : nonneg a ↔ 0 ≀ a := show _ ↔ nonneg _, by simp theorem pos_def {a : Ξ±} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : Β¬ pos (0 : Ξ±) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : Ξ±} : 0 < a ↔ nonneg a ∧ Β¬ nonneg (-a) := pos_def.symm.trans (pos_iff Ξ± _) theorem nonneg_total_iff : (βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) ↔ (βˆ€ a b : Ξ±, a ≀ b ∨ b ≀ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, Ξ» h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ def to_decidable_linear_ordered_comm_group [decidable_pred (@nonneg Ξ± _)] (nonneg_total : βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_comm_group Ξ± := { le := (≀), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_eq := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_comm_group.to_ordered_comm_group _ s } end nonneg_comm_group namespace order_dual instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (order_dual Ξ±) := { add_le_add_left := Ξ» a b h c, @add_le_add_left' Ξ± _ b a c h, lt_of_add_lt_add_left := Ξ» a b c h, @lt_of_add_lt_add_left' Ξ± _ a c b h, ..order_dual.partial_order Ξ±, ..show add_comm_monoid Ξ±, by apply_instance } instance [ordered_cancel_comm_monoid Ξ±] : ordered_cancel_comm_monoid (order_dual Ξ±) := { le_of_add_le_add_left := Ξ» a b c : Ξ±, le_of_add_le_add_left, add_left_cancel := @add_left_cancel Ξ± _, add_right_cancel := @add_right_cancel Ξ± _, ..order_dual.ordered_comm_monoid } instance [ordered_comm_group Ξ±] : ordered_comm_group (order_dual Ξ±) := { add_lt_add_left := Ξ» a b : Ξ±, ordered_comm_group.add_lt_add_left b a, add_left_neg := Ξ» a : Ξ±, add_left_neg a, ..order_dual.ordered_comm_monoid, ..show add_comm_group Ξ±, by apply_instance } end order_dual
702367007c020e9bfb562f4dcf92e015df544a43
60bf3fa4185ec5075eaea4384181bfbc7e1dc319
/src/game/order/level07.lean
0d271930d837b2cb8c5c51bf126f4cc829231115
[ "Apache-2.0" ]
permissive
anrddh/real-number-game
660f1127d03a78fd35986c771d65c3132c5f4025
c708c4e02ec306c657e1ea67862177490db041b0
refs/heads/master
1,668,214,277,092
1,593,105,075,000
1,593,105,075,000
264,269,218
0
0
null
1,589,567,264,000
1,589,567,264,000
null
UTF-8
Lean
false
false
929
lean
import data.real.basic import data.real.irrational open real namespace xena -- hide /- # Chapter 2 : Order ## Level 7 Prove by example that there exist pairs of real numbers $a$ and $b$ such that $a \in \mathbb{R} \setminus \mathbb{Q}$, $b \in \mathbb{R} \setminus \mathbb{Q}$, but their sum $a + b$ is a rational number, $(a+b) \in \mathbb{Q}$. You may use this result in the Lean mathlib library: `irrational_sqrt_two : irrational (sqrt 2)` -/ /- Axiom : irrational_sqrt_two : irrational (sqrt 2) -/ /- Lemma Not true that for any $a$, $b$, irrational numbers, the sum is also an irrational number. -/ theorem not_sum_irrational : Β¬ ( βˆ€ (a b : ℝ), irrational a β†’ irrational b β†’ irrational (a+b) ) := begin intro H, have H2 := H (sqrt 2) (-sqrt 2), have H3 := H2 irrational_sqrt_two (irrational_neg_iff.2 irrational_sqrt_two), apply H3, existsi (0 : β„š), simp, done end end xena -- hide
1dffe342c0716f893418e6024e8cf17a36ef37b9
2caa8cd2737f8e6ea2ec83101247ef95d28a4406
/src/chapter0.lean
994ef82cd85a0039a18b9f6e541a338fb1583d15
[]
no_license
ruler501/DescriptiveSetTheory
1a079368bf2b06fbcba6864f31f4d3ff2a89195c
08a91bcd1533a88a28c2fac45d26ff223de2e9e6
refs/heads/master
1,676,123,700,591
1,610,658,976,000
1,610,658,976,000
327,178,014
0
0
null
null
null
null
UTF-8
Lean
false
false
1,184
lean
import measure_theory.borel_space import set_theory.cardinal_ordinal import set_theory.ordinal import topology.basic import topology.G_delta noncomputable theory open set classical topological_space open_locale classical section universes u w variables {Ξ± : Type u} {ΞΉ : Sort w} [t : topological_space Ξ±] include t def is_sigma_0_ΞΎ : Ξ  (ΞΎ : ordinal), (1 ≀ ΞΎ ∧ ΞΎ < (cardinal.aleph 1).ord) β†’ set Ξ± β†’ Prop | ΞΎ := Ξ» h s, if heo: ΞΎ = 1 then is_open s else βˆƒ (T : set (set Ξ±)), (βˆ€ (t : set Ξ±), t ∈ T β†’ βˆƒ (ΞΎβ‚™ : ordinal) (hβ‚™ : 1 ≀ ΞΎβ‚™ ∧ ΞΎβ‚™ < ΞΎ), have hdec : ΞΎβ‚™ < ΞΎ := hβ‚™.2, have hrec : 1 ≀ ΞΎβ‚™ ∧ (ΞΎβ‚™ < (cardinal.aleph 1).ord), { split, exact hβ‚™.1, exact (lt_trans hβ‚™.2 h.2) }, is_sigma_0_ΞΎ ΞΎβ‚™ hrec tᢜ ) ∧ T.countable ∧ (s = ⋃₀ T) using_well_founded { dec_tac := `[assumption] } def is_pi_0_ΞΎ (ΞΎ : ordinal) (h : 1 ≀ ΞΎ ∧ ΞΎ < (cardinal.aleph 1).ord) (s : set Ξ±) : Prop := is_sigma_0_ΞΎ ΞΎ h s def is_delta_0_ΞΎ (ΞΎ : ordinal) (h : 1 ≀ ΞΎ ∧ ΞΎ < (cardinal.aleph 1).ord) (s : set Ξ±) : Prop := is_sigma_0_ΞΎ ΞΎ h s ∧ is_pi_0_ΞΎ ΞΎ h s end
0c1d183241d299b27fab34d4ce087aebc80d4191
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/order/rel_iso.lean
7ad702c2a085434843ca52712c1e676f7ce7f295
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,842
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.group.defs import data.equiv.set import logic.embedding import order.rel_classes /-! # Relation homomorphisms, embeddings, isomorphisms This file defines relation homomorphisms, embeddings, isomorphisms and order embeddings and isomorphisms. ## Main declarations * `rel_hom`: Relation homomorphism. A `rel_hom r s` is a function `f : Ξ± β†’ Ξ²` such that `r a b β†’ s (f a) (f b)`. * `rel_embedding`: Relation embedding. A `rel_embedding r s` is an embedding `f : Ξ± β†ͺ Ξ²` such that `r a b ↔ s (f a) (f b)`. * `rel_iso`: Relation isomorphism. A `rel_iso r s` is an equivalence `f : Ξ± ≃ Ξ²` such that `r a b ↔ s (f a) (f b)`. * `order_embedding`: Relation embedding. An `order_embedding Ξ± Ξ²` is an embedding `f : Ξ± β†ͺ Ξ²` such that `a ≀ b ↔ f a ≀ f b`. Defined as an abbreviation of `@rel_embedding Ξ± Ξ² (≀) (≀)`. * `order_iso`: Relation isomorphism. An `order_iso Ξ± Ξ²` is an equivalence `f : Ξ± ≃ Ξ²` such that `a ≀ b ↔ f a ≀ f b`. Defined as an abbreviation of `@rel_iso Ξ± Ξ² (≀) (≀)`. * `sum_lex_congr`, `prod_lex_congr`: Creates a relation homomorphism between two `sum_lex` or two `prod_lex` from relation homomorphisms between their arguments. ## Notation * `β†’r`: `rel_hom` * `β†ͺr`: `rel_embedding` * `≃r`: `rel_iso` * `β†ͺo`: `order_embedding` * `≃o`: `order_iso` -/ open function universes u v w variables {Ξ± Ξ² Ξ³ : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} /-- A relation homomorphism with respect to a given pair of relations `r` and `s` is a function `f : Ξ± β†’ Ξ²` such that `r a b β†’ s (f a) (f b)`. -/ @[nolint has_inhabited_instance] structure rel_hom {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) := (to_fun : Ξ± β†’ Ξ²) (map_rel' : βˆ€ {a b}, r a b β†’ s (to_fun a) (to_fun b)) infix ` β†’r `:25 := rel_hom namespace rel_hom instance : has_coe_to_fun (r β†’r s) (Ξ» _, Ξ± β†’ Ξ²) := ⟨λ o, o.to_fun⟩ initialize_simps_projections rel_hom (to_fun β†’ apply) theorem map_rel (f : r β†’r s) : βˆ€ {a b}, r a b β†’ s (f a) (f b) := f.map_rel' @[simp] theorem coe_fn_mk (f : Ξ± β†’ Ξ²) (o) : (@rel_hom.mk _ _ r s f o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_fun (f : r β†’r s) : (f.to_fun : Ξ± β†’ Ξ²) = f := rfl /-- The map `coe_fn : (r β†’r s) β†’ (Ξ± β†’ Ξ²)` is injective. -/ theorem coe_fn_injective : @function.injective (r β†’r s) (Ξ± β†’ Ξ²) coe_fn | ⟨f₁, oβ‚βŸ© ⟨fβ‚‚, oβ‚‚βŸ© h := by { congr, exact h } @[ext] theorem ext ⦃f g : r β†’r s⦄ (h : βˆ€ x, f x = g x) : f = g := coe_fn_injective (funext h) theorem ext_iff {f g : r β†’r s} : f = g ↔ βˆ€ x, f x = g x := ⟨λ h x, h β–Έ rfl, Ξ» h, ext h⟩ /-- Identity map is a relation homomorphism. -/ @[refl, simps] protected def id (r : Ξ± β†’ Ξ± β†’ Prop) : r β†’r r := ⟨λ x, x, Ξ» a b x, x⟩ /-- Composition of two relation homomorphisms is a relation homomorphism. -/ @[trans, simps] protected def comp (g : s β†’r t) (f : r β†’r s) : r β†’r t := ⟨λ x, g (f x), Ξ» a b h, g.2 (f.2 h)⟩ /-- A relation homomorphism is also a relation homomorphism between dual relations. -/ protected def swap (f : r β†’r s) : swap r β†’r swap s := ⟨f, Ξ» a b, f.map_rel⟩ /-- A function is a relation homomorphism from the preimage relation of `s` to `s`. -/ def preimage (f : Ξ± β†’ Ξ²) (s : Ξ² β†’ Ξ² β†’ Prop) : f ⁻¹'o s β†’r s := ⟨f, Ξ» a b, id⟩ protected theorem is_irrefl : βˆ€ (f : r β†’r s) [is_irrefl Ξ² s], is_irrefl Ξ± r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o h)⟩ protected theorem is_asymm : βˆ€ (f : r β†’r s) [is_asymm Ξ² s], is_asymm Ξ± r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ hβ‚‚, H _ _ (o h₁) (o hβ‚‚)⟩ protected theorem acc (f : r β†’r s) (a : Ξ±) : acc s (f a) β†’ acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, Ξ» a' h, IH (f a') (f.map_rel h) _ rfl⟩ end protected theorem well_founded : βˆ€ (f : r β†’r s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ lemma map_inf {Ξ± Ξ² : Type*} [semilattice_inf Ξ±] [linear_order Ξ²] (a : ((<) : Ξ² β†’ Ξ² β†’ Prop) β†’r ((<) : Ξ± β†’ Ξ± β†’ Prop)) (m n : Ξ²) : a (m βŠ“ n) = a m βŠ“ a n := begin symmetry, cases le_or_lt n m with h, { rw [inf_eq_right.mpr h, inf_eq_right], exact strict_mono.monotone (Ξ» x y, a.map_rel) h, }, { rw [inf_eq_left.mpr (le_of_lt h), inf_eq_left], exact le_of_lt (a.map_rel h), }, end lemma map_sup {Ξ± Ξ² : Type*} [semilattice_sup Ξ±] [linear_order Ξ²] (a : ((>) : Ξ² β†’ Ξ² β†’ Prop) β†’r ((>) : Ξ± β†’ Ξ± β†’ Prop)) (m n : Ξ²) : a (m βŠ” n) = a m βŠ” a n := begin symmetry, cases le_or_lt m n with h, { rw [sup_eq_right.mpr h, sup_eq_right], exact strict_mono.monotone (Ξ» x y, a.swap.map_rel) h, }, { rw [sup_eq_left.mpr (le_of_lt h), sup_eq_left], exact le_of_lt (a.map_rel h), }, end end rel_hom /-- An increasing function is injective -/ lemma injective_of_increasing (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) [is_trichotomous Ξ± r] [is_irrefl Ξ² s] (f : Ξ± β†’ Ξ²) (hf : βˆ€ {x y}, r x y β†’ s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An increasing function is injective -/ lemma rel_hom.injective_of_increasing [is_trichotomous Ξ± r] [is_irrefl Ξ² s] (f : r β†’r s) : injective f := injective_of_increasing r s f (Ξ» x y, f.map_rel) theorem surjective.well_founded_iff {f : Ξ± β†’ Ξ²} (hf : surjective f) (o : βˆ€ {a b}, r a b ↔ s (f a) (f b)) : well_founded r ↔ well_founded s := iff.intro (begin apply rel_hom.well_founded, refine rel_hom.mk _ _, {exact classical.some hf.has_right_inverse}, intros a b h, apply o.2, convert h, iterate 2 { apply classical.some_spec hf.has_right_inverse }, end) (rel_hom.well_founded ⟨f, Ξ» _ _, o.1⟩) /-- A relation embedding with respect to a given pair of relations `r` and `s` is an embedding `f : Ξ± β†ͺ Ξ²` such that `r a b ↔ s (f a) (f b)`. -/ structure rel_embedding {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) extends Ξ± β†ͺ Ξ² := (map_rel_iff' : βˆ€ {a b}, s (to_embedding a) (to_embedding b) ↔ r a b) infix ` β†ͺr `:25 := rel_embedding /-- An order embedding is an embedding `f : Ξ± β†ͺ Ξ²` such that `a ≀ b ↔ (f a) ≀ (f b)`. This definition is an abbreviation of `rel_embedding (≀) (≀)`. -/ abbreviation order_embedding (Ξ± Ξ² : Type*) [has_le Ξ±] [has_le Ξ²] := @rel_embedding Ξ± Ξ² (≀) (≀) infix ` β†ͺo `:25 := order_embedding /-- The induced relation on a subtype is an embedding under the natural inclusion. -/ definition subtype.rel_embedding {X : Type*} (r : X β†’ X β†’ Prop) (p : X β†’ Prop) : ((subtype.val : subtype p β†’ X) ⁻¹'o r) β†ͺr r := ⟨embedding.subtype p, Ξ» x y, iff.rfl⟩ theorem preimage_equivalence {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) {s : Ξ² β†’ Ξ² β†’ Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, Ξ» a b h, hs.2.1 h, Ξ» a b c h₁ hβ‚‚, hs.2.2 h₁ hβ‚‚βŸ© namespace rel_embedding /-- A relation embedding is also a relation homomorphism -/ def to_rel_hom (f : r β†ͺr s) : (r β†’r s) := { to_fun := f.to_embedding.to_fun, map_rel' := Ξ» x y, (map_rel_iff' f).mpr } instance : has_coe (r β†ͺr s) (r β†’r s) := ⟨to_rel_hom⟩ -- see Note [function coercion] instance : has_coe_to_fun (r β†ͺr s) (Ξ» _, Ξ± β†’ Ξ²) := ⟨λ o, o.to_embedding⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : r β†ͺr s) : Ξ± β†’ Ξ² := h initialize_simps_projections rel_embedding (to_embedding_to_fun β†’ apply, -to_embedding) @[simp] lemma to_rel_hom_eq_coe (f : r β†ͺr s) : f.to_rel_hom = f := rfl @[simp] lemma coe_coe_fn (f : r β†ͺr s) : ((f : r β†’r s) : Ξ± β†’ Ξ²) = f := rfl theorem injective (f : r β†ͺr s) : injective f := f.inj' theorem map_rel_iff (f : r β†ͺr s) : βˆ€ {a b}, s (f a) (f b) ↔ r a b := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : Ξ± β†ͺ Ξ²) (o) : (@rel_embedding.mk _ _ r s f o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r β†ͺr s) : (f.to_embedding : Ξ± β†’ Ξ²) = f := rfl /-- The map `coe_fn : (r β†ͺr s) β†’ (Ξ± β†’ Ξ²)` is injective. -/ theorem coe_fn_injective : @function.injective (r β†ͺr s) (Ξ± β†’ Ξ²) coe_fn | ⟨⟨f₁, hβ‚βŸ©, oβ‚βŸ© ⟨⟨fβ‚‚, hβ‚‚βŸ©, oβ‚‚βŸ© h := by { congr, exact h } @[ext] theorem ext ⦃f g : r β†ͺr s⦄ (h : βˆ€ x, f x = g x) : f = g := coe_fn_injective (funext h) theorem ext_iff {f g : r β†ͺr s} : f = g ↔ βˆ€ x, f x = g x := ⟨λ h x, h β–Έ rfl, Ξ» h, ext h⟩ /-- Identity map is a relation embedding. -/ @[refl, simps] protected def refl (r : Ξ± β†’ Ξ± β†’ Prop) : r β†ͺr r := ⟨embedding.refl _, Ξ» a b, iff.rfl⟩ /-- Composition of two relation embeddings is a relation embedding. -/ @[trans] protected def trans (f : r β†ͺr s) (g : s β†ͺr t) : r β†ͺr t := ⟨f.1.trans g.1, Ξ» a b, by simp [f.map_rel_iff, g.map_rel_iff]⟩ instance (r : Ξ± β†’ Ξ± β†’ Prop) : inhabited (r β†ͺr r) := ⟨rel_embedding.refl _⟩ theorem trans_apply (f : r β†ͺr s) (g : s β†ͺr t) (a : Ξ±) : (f.trans g) a = g (f a) := rfl @[simp] theorem coe_trans (f : r β†ͺr s) (g : s β†ͺr t) : ⇑(f.trans g) = g ∘ f := rfl /-- A relation embedding is also a relation embedding between dual relations. -/ protected def swap (f : r β†ͺr s) : swap r β†ͺr swap s := ⟨f.to_embedding, Ξ» a b, f.map_rel_iff⟩ /-- If `f` is injective, then it is a relation embedding from the preimage relation of `s` to `s`. -/ def preimage (f : Ξ± β†ͺ Ξ²) (s : Ξ² β†’ Ξ² β†’ Prop) : f ⁻¹'o s β†ͺr s := ⟨f, Ξ» a b, iff.rfl⟩ theorem eq_preimage (f : r β†ͺr s) : r = f ⁻¹'o s := by { ext a b, exact f.map_rel_iff.symm } protected theorem is_irrefl (f : r β†ͺr s) [is_irrefl Ξ² s] : is_irrefl Ξ± r := ⟨λ a, mt f.map_rel_iff.2 (irrefl (f a))⟩ protected theorem is_refl (f : r β†ͺr s) [is_refl Ξ² s] : is_refl Ξ± r := ⟨λ a, f.map_rel_iff.1 $ refl _⟩ protected theorem is_symm (f : r β†ͺr s) [is_symm Ξ² s] : is_symm Ξ± r := ⟨λ a b, imp_imp_imp f.map_rel_iff.2 f.map_rel_iff.1 symm⟩ protected theorem is_asymm (f : r β†ͺr s) [is_asymm Ξ² s] : is_asymm Ξ± r := ⟨λ a b h₁ hβ‚‚, asymm (f.map_rel_iff.2 h₁) (f.map_rel_iff.2 hβ‚‚)⟩ protected theorem is_antisymm : βˆ€ (f : r β†ͺr s) [is_antisymm Ξ² s], is_antisymm Ξ± r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ hβ‚‚, f.inj' (H _ _ (o.2 h₁) (o.2 hβ‚‚))⟩ protected theorem is_trans : βˆ€ (f : r β†ͺr s) [is_trans Ξ² s], is_trans Ξ± r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ hβ‚‚, o.1 (H _ _ _ (o.2 h₁) (o.2 hβ‚‚))⟩ protected theorem is_total : βˆ€ (f : r β†ͺr s) [is_total Ξ² s], is_total Ξ± r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).1 (H _ _)⟩ protected theorem is_preorder : βˆ€ (f : r β†ͺr s) [is_preorder Ξ² s], is_preorder Ξ± r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : βˆ€ (f : r β†ͺr s) [is_partial_order Ξ² s], is_partial_order Ξ± r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : βˆ€ (f : r β†ͺr s) [is_linear_order Ξ² s], is_linear_order Ξ± r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : βˆ€ (f : r β†ͺr s) [is_strict_order Ξ² s], is_strict_order Ξ± r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : βˆ€ (f : r β†ͺr s) [is_trichotomous Ξ² s], is_trichotomous Ξ± r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff o)).1 (H _ _)⟩ protected theorem is_strict_total_order' : βˆ€ (f : r β†ͺr s) [is_strict_total_order' Ξ² s], is_strict_total_order' Ξ± r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r β†ͺr s) (a : Ξ±) : acc s (f a) β†’ acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, Ξ» a' h, IH (f a') (f.map_rel_iff.2 h) _ rfl⟩ end protected theorem well_founded : βˆ€ (f : r β†ͺr s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : βˆ€ (f : r β†ͺr s) [is_well_order Ξ² s], is_well_order Ξ± r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- To define an relation embedding from an antisymmetric relation `r` to a reflexive relation `s` it suffices to give a function together with a proof that it satisfies `s (f a) (f b) ↔ r a b`. -/ def of_map_rel_iff (f : Ξ± β†’ Ξ²) [is_antisymm Ξ± r] [is_refl Ξ² s] (hf : βˆ€ a b, s (f a) (f b) ↔ r a b) : r β†ͺr s := { to_fun := f, inj' := Ξ» x y h, antisymm ((hf _ _).1 (h β–Έ refl _)) ((hf _ _).1 (h β–Έ refl _)), map_rel_iff' := hf } @[simp] lemma of_map_rel_iff_coe (f : Ξ± β†’ Ξ²) [is_antisymm Ξ± r] [is_refl Ξ² s] (hf : βˆ€ a b, s (f a) (f b) ↔ r a b) : ⇑(of_map_rel_iff f hf : r β†ͺr s) = f := rfl /-- It suffices to prove `f` is monotone between strict relations to show it is a relation embedding. -/ def of_monotone [is_trichotomous Ξ± r] [is_asymm Ξ² s] (f : Ξ± β†’ Ξ²) (H : βˆ€ a b, r a b β†’ s (f a) (f b)) : r β†ͺr s := begin haveI := @is_asymm.is_irrefl Ξ² s _, refine ⟨⟨f, Ξ» a b e, _⟩, Ξ» a b, ⟨λ h, _, H _ _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact Ξ» h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (Ξ» e, _) (Ξ» h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous Ξ± r] [is_asymm Ξ² s] (f : Ξ± β†’ Ξ²) (H) : (@of_monotone _ _ r s _ _ f H : Ξ± β†’ Ξ²) = f := rfl /-- Embeddings of partial orders that preserve `<` also preserve `≀`. -/ def order_embedding_of_lt_embedding [partial_order Ξ±] [partial_order Ξ²] (f : ((<) : Ξ± β†’ Ξ± β†’ Prop) β†ͺr ((<) : Ξ² β†’ Ξ² β†’ Prop)) : Ξ± β†ͺo Ξ² := { map_rel_iff' := by { intros, simp [le_iff_lt_or_eq,f.map_rel_iff, f.injective.eq_iff] }, .. f } @[simp] lemma order_embedding_of_lt_embedding_apply [partial_order Ξ±] [partial_order Ξ²] {f : ((<) : Ξ± β†’ Ξ± β†’ Prop) β†ͺr ((<) : Ξ² β†’ Ξ² β†’ Prop)} {x : Ξ±} : order_embedding_of_lt_embedding f x = f x := rfl end rel_embedding namespace order_embedding variables [preorder Ξ±] [preorder Ξ²] (f : Ξ± β†ͺo Ξ²) /-- `<` is preserved by order embeddings of preorders. -/ def lt_embedding : ((<) : Ξ± β†’ Ξ± β†’ Prop) β†ͺr ((<) : Ξ² β†’ Ξ² β†’ Prop) := { map_rel_iff' := by intros; simp [lt_iff_le_not_le, f.map_rel_iff], .. f } @[simp] lemma lt_embedding_apply (x : Ξ±) : f.lt_embedding x = f x := rfl @[simp] theorem le_iff_le {a b} : (f a) ≀ (f b) ↔ a ≀ b := f.map_rel_iff @[simp] theorem lt_iff_lt {a b} : f a < f b ↔ a < b := f.lt_embedding.map_rel_iff @[simp] lemma eq_iff_eq {a b} : f a = f b ↔ a = b := f.injective.eq_iff protected theorem monotone : monotone f := Ξ» x y, f.le_iff_le.2 protected theorem strict_mono : strict_mono f := Ξ» x y, f.lt_iff_lt.2 protected theorem acc (a : Ξ±) : acc (<) (f a) β†’ acc (<) a := f.lt_embedding.acc a protected theorem well_founded : well_founded ((<) : Ξ² β†’ Ξ² β†’ Prop) β†’ well_founded ((<) : Ξ± β†’ Ξ± β†’ Prop) := f.lt_embedding.well_founded protected theorem is_well_order [is_well_order Ξ² (<)] : is_well_order Ξ± (<) := f.lt_embedding.is_well_order /-- An order embedding is also an order embedding between dual orders. -/ protected def dual : order_dual Ξ± β†ͺo order_dual Ξ² := ⟨f.to_embedding, Ξ» a b, f.map_rel_iff⟩ /-- To define an order embedding from a partial order to a preorder it suffices to give a function together with a proof that it satisfies `f a ≀ f b ↔ a ≀ b`. -/ def of_map_le_iff {Ξ± Ξ²} [partial_order Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) (hf : βˆ€ a b, f a ≀ f b ↔ a ≀ b) : Ξ± β†ͺo Ξ² := rel_embedding.of_map_rel_iff f hf @[simp] lemma coe_of_map_le_iff {Ξ± Ξ²} [partial_order Ξ±] [preorder Ξ²] {f : Ξ± β†’ Ξ²} (h) : ⇑(of_map_le_iff f h) = f := rfl /-- A strictly monotone map from a linear order is an order embedding. --/ def of_strict_mono {Ξ± Ξ²} [linear_order Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) (h : strict_mono f) : Ξ± β†ͺo Ξ² := of_map_le_iff f (Ξ» _ _, h.le_iff_le) @[simp] lemma coe_of_strict_mono {Ξ± Ξ²} [linear_order Ξ±] [preorder Ξ²] {f : Ξ± β†’ Ξ²} (h : strict_mono f) : ⇑(of_strict_mono f h) = f := rfl /-- Embedding of a subtype into the ambient type as an `order_embedding`. -/ @[simps {fully_applied := ff}] def subtype (p : Ξ± β†’ Prop) : subtype p β†ͺo Ξ± := ⟨embedding.subtype p, Ξ» x y, iff.rfl⟩ end order_embedding /-- A relation isomorphism is an equivalence that is also a relation embedding. -/ structure rel_iso {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) extends Ξ± ≃ Ξ² := (map_rel_iff' : βˆ€ {a b}, s (to_equiv a) (to_equiv b) ↔ r a b) infix ` ≃r `:25 := rel_iso /-- An order isomorphism is an equivalence such that `a ≀ b ↔ (f a) ≀ (f b)`. This definition is an abbreviation of `rel_iso (≀) (≀)`. -/ abbreviation order_iso (Ξ± Ξ² : Type*) [has_le Ξ±] [has_le Ξ²] := @rel_iso Ξ± Ξ² (≀) (≀) infix ` ≃o `:25 := order_iso namespace rel_iso /-- Convert an `rel_iso` to an `rel_embedding`. This function is also available as a coercion but often it is easier to write `f.to_rel_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_rel_embedding (f : r ≃r s) : r β†ͺr s := ⟨f.to_equiv.to_embedding, f.map_rel_iff'⟩ instance : has_coe (r ≃r s) (r β†ͺr s) := ⟨to_rel_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃r s) (Ξ» _, Ξ± β†’ Ξ²) := ⟨λ f, f⟩ @[simp] lemma to_rel_embedding_eq_coe (f : r ≃r s) : f.to_rel_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃r s) : ((f : r β†ͺr s) : Ξ± β†’ Ξ²) = f := rfl theorem map_rel_iff (f : r ≃r s) : βˆ€ {a b}, s (f a) (f b) ↔ r a b := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : Ξ± ≃ Ξ²) (o : βˆ€ ⦃a b⦄, s (f a) (f b) ↔ r a b) : (rel_iso.mk f o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃r s) : (f.to_equiv : Ξ± β†’ Ξ²) = f := rfl theorem to_equiv_injective : injective (to_equiv : (r ≃r s) β†’ Ξ± ≃ Ξ²) | ⟨e₁, oβ‚βŸ© ⟨eβ‚‚, oβ‚‚βŸ© h := by { congr, exact h } /-- The map `coe_fn : (r ≃r s) β†’ (Ξ± β†’ Ξ²)` is injective. Lean fails to parse `function.injective (Ξ» e : r ≃r s, (e : Ξ± β†’ Ξ²))`, so we use a trick to say the same. -/ theorem coe_fn_injective : @function.injective (r ≃r s) (Ξ± β†’ Ξ²) coe_fn := equiv.coe_fn_injective.comp to_equiv_injective @[ext] theorem ext ⦃f g : r ≃r s⦄ (h : βˆ€ x, f x = g x) : f = g := coe_fn_injective (funext h) theorem ext_iff {f g : r ≃r s} : f = g ↔ βˆ€ x, f x = g x := ⟨λ h x, h β–Έ rfl, Ξ» h, ext h⟩ /-- Inverse map of a relation isomorphism is a relation isomorphism. -/ @[symm] protected def symm (f : r ≃r s) : s ≃r r := ⟨f.to_equiv.symm, Ξ» a b, by erw [← f.map_rel_iff, f.1.apply_symm_apply, f.1.apply_symm_apply]⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : r ≃r s) : Ξ± β†’ Ξ² := h /-- See Note [custom simps projection]. -/ def simps.symm_apply (h : r ≃r s) : Ξ² β†’ Ξ± := h.symm initialize_simps_projections rel_iso (to_equiv_to_fun β†’ apply, to_equiv_inv_fun β†’ symm_apply, -to_equiv) /-- Identity map is a relation isomorphism. -/ @[refl, simps apply] protected def refl (r : Ξ± β†’ Ξ± β†’ Prop) : r ≃r r := ⟨equiv.refl _, Ξ» a b, iff.rfl⟩ /-- Composition of two relation isomorphisms is a relation isomorphism. -/ @[trans, simps apply] protected def trans (f₁ : r ≃r s) (fβ‚‚ : s ≃r t) : r ≃r t := ⟨f₁.to_equiv.trans fβ‚‚.to_equiv, Ξ» a b, fβ‚‚.map_rel_iff.trans f₁.map_rel_iff⟩ instance (r : Ξ± β†’ Ξ± β†’ Prop) : inhabited (r ≃r r) := ⟨rel_iso.refl _⟩ @[simp] lemma default_def (r : Ξ± β†’ Ξ± β†’ Prop) : default (r ≃r r) = rel_iso.refl r := rfl /-- a relation isomorphism is also a relation isomorphism between dual relations. -/ protected def swap (f : r ≃r s) : (swap r) ≃r (swap s) := ⟨f.to_equiv, Ξ» _ _, f.map_rel_iff⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@rel_iso.mk _ _ r s f o).symm : Ξ² β†’ Ξ±) = f.symm := rfl @[simp] theorem apply_symm_apply (e : r ≃r s) (x : Ξ²) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] theorem symm_apply_apply (e : r ≃r s) (x : Ξ±) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem rel_symm_apply (e : r ≃r s) {x y} : r x (e.symm y) ↔ s (e x) y := by rw [← e.map_rel_iff, e.apply_symm_apply] theorem symm_apply_rel (e : r ≃r s) {x y} : r (e.symm x) y ↔ s x (e y) := by rw [← e.map_rel_iff, e.apply_symm_apply] protected lemma bijective (e : r ≃r s) : bijective e := e.to_equiv.bijective protected lemma injective (e : r ≃r s) : injective e := e.to_equiv.injective protected lemma surjective (e : r ≃r s) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : r ≃r s) : set.range e = set.univ := e.surjective.range_eq @[simp] lemma eq_iff_eq (f : r ≃r s) {a b} : f a = f b ↔ a = b := f.injective.eq_iff /-- Any equivalence lifts to a relation isomorphism between `s` and its preimage. -/ protected def preimage (f : Ξ± ≃ Ξ²) (s : Ξ² β†’ Ξ² β†’ Prop) : f ⁻¹'o s ≃r s := ⟨f, Ξ» a b, iff.rfl⟩ /-- A surjective relation embedding is a relation isomorphism. -/ @[simps apply] noncomputable def of_surjective (f : r β†ͺr s) (H : surjective f) : r ≃r s := ⟨equiv.of_bijective f ⟨f.injective, H⟩, Ξ» a b, f.map_rel_iff⟩ /-- Given relation isomorphisms `r₁ ≃r s₁` and `rβ‚‚ ≃r sβ‚‚`, construct a relation isomorphism for the lexicographic orders on the sum. -/ def sum_lex_congr {α₁ Ξ±β‚‚ β₁ Ξ²β‚‚ r₁ rβ‚‚ s₁ sβ‚‚} (e₁ : @rel_iso α₁ β₁ r₁ s₁) (eβ‚‚ : @rel_iso Ξ±β‚‚ Ξ²β‚‚ rβ‚‚ sβ‚‚) : sum.lex r₁ rβ‚‚ ≃r sum.lex s₁ sβ‚‚ := ⟨equiv.sum_congr e₁.to_equiv eβ‚‚.to_equiv, Ξ» a b, by cases e₁ with f hf; cases eβ‚‚ with g hg; cases a; cases b; simp [hf, hg]⟩ /-- Given relation isomorphisms `r₁ ≃r s₁` and `rβ‚‚ ≃r sβ‚‚`, construct a relation isomorphism for the lexicographic orders on the product. -/ def prod_lex_congr {α₁ Ξ±β‚‚ β₁ Ξ²β‚‚ r₁ rβ‚‚ s₁ sβ‚‚} (e₁ : @rel_iso α₁ β₁ r₁ s₁) (eβ‚‚ : @rel_iso Ξ±β‚‚ Ξ²β‚‚ rβ‚‚ sβ‚‚) : prod.lex r₁ rβ‚‚ ≃r prod.lex s₁ sβ‚‚ := ⟨equiv.prod_congr e₁.to_equiv eβ‚‚.to_equiv, Ξ» a b, by simp [prod.lex_def, e₁.map_rel_iff, eβ‚‚.map_rel_iff]⟩ instance : group (r ≃r r) := { one := rel_iso.refl r, mul := Ξ» f₁ fβ‚‚, fβ‚‚.trans f₁, inv := rel_iso.symm, mul_assoc := Ξ» f₁ fβ‚‚ f₃, rfl, one_mul := Ξ» f, ext $ Ξ» _, rfl, mul_one := Ξ» f, ext $ Ξ» _, rfl, mul_left_inv := Ξ» f, ext f.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : r ≃r r) = id := rfl @[simp] lemma coe_mul (e₁ eβ‚‚ : r ≃r r) : ⇑(e₁ * eβ‚‚) = e₁ ∘ eβ‚‚ := rfl lemma mul_apply (e₁ eβ‚‚ : r ≃r r) (x : Ξ±) : (e₁ * eβ‚‚) x = e₁ (eβ‚‚ x) := rfl @[simp] lemma inv_apply_self (e : r ≃r r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : r ≃r r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x end rel_iso namespace order_iso section has_le variables [has_le Ξ±] [has_le Ξ²] [has_le Ξ³] /-- Reinterpret an order isomorphism as an order embedding. -/ def to_order_embedding (e : Ξ± ≃o Ξ²) : Ξ± β†ͺo Ξ² := e.to_rel_embedding @[simp] lemma coe_to_order_embedding (e : Ξ± ≃o Ξ²) : ⇑(e.to_order_embedding) = e := rfl protected lemma bijective (e : Ξ± ≃o Ξ²) : bijective e := e.to_equiv.bijective protected lemma injective (e : Ξ± ≃o Ξ²) : injective e := e.to_equiv.injective protected lemma surjective (e : Ξ± ≃o Ξ²) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : Ξ± ≃o Ξ²) : set.range e = set.univ := e.surjective.range_eq @[simp] lemma apply_eq_iff_eq (e : Ξ± ≃o Ξ²) {x y : Ξ±} : e x = e y ↔ x = y := e.to_equiv.apply_eq_iff_eq /-- Identity order isomorphism. -/ def refl (Ξ± : Type*) [has_le Ξ±] : Ξ± ≃o Ξ± := rel_iso.refl (≀) @[simp] lemma coe_refl : ⇑(refl Ξ±) = id := rfl lemma refl_apply (x : Ξ±) : refl Ξ± x = x := rfl @[simp] lemma refl_to_equiv : (refl Ξ±).to_equiv = equiv.refl Ξ± := rfl /-- Inverse of an order isomorphism. -/ def symm (e : Ξ± ≃o Ξ²) : Ξ² ≃o Ξ± := e.symm @[simp] lemma apply_symm_apply (e : Ξ± ≃o Ξ²) (x : Ξ²) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (e : Ξ± ≃o Ξ²) (x : Ξ±) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x @[simp] lemma symm_refl (Ξ± : Type*) [has_le Ξ±] : (refl Ξ±).symm = refl Ξ± := rfl lemma apply_eq_iff_eq_symm_apply (e : Ξ± ≃o Ξ²) (x : Ξ±) (y : Ξ²) : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply theorem symm_apply_eq (e : Ξ± ≃o Ξ²) {x : Ξ±} {y : Ξ²} : e.symm y = x ↔ y = e x := e.to_equiv.symm_apply_eq @[simp] lemma symm_symm (e : Ξ± ≃o Ξ²) : e.symm.symm = e := by { ext, refl } lemma symm_injective : injective (symm : (Ξ± ≃o Ξ²) β†’ (Ξ² ≃o Ξ±)) := Ξ» e e' h, by rw [← e.symm_symm, h, e'.symm_symm] @[simp] lemma to_equiv_symm (e : Ξ± ≃o Ξ²) : e.to_equiv.symm = e.symm.to_equiv := rfl @[simp] lemma symm_image_image (e : Ξ± ≃o Ξ²) (s : set Ξ±) : e.symm '' (e '' s) = s := e.to_equiv.symm_image_image s @[simp] lemma image_symm_image (e : Ξ± ≃o Ξ²) (s : set Ξ²) : e '' (e.symm '' s) = s := e.to_equiv.image_symm_image s lemma image_eq_preimage (e : Ξ± ≃o Ξ²) (s : set Ξ±) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s @[simp] lemma preimage_symm_preimage (e : Ξ± ≃o Ξ²) (s : set Ξ±) : e ⁻¹' (e.symm ⁻¹' s) = s := e.to_equiv.preimage_symm_preimage s @[simp] lemma symm_preimage_preimage (e : Ξ± ≃o Ξ²) (s : set Ξ²) : e.symm ⁻¹' (e ⁻¹' s) = s := e.to_equiv.symm_preimage_preimage s @[simp] lemma image_preimage (e : Ξ± ≃o Ξ²) (s : set Ξ²) : e '' (e ⁻¹' s) = s := e.to_equiv.image_preimage s @[simp] lemma preimage_image (e : Ξ± ≃o Ξ²) (s : set Ξ±) : e ⁻¹' (e '' s) = s := e.to_equiv.preimage_image s /-- Composition of two order isomorphisms is an order isomorphism. -/ @[trans] def trans (e : Ξ± ≃o Ξ²) (e' : Ξ² ≃o Ξ³) : Ξ± ≃o Ξ³ := e.trans e' @[simp] lemma coe_trans (e : Ξ± ≃o Ξ²) (e' : Ξ² ≃o Ξ³) : ⇑(e.trans e') = e' ∘ e := rfl lemma trans_apply (e : Ξ± ≃o Ξ²) (e' : Ξ² ≃o Ξ³) (x : Ξ±) : e.trans e' x = e' (e x) := rfl @[simp] lemma refl_trans (e : Ξ± ≃o Ξ²) : (refl Ξ±).trans e = e := by { ext x, refl } @[simp] lemma trans_refl (e : Ξ± ≃o Ξ²) : e.trans (refl Ξ²) = e := by { ext x, refl } end has_le open set section le variables [has_le Ξ±] [has_le Ξ²] [has_le Ξ³] @[simp] lemma le_iff_le (e : Ξ± ≃o Ξ²) {x y : Ξ±} : e x ≀ e y ↔ x ≀ y := e.map_rel_iff lemma le_symm_apply (e : Ξ± ≃o Ξ²) {x : Ξ±} {y : Ξ²} : x ≀ e.symm y ↔ e x ≀ y := e.rel_symm_apply lemma symm_apply_le (e : Ξ± ≃o Ξ²) {x : Ξ±} {y : Ξ²} : e.symm y ≀ x ↔ y ≀ e x := e.symm_apply_rel end le variables [preorder Ξ±] [preorder Ξ²] [preorder Ξ³] protected lemma monotone (e : Ξ± ≃o Ξ²) : monotone e := e.to_order_embedding.monotone protected lemma strict_mono (e : Ξ± ≃o Ξ²) : strict_mono e := e.to_order_embedding.strict_mono @[simp] lemma lt_iff_lt (e : Ξ± ≃o Ξ²) {x y : Ξ±} : e x < e y ↔ x < y := e.to_order_embedding.lt_iff_lt /-- To show that `f : Ξ± β†’ Ξ²`, `g : Ξ² β†’ Ξ±` make up an order isomorphism of linear orders, it suffices to prove `cmp a (g b) = cmp (f a) b`. --/ def of_cmp_eq_cmp {Ξ± Ξ²} [linear_order Ξ±] [linear_order Ξ²] (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ±) (h : βˆ€ (a : Ξ±) (b : Ξ²), cmp a (g b) = cmp (f a) b) : Ξ± ≃o Ξ² := have gf : βˆ€ (a : Ξ±), a = g (f a) := by { intro, rw [←cmp_eq_eq_iff, h, cmp_self_eq_eq] }, { to_fun := f, inv_fun := g, left_inv := Ξ» a, (gf a).symm, right_inv := by { intro, rw [←cmp_eq_eq_iff, ←h, cmp_self_eq_eq] }, map_rel_iff' := by { intros, apply le_iff_le_of_cmp_eq_cmp, convert (h _ _).symm, apply gf } } /-- Order isomorphism between two equal sets. -/ def set_congr (s t : set Ξ±) (h : s = t) : s ≃o t := { to_equiv := equiv.set_congr h, map_rel_iff' := Ξ» x y, iff.rfl } /-- Order isomorphism between `univ : set Ξ±` and `Ξ±`. -/ def set.univ : (set.univ : set Ξ±) ≃o Ξ± := { to_equiv := equiv.set.univ Ξ±, map_rel_iff' := Ξ» x y, iff.rfl } /-- Order isomorphism between `Ξ± β†’ Ξ²` and `Ξ²`, where `Ξ±` has a unique element. -/ @[simps to_equiv apply] def fun_unique (Ξ± Ξ² : Type*) [unique Ξ±] [preorder Ξ²] : (Ξ± β†’ Ξ²) ≃o Ξ² := { to_equiv := equiv.fun_unique Ξ± Ξ², map_rel_iff' := Ξ» f g, by simp [pi.le_def, unique.forall_iff] } @[simp] lemma fun_unique_symm_apply {Ξ± Ξ² : Type*} [unique Ξ±] [preorder Ξ²] : ((fun_unique Ξ± Ξ²).symm : Ξ² β†’ Ξ± β†’ Ξ²) = function.const Ξ± := rfl end order_iso namespace equiv variables [preorder Ξ±] [preorder Ξ²] /-- If `e` is an equivalence with monotone forward and inverse maps, then `e` is an order isomorphism. -/ def to_order_iso (e : Ξ± ≃ Ξ²) (h₁ : monotone e) (hβ‚‚ : monotone e.symm) : Ξ± ≃o Ξ² := ⟨e, Ξ» x y, ⟨λ h, by simpa only [e.symm_apply_apply] using hβ‚‚ h, Ξ» h, h₁ h⟩⟩ @[simp] lemma coe_to_order_iso (e : Ξ± ≃ Ξ²) (h₁ : monotone e) (hβ‚‚ : monotone e.symm) : ⇑(e.to_order_iso h₁ hβ‚‚) = e := rfl @[simp] lemma to_order_iso_to_equiv (e : Ξ± ≃ Ξ²) (h₁ : monotone e) (hβ‚‚ : monotone e.symm) : (e.to_order_iso h₁ hβ‚‚).to_equiv = e := rfl end equiv /-- If a function `f` is strictly monotone on a set `s`, then it defines an order isomorphism between `s` and its image. -/ protected noncomputable def strict_mono_on.order_iso {Ξ± Ξ²} [linear_order Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) (s : set Ξ±) (hf : strict_mono_on f s) : s ≃o f '' s := { to_equiv := hf.inj_on.bij_on_image.equiv _, map_rel_iff' := Ξ» x y, hf.le_iff_le x.2 y.2 } /-- A strictly monotone function from a linear order is an order isomorphism between its domain and its range. -/ protected noncomputable def strict_mono.order_iso {Ξ± Ξ²} [linear_order Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) (h_mono : strict_mono f) : Ξ± ≃o set.range f := { to_equiv := equiv.of_injective f h_mono.injective, map_rel_iff' := Ξ» a b, h_mono.le_iff_le } /-- A strictly monotone surjective function from a linear order is an order isomorphism. -/ noncomputable def strict_mono.order_iso_of_surjective {Ξ± Ξ²} [linear_order Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) (h_mono : strict_mono f) (h_surj : surjective f) : Ξ± ≃o Ξ² := (h_mono.order_iso f).trans $ (order_iso.set_congr _ _ h_surj.range_eq).trans order_iso.set.univ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : Ξ± β†’ Ξ± β†’ Prop) (p : set Ξ±) : p β†’ p β†’ Prop := (coe : p β†’ Ξ±) ⁻¹'o r @[simp] theorem subrel_val (r : Ξ± β†’ Ξ± β†’ Prop) (p : set Ξ±) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel /-- The relation embedding from the inherited relation on a subset. -/ protected def rel_embedding (r : Ξ± β†’ Ξ± β†’ Prop) (p : set Ξ±) : subrel r p β†ͺr r := ⟨embedding.subtype _, Ξ» a b, iff.rfl⟩ @[simp] theorem rel_embedding_apply (r : Ξ± β†’ Ξ± β†’ Prop) (p a) : subrel.rel_embedding r p a = a.1 := rfl instance (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (p : set Ξ±) : is_well_order p (subrel r p) := rel_embedding.is_well_order (subrel.rel_embedding r p) end subrel /-- Restrict the codomain of a relation embedding. -/ def rel_embedding.cod_restrict (p : set Ξ²) (f : r β†ͺr s) (H : βˆ€ a, f a ∈ p) : r β†ͺr subrel s p := ⟨f.to_embedding.cod_restrict p H, f.map_rel_iff'⟩ @[simp] theorem rel_embedding.cod_restrict_apply (p) (f : r β†ͺr s) (H a) : rel_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- An order isomorphism is also an order isomorphism between dual orders. -/ protected def order_iso.dual [preorder Ξ±] [preorder Ξ²] (f : Ξ± ≃o Ξ²) : order_dual Ξ± ≃o order_dual Ξ² := ⟨f.to_equiv, Ξ» _ _, f.map_rel_iff⟩ section lattice_isos lemma order_iso.map_bot' [partial_order Ξ±] [partial_order Ξ²] (f : Ξ± ≃o Ξ²) {x : Ξ±} {y : Ξ²} (hx : βˆ€ x', x ≀ x') (hy : βˆ€ y', y ≀ y') : f x = y := by { refine le_antisymm _ (hy _), rw [← f.apply_symm_apply y, f.map_rel_iff], apply hx } lemma order_iso.map_bot [order_bot Ξ±] [order_bot Ξ²] (f : Ξ± ≃o Ξ²) : f βŠ₯ = βŠ₯ := f.map_bot' (Ξ» _, bot_le) (Ξ» _, bot_le) lemma order_iso.map_top' [partial_order Ξ±] [partial_order Ξ²] (f : Ξ± ≃o Ξ²) {x : Ξ±} {y : Ξ²} (hx : βˆ€ x', x' ≀ x) (hy : βˆ€ y', y' ≀ y) : f x = y := f.dual.map_bot' hx hy lemma order_iso.map_top [order_top Ξ±] [order_top Ξ²] (f : Ξ± ≃o Ξ²) : f ⊀ = ⊀ := f.dual.map_bot lemma order_embedding.map_inf_le [semilattice_inf Ξ±] [semilattice_inf Ξ²] (f : Ξ± β†ͺo Ξ²) (x y : Ξ±) : f (x βŠ“ y) ≀ f x βŠ“ f y := f.monotone.map_inf_le x y lemma order_iso.map_inf [semilattice_inf Ξ±] [semilattice_inf Ξ²] (f : Ξ± ≃o Ξ²) (x y : Ξ±) : f (x βŠ“ y) = f x βŠ“ f y := begin refine (f.to_order_embedding.map_inf_le x y).antisymm _, simpa [← f.symm.le_iff_le] using f.symm.to_order_embedding.map_inf_le (f x) (f y) end lemma order_embedding.le_map_sup [semilattice_sup Ξ±] [semilattice_sup Ξ²] (f : Ξ± β†ͺo Ξ²) (x y : Ξ±) : f x βŠ” f y ≀ f (x βŠ” y) := f.monotone.le_map_sup x y lemma order_iso.map_sup [semilattice_sup Ξ±] [semilattice_sup Ξ²] (f : Ξ± ≃o Ξ²) (x y : Ξ±) : f (x βŠ” y) = f x βŠ” f y := f.dual.map_inf x y section bounded_lattice variables [bounded_lattice Ξ±] [bounded_lattice Ξ²] (f : Ξ± ≃o Ξ²) include f lemma order_iso.is_compl {x y : Ξ±} (h : is_compl x y) : is_compl (f x) (f y) := ⟨by { rw [← f.map_bot, ← f.map_inf, f.map_rel_iff], exact h.1 }, by { rw [← f.map_top, ← f.map_sup, f.map_rel_iff], exact h.2 }⟩ theorem order_iso.is_compl_iff {x y : Ξ±} : is_compl x y ↔ is_compl (f x) (f y) := ⟨f.is_compl, Ξ» h, begin rw [← f.symm_apply_apply x, ← f.symm_apply_apply y], exact f.symm.is_compl h, end⟩ lemma order_iso.is_complemented [is_complemented Ξ±] : is_complemented Ξ² := ⟨λ x, begin obtain ⟨y, hy⟩ := exists_is_compl (f.symm x), rw ← f.symm_apply_apply y at hy, refine ⟨f y, f.symm.is_compl_iff.2 hy⟩, end⟩ theorem order_iso.is_complemented_iff : is_complemented Ξ± ↔ is_complemented Ξ² := ⟨by { introI, exact f.is_complemented }, by { introI, exact f.symm.is_complemented }⟩ end bounded_lattice end lattice_isos
ea39da092c2ec8695f00ea535fe5ef0edb706470
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/group_action/opposite.lean
10bdc5494a0fde5cdfc0af06c1bf5ec45d556daf
[ "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
5,599
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.group.opposite import group_theory.group_action.defs /-! # Scalar actions on and by `Mᡐᡒᡖ` This file defines the actions on the opposite type `has_scalar R Mᡐᡒᡖ`, and actions by the opposite type, `has_scalar Rᡐᡒᡖ M`. Note that `mul_opposite.has_scalar` is provided in an earlier file as it is needed to provide the `add_monoid.nsmul` and `add_comm_group.gsmul` fields. -/ variables (Ξ± : Type*) /-! ### Actions _on_ the opposite type Actions on the opposite type just act on the underlying type. -/ namespace mul_opposite @[to_additive] instance (R : Type*) [monoid R] [mul_action R Ξ±] : mul_action R αᡐᡒᡖ := { one_smul := Ξ» x, unop_injective $ one_smul R (unop x), mul_smul := Ξ» r₁ rβ‚‚ x, unop_injective $ mul_smul r₁ rβ‚‚ (unop x), .. mul_opposite.has_scalar Ξ± R } instance (R : Type*) [monoid R] [add_monoid Ξ±] [distrib_mul_action R Ξ±] : distrib_mul_action R αᡐᡒᡖ := { smul_add := Ξ» r x₁ xβ‚‚, unop_injective $ smul_add r (unop x₁) (unop xβ‚‚), smul_zero := Ξ» r, unop_injective $ smul_zero r, .. mul_opposite.mul_action Ξ± R } instance (R : Type*) [monoid R] [monoid Ξ±] [mul_distrib_mul_action R Ξ±] : mul_distrib_mul_action R αᡐᡒᡖ := { smul_mul := Ξ» r x₁ xβ‚‚, unop_injective $ smul_mul' r (unop xβ‚‚) (unop x₁), smul_one := Ξ» r, unop_injective $ smul_one r, .. mul_opposite.mul_action Ξ± R } instance {M N} [has_scalar M N] [has_scalar M Ξ±] [has_scalar N Ξ±] [is_scalar_tower M N Ξ±] : is_scalar_tower M N αᡐᡒᡖ := ⟨λ x y z, unop_injective $ smul_assoc _ _ _⟩ @[to_additive] instance {M N} [has_scalar M Ξ±] [has_scalar N Ξ±] [smul_comm_class M N Ξ±] : smul_comm_class M N αᡐᡒᡖ := ⟨λ x y z, unop_injective $ smul_comm _ _ _⟩ instance (R : Type*) [has_scalar R Ξ±] [has_scalar Rᡐᡒᡖ Ξ±] [is_central_scalar R Ξ±] : is_central_scalar R αᡐᡒᡖ := ⟨λ r m, unop_injective $ op_smul_eq_smul _ _⟩ lemma op_smul_eq_op_smul_op {R : Type*} [has_scalar R Ξ±] [has_scalar Rᡐᡒᡖ Ξ±] [is_central_scalar R Ξ±] (r : R) (a : Ξ±) : op (r β€’ a) = op r β€’ op a := (op_smul_eq_smul r (op a)).symm lemma unop_smul_eq_unop_smul_unop {R : Type*} [has_scalar R Ξ±] [has_scalar Rᡐᡒᡖ Ξ±] [is_central_scalar R Ξ±] (r : Rᡐᡒᡖ) (a : αᡐᡒᡖ) : unop (r β€’ a) = unop r β€’ unop a := (unop_smul_eq_smul r (unop a)).symm end mul_opposite /-! ### Actions _by_ the opposite type (right actions) In `has_mul.to_has_scalar` in another file, we define the left action `a₁ β€’ aβ‚‚ = a₁ * aβ‚‚`. For the multiplicative opposite, we define `mul_opposite.op a₁ β€’ aβ‚‚ = aβ‚‚ * a₁`, with the multiplication reversed. -/ open mul_opposite /-- Like `has_mul.to_has_scalar`, but multiplies on the right. See also `monoid.to_opposite_mul_action` and `monoid_with_zero.to_opposite_mul_action_with_zero`. -/ @[to_additive] instance has_mul.to_has_opposite_scalar [has_mul Ξ±] : has_scalar αᡐᡒᡖ Ξ± := { smul := Ξ» c x, x * c.unop } @[to_additive] lemma op_smul_eq_mul [has_mul Ξ±] {a a' : Ξ±} : op a β€’ a' = a' * a := rfl @[simp, to_additive] lemma mul_opposite.smul_eq_mul_unop [has_mul Ξ±] {a : αᡐᡒᡖ} {a' : Ξ±} : a β€’ a' = a' * a.unop := rfl /-- The right regular action of a group on itself is transitive. -/ @[to_additive "The right regular action of an additive group on itself is transitive."] instance mul_action.opposite_regular.is_pretransitive {G : Type*} [group G] : mul_action.is_pretransitive Gᡐᡒᡖ G := ⟨λ x y, ⟨op (x⁻¹ * y), mul_inv_cancel_left _ _⟩⟩ @[to_additive] instance semigroup.opposite_smul_comm_class [semigroup Ξ±] : smul_comm_class αᡐᡒᡖ Ξ± Ξ± := { smul_comm := Ξ» x y z, (mul_assoc _ _ _) } @[to_additive] instance semigroup.opposite_smul_comm_class' [semigroup Ξ±] : smul_comm_class Ξ± αᡐᡒᡖ Ξ± := smul_comm_class.symm _ _ _ instance comm_semigroup.is_central_scalar [comm_semigroup Ξ±] : is_central_scalar Ξ± Ξ± := ⟨λ r m, mul_comm _ _⟩ /-- Like `monoid.to_mul_action`, but multiplies on the right. -/ @[to_additive] instance monoid.to_opposite_mul_action [monoid Ξ±] : mul_action αᡐᡒᡖ Ξ± := { smul := (β€’), one_smul := mul_one, mul_smul := Ξ» x y r, (mul_assoc _ _ _).symm } instance is_scalar_tower.opposite_mid {M N} [has_mul N] [has_scalar M N] [smul_comm_class M N N] : is_scalar_tower M Nᡐᡒᡖ N := ⟨λ x y z, mul_smul_comm _ _ _⟩ instance smul_comm_class.opposite_mid {M N} [has_mul N] [has_scalar M N] [is_scalar_tower M N N] : smul_comm_class M Nᡐᡒᡖ N := ⟨λ x y z, by { induction y using mul_opposite.rec, simp [smul_mul_assoc] }⟩ -- The above instance does not create an unwanted diamond, the two paths to -- `mul_action αᡐᡒᡖ αᡐᡒᡖ` are defeq. example [monoid Ξ±] : monoid.to_mul_action αᡐᡒᡖ = mul_opposite.mul_action Ξ± αᡐᡒᡖ := rfl /-- `monoid.to_opposite_mul_action` is faithful on cancellative monoids. -/ @[to_additive] instance left_cancel_monoid.to_has_faithful_opposite_scalar [left_cancel_monoid Ξ±] : has_faithful_scalar αᡐᡒᡖ Ξ± := ⟨λ x y h, unop_injective $ mul_left_cancel (h 1)⟩ /-- `monoid.to_opposite_mul_action` is faithful on nontrivial cancellative monoids with zero. -/ instance cancel_monoid_with_zero.to_has_faithful_opposite_scalar [cancel_monoid_with_zero Ξ±] [nontrivial Ξ±] : has_faithful_scalar αᡐᡒᡖ Ξ± := ⟨λ x y h, unop_injective $ mul_left_cancelβ‚€ one_ne_zero (h 1)⟩
27a8316a0407ae5858fd283cc20854909c354467
2dae50597b29069308a49d0995d06d4a0720029a
/src/parsing_example.lean
6d1980c11fce0f22e5011b98d6f92b6d4b20a37b
[ "Apache-2.0" ]
permissive
jasonrute/lean-proof-recording-public-old
d94ae9ba64c1cbf49cda9fb4f25755a3d92fb171
34e75a8bb67b6527177b217c9207191d409368dd
refs/heads/master
1,678,527,177,787
1,613,767,073,000
1,613,767,073,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,515
lean
import init.meta.lean.parser --set_option pp.colors false namespace parser open lean meta def get_options : parser options := Ξ» s, interaction_monad.result.success s.options s meta def myparser : parser unit := do p <- parser.cur_pos, o <- get_options, tactic.trace "Inside parser", tactic.trace o, tactic.trace p, return () @[reducible] protected meta def my_itactic : parser (tactic unit) := parser.val (do pos <- parser.cur_pos, tactic.trace pos, a <- parser.itactic_reflected, pos <- parser.cur_pos, tactic.trace pos, return a) meta def pr_parser {Ξ± : Type} (p : parser Ξ±) [lean.parser.reflectable p] : parser Ξ± := do pos <- parser.cur_pos, tactic.trace pos, a <- p, pos <- parser.cur_pos, tactic.trace pos, return a end parser meta def tactic.interactive.my_try (t : interactive.parse parser.my_itactic) : tactic unit := tactic.try t meta def tactic.interactive.my_apply (q : interactive.parse $ parser.pr_parser $ interactive.types.texpr) : tactic unit := tactic.interactive.concat_tags (do h ← tactic.i_to_expr_for_apply q, tactic.apply h) set_option pp.all true #check interactive.parse $ interactive.types.texpr #check interactive.parse $ parser.pr_parser $ interactive.types.texpr #check interactive.parse $ parser.my_itactic #check interactive.parse $ lean.parser.itactic #check interactive.parse $ parser.pr_parser $ lean.parser.itactic #check @lean.parser.reflectable.cast (tactic.{0} unit) lean.parser.itactic_reflected example : true := begin my_try { my_apply true.intro }, end
d31d015aac3229176e4dbd9d80a5a39a35927385
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/toExpr.lean
eb1133af2cd15511a4b2614b2355eb56ac38913f
[ "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
782
lean
import Lean open Lean unsafe def test {Ξ± : Type} [ToString Ξ±] [ToExpr Ξ±] [BEq Ξ±] (a : Ξ±) : CoreM Unit := do let env ← getEnv; let auxName := `_toExpr._test; let decl := Declaration.defnDecl { name := auxName, lparams := [], value := toExpr a, type := toTypeExpr Ξ±, hints := ReducibilityHints.abbrev, isUnsafe := false }; IO.println (toExpr a); (match env.addAndCompile {} decl with | Except.error _ => throwError "addDecl failed" | Except.ok env => match env.evalConst Ξ± {} auxName with | Except.error ex => throwError ex | Except.ok b => do IO.println b; Β«unlessΒ» (a == b) $ throwError "toExpr failed"; pure ()) #eval test #[(1, 2), (3, 4)] #eval test ['a', 'b', 'c'] #eval test ("hello", true) #eval test ((), 10)
4c6b77d8bad0b92cc2891430b710a811d86f2b6f
76df16d6c3760cb415f1294caee997cc4736e09b
/lean/src/cs/dets.lean
87bff4f5cce24dc23c8a583836cc7ac94aca6dd6
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
5,641
lean
import tactic.basic import tactic.split_ifs import tactic.linarith import tactic.apply_fun import .svm import .lib import .hp import .mrg namespace sym open lang section det variables {Model SymB SymV D O : Type} [inhabited Model] [inhabited SymV] (f : factory Model SymB SymV D O) {m : Model} -- The SVM rules are deterministic: given the same environment and -- state, they produce the same result . theorem svm_det {x : exp D O} {Ξ΅ : env SymV} {Οƒ : state SymB} {ρ1 ρ2 : result SymB SymV} : evalS f x Ξ΅ Οƒ ρ1 β†’ evalS f x Ξ΅ Οƒ ρ2 β†’ ρ1 = ρ2 := begin intros h1 h2, induction h1 generalizing ρ2, case sym.evalS.app { cases h2, congr, apply list.ext_le, { rewrite [←h1_h1, ←h2_h1], }, { intros i h1 h2, have hx : i < h1_xs.length := by { simp only [h1_h1, h1], }, specialize h2_h2 i hx h2, specialize h1_ih i hx h1 h2_h2, simp only [true_and, eq_self_iff_true] at h1_ih, exact h1_ih, } }, case sym.evalS.call_sym { cases h2, { clear h2, specialize h1_ih_h1 h2_h1, simp only at h1_ih_h1, specialize h1_ih_h2 h2_h2, simp only at h1_ih_h2, congr, { simp only [h1_h3, h2_h3, h1_ih_h1], }, { apply list.ext_le, { apply_fun list.length at h1_h5 h2_h5, simp only [list.length_map] at h1_h5 h2_h5, rewrite [←h1_h5, ←h2_h5], simp only [h1_ih_h1], }, { intros i h1 h2, cases h1_ih_h1 with h1_ih_h1_Οƒ h1_ih_h1_c, cases h1_ih_h2 with h1_ih_h2_Οƒ h1_ih_h2_v, specialize h2_h6 i (list.map_bound (eq.symm h2_h5) h2) h2, have hc1 : i < list.length (f.cast h1_c) := (list.map_bound (eq.symm h1_h5) h1), have hc2 : i < list.length (f.cast h2_c) := (list.map_bound (eq.symm h2_h5) h2), have h : (list.nth_le (f.cast h2_c) i hc2) = (list.nth_le (f.cast h1_c) i hc1) := by { congr, simp only [h1_ih_h1_c], }, have h' : h2_Οƒ' = h1_Οƒ' := by { simp only [h1_h3, h2_h3, h1_ih_h1_c], }, simp only [h, h'] at h2_h6, rewrite ←h1_ih_h2_v at h2_h6, specialize h1_ih_h6 i hc1 h1 h2_h6, cases h1' : list.nth_le h1_grs i h1, cases h2' : list.nth_le h2_grs i h2, congr, { apply_fun choice.guard at h1' h2', rewrite [←h1', ←h2'], rcases (list.nth_le_of_eq h1_h5 (by {simp only [list.length_map], exact hc1,})) with hq1, simp only [list.nth_le_map'] at hq1, rcases (list.nth_le_of_eq h2_h5 (by {simp only [list.length_map], exact hc2,})) with hq2, simp only [list.nth_le_map'] at hq2, rewrite [←hq1, ←hq2], simp only [h1_ih_h1_c], }, { simp only [h1', h2'] at h1_ih_h6, exact h1_ih_h6, } } } }, { specialize h1_ih_h1 h2_h1, simp only at h1_ih_h1, simp only [h1_ih_h1, h1_h3] at h1_h4, simp only [h1_h4, h2_h3, or_self] at h2_h4, contradiction, } }, case sym.evalS.call_halt { cases h2, { specialize h1_ih_h1 h2_h1, simp only at h1_ih_h1, simp only [h1_ih_h1, h1_h3] at h1_h4, simp only [h2_h3, eq_ff_eq_not_eq_tt] at h2_h4, simp only [h2_h4, coe_sort_ff, or_self] at h1_h4, contradiction, }, { specialize h1_ih_h1 h2_h1, simp only at h1_ih_h1, simp only [h1_h3, h2_h3], congr, simp only [h1_ih_h1], } }, case sym.evalS.let0 { cases h2, { specialize h1_ih_h1 h2_h1, simp only at h1_ih_h1, apply h1_ih_h2, simp only [h1_ih_h1, h2_h2], }, { specialize h1_ih_h1 h2_h1, simp only at h1_ih_h1, contradiction, } }, case sym.evalS.let0_halt { cases h2, { specialize h1_ih h2_h1, simp only at h1_ih, contradiction}, { apply h1_ih h2_h1, } }, case sym.evalS.if0_true { cases h2; specialize h1_ih_hc h2_hc; simp only [true_and, eq_self_iff_true] at h1_ih_hc; simp only [h1_ih_hc] at h1_hv, { apply h1_ih_hr h2_hr, }, { rewrite [f.is_tt_sound] at h1_hv, rewrite [f.is_ff_sound] at h2_hv, rewrite h1_hv at h2_hv, rcases (f.tt_neq_ff) with hn, contradiction, }, { clear h2, elide 0, simp only [h1_hv, not_true, false_and] at h2_hv, contradiction, }, }, case sym.evalS.if0_false { cases h2; specialize h1_ih_hc h2_hc; simp only [true_and, eq_self_iff_true] at h1_ih_hc; simp only [h1_ih_hc] at h1_hv, { rewrite [f.is_tt_sound] at h2_hv, rewrite [f.is_ff_sound] at h1_hv, rewrite h2_hv at h1_hv, rcases (f.tt_neq_ff) with hn, contradiction, }, { apply h1_ih_hr h2_hr, }, { clear h2, elide 0, simp only [h1_hv, not_true, and_false] at h2_hv, contradiction, }, }, case sym.evalS.if0_sym { cases h2; specialize h1_ih_hc h2_hc; simp only [true_and, eq_self_iff_true] at h1_ih_hc; simp only [h1_ih_hc] at h1_hv, { simp only [h1_hv, not_true, false_and] at h2_hv, contradiction, }, { simp only [h1_hv, not_true, and_false] at h2_hv, contradiction, }, { clear h2, congr, any_goals { exact h1_ih_hc, }, { apply h1_ih_ht, simp only [h1_ih_hc, h2_ht], }, { apply h1_ih_hf, simp only [h1_ih_hc, h2_hf], }, }, }, all_goals { cases h2, refl, }, end end det end sym
f566163996e9b5ea7d24cbc6d4619eee006c297b
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/order/filter/germ.lean
47e16ee88442a73e42b65a4d14adde50abd48b4a
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
23,032
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Abhimanyu Pallavi Sudhir -/ import order.filter.basic import algebra.pi_instances /-! # Germ of a function at a filter The germ of a function `f : Ξ± β†’ Ξ²` at a filter `l : filter Ξ±` is the equivalence class of `f` with respect to the equivalence relation `eventually_eq l`: `f β‰ˆ g` means `βˆ€αΆ  x in l, f x = g x`. ## Main definitions We define * `germ l Ξ²` to be the space of germs of functions `Ξ± β†’ Ξ²` at a filter `l : filter Ξ±`; * coercion from `Ξ± β†’ Ξ²` to `germ l Ξ²`: `(f : germ l Ξ²)` is the germ of `f : Ξ± β†’ Ξ²` at `l : filter Ξ±`; this coercion is declared as `has_coe_t`, so it does not require an explicit up arrow `↑`; * coercion from `Ξ²` to `germ l Ξ²`: `(↑c : germ l Ξ²)` is the germ of the constant function `Ξ» x:Ξ±, c` at a filter `l`; this coercion is declared as `has_lift_t`, so it requires an explicit up arrow `↑`, see [TPiL][TPiL_coe] for details. * `map (F : Ξ² β†’ Ξ³) (f : germ l Ξ²)` to be the composition of a function `F` and a germ `f`; * `mapβ‚‚ (F : Ξ² β†’ Ξ³ β†’ Ξ΄) (f : germ l Ξ²) (g : germ l Ξ³)` to be the germ of `Ξ» x, F (f x) (g x)` at `l`; * `f.tendsto lb`: we say that a germ `f : germ l Ξ²` tends to a filter `lb` if its representatives tend to `lb` along `l`; * `f.comp_tendsto g hg` and `f.comp_tendsto' g hg`: given `f : germ l Ξ²` and a function `g : Ξ³ β†’ Ξ±` (resp., a germ `g : germ lc Ξ±`), if `g` tends to `l` along `lc`, then the composition `f ∘ g` is a well-defined germ at `lc`; * `germ.lift_pred`, `germ.lift_rel`: lift a predicate or a relation to the space of germs: `(f : germ l Ξ²).lift_pred p` means `βˆ€αΆ  x in l, p (f x)`, and similarly for a relation. [TPiL_coe]: https://leanprover.github.io/theorem_proving_in_lean/type_classes.html#coercions-using-type-classes We also define `map (F : Ξ² β†’ Ξ³) : germ l Ξ² β†’ germ l Ξ³` sending each germ `f` to `F ∘ f`. For each of the following structures we prove that if `Ξ²` has this structure, then so does `germ l Ξ²`: * one-operation algebraic structures up to `comm_group`; * `mul_zero_class`, `distrib`, `semiring`, `comm_semiring`, `ring`, `comm_ring`; * `mul_action`, `distrib_mul_action`, `semimodule`; * `preorder`, `partial_order`, and `lattice` structures up to `bounded_lattice`; * `ordered_cancel_comm_monoid` and `ordered_cancel_add_comm_monoid`. ## Tags filter, germ -/ namespace filter variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*} {l : filter Ξ±} {f g h : Ξ± β†’ Ξ²} lemma const_eventually_eq' (hl : l β‰  βŠ₯) {a b : Ξ²} : (βˆ€αΆ  x in l, a = b) ↔ a = b := eventually_const hl lemma const_eventually_eq (hl : l β‰  βŠ₯) {a b : Ξ²} : ((Ξ» _, a) =αΆ [l] (Ξ» _, b)) ↔ a = b := @const_eventually_eq' _ _ _ hl a b lemma eventually_eq.comp_tendsto {f' : Ξ± β†’ Ξ²} (H : f =αΆ [l] f') {g : Ξ³ β†’ Ξ±} {lc : filter Ξ³} (hg : tendsto g lc l) : f ∘ g =αΆ [lc] f' ∘ g := hg.eventually H section has_le variables [has_le Ξ²] /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter Ξ±) (f g : Ξ± β†’ Ξ²) : Prop := βˆ€αΆ  x in l, f x ≀ g x notation f ` ≀ᢠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : Ξ± β†’ Ξ²} (H : f ≀ᢠ[l] g) (hf : f =αΆ [l] f') (hg : g =αΆ [l] g') : f' ≀ᢠ[l] g' := H.mp $ hg.mp $ hf.mono $ Ξ» x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : Ξ± β†’ Ξ²} (hf : f =αΆ [l] f') (hg : g =αΆ [l] g') : f ≀ᢠ[l] g ↔ f' ≀ᢠ[l] g' := ⟨λ H, H.congr hf hg, Ξ» H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder Ξ²] lemma eventually_eq.le (h : f =αΆ [l] g) : f ≀ᢠ[l] g := h.mono $ Ξ» x, le_of_eq @[refl] lemma eventually_le.refl (l : filter Ξ±) (f : Ξ± β†’ Ξ²) : f ≀ᢠ[l] f := (eventually_eq.refl l f).le @[trans] lemma eventually_le.trans (H₁ : f ≀ᢠ[l] g) (Hβ‚‚ : g ≀ᢠ[l] h) : f ≀ᢠ[l] h := Hβ‚‚.mp $ H₁.mono $ Ξ» x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =αΆ [l] g) (Hβ‚‚ : g ≀ᢠ[l] h) : f ≀ᢠ[l] h := H₁.le.trans Hβ‚‚ @[trans] lemma eventually_le.trans_eq (H₁ : f ≀ᢠ[l] g) (Hβ‚‚ : g =αΆ [l] h) : f ≀ᢠ[l] h := H₁.trans Hβ‚‚.le end preorder lemma eventually_le.antisymm [partial_order Ξ²] (h₁ : f ≀ᢠ[l] g) (hβ‚‚ : g ≀ᢠ[l] f) : f =αΆ [l] g := hβ‚‚.mp $ h₁.mono $ Ξ» x, le_antisymm /-- Setoid used to define the space of germs. -/ def germ_setoid (l : filter Ξ±) (Ξ² : Type*) : setoid (Ξ± β†’ Ξ²) := { r := eventually_eq l, iseqv := ⟨eventually_eq.refl _, Ξ» _ _, eventually_eq.symm, Ξ» _ _ _, eventually_eq.trans⟩ } /-- The space of germs of functions `Ξ± β†’ Ξ²` at a filter `l`. -/ def germ (l : filter Ξ±) (Ξ² : Type*) : Type* := quotient (germ_setoid l Ξ²) namespace germ instance : has_coe_t (Ξ± β†’ Ξ²) (germ l Ξ²) := ⟨quotient.mk'⟩ instance : has_lift_t Ξ² (germ l Ξ²) := ⟨λ c, ↑(Ξ» (x : Ξ±), c)⟩ @[simp] lemma quot_mk_eq_coe (l : filter Ξ±) (f : Ξ± β†’ Ξ²) : quot.mk _ f = (f : germ l Ξ²) := rfl @[simp] lemma mk'_eq_coe (l : filter Ξ±) (f : Ξ± β†’ Ξ²) : quotient.mk' f = (f : germ l Ξ²) := rfl @[elab_as_eliminator] lemma induction_on (f : germ l Ξ²) {p : germ l Ξ² β†’ Prop} (h : βˆ€ f : Ξ± β†’ Ξ², p f) : p f := quotient.induction_on' f h @[elab_as_eliminator] lemma induction_onβ‚‚ (f : germ l Ξ²) (g : germ l Ξ³) {p : germ l Ξ² β†’ germ l Ξ³ β†’ Prop} (h : βˆ€ (f : Ξ± β†’ Ξ²) (g : Ξ± β†’ Ξ³), p f g) : p f g := quotient.induction_onβ‚‚' f g h @[elab_as_eliminator] lemma induction_on₃ (f : germ l Ξ²) (g : germ l Ξ³) (h : germ l Ξ΄) {p : germ l Ξ² β†’ germ l Ξ³ β†’ germ l Ξ΄ β†’ Prop} (H : βˆ€ (f : Ξ± β†’ Ξ²) (g : Ξ± β†’ Ξ³) (h : Ξ± β†’ Ξ΄), p f g h) : p f g h := quotient.induction_on₃' f g h H /-- Given a map `F : (Ξ± β†’ Ξ²) β†’ (Ξ³ β†’ Ξ΄)` that sends functions eventually equal at `l` to functions eventually equal at `lc`, returns a map from `germ l Ξ²` to `germ lc Ξ΄`. -/ def map' {lc : filter Ξ³} (F : (Ξ± β†’ Ξ²) β†’ (Ξ³ β†’ Ξ΄)) (hF : (l.eventually_eq β‡’ lc.eventually_eq) F F) : germ l Ξ² β†’ germ lc Ξ΄ := quotient.map' F hF /-- Given a germ `f : germ l Ξ²` and a function `F : (Ξ± β†’ Ξ²) β†’ Ξ³` sending eventually equal functions to the same value, returns the value `F` takes on functions having germ `f` at `l`. -/ def lift_on {Ξ³ : Sort*} (f : germ l Ξ²) (F : (Ξ± β†’ Ξ²) β†’ Ξ³) (hF : (l.eventually_eq β‡’ (=)) F F) : Ξ³ := quotient.lift_on' f F hF @[simp] lemma map'_coe {lc : filter Ξ³} (F : (Ξ± β†’ Ξ²) β†’ (Ξ³ β†’ Ξ΄)) (hF : (l.eventually_eq β‡’ lc.eventually_eq) F F) (f : Ξ± β†’ Ξ²) : map' F hF f = F f := rfl @[simp, norm_cast] lemma coe_eq : (f : germ l Ξ²) = g ↔ (f =αΆ [l] g) := quotient.eq' alias coe_eq ↔ _ filter.eventually_eq.germ_eq /-- Lift a function `Ξ² β†’ Ξ³` to a function `germ l Ξ² β†’ germ l Ξ³`. -/ def map (op : Ξ² β†’ Ξ³) : germ l Ξ² β†’ germ l Ξ³ := map' ((∘) op) $ Ξ» f g H, H.mono $ Ξ» x H, congr_arg op H @[simp] lemma map_coe (op : Ξ² β†’ Ξ³) (f : Ξ± β†’ Ξ²) : map op (f : germ l Ξ²) = op ∘ f := rfl @[simp] lemma map_id : map id = (id : germ l Ξ² β†’ germ l Ξ²) := by { ext ⟨f⟩, refl } lemma map_map (op₁ : Ξ³ β†’ Ξ΄) (opβ‚‚ : Ξ² β†’ Ξ³) (f : germ l Ξ²) : map op₁ (map opβ‚‚ f) = map (op₁ ∘ opβ‚‚) f := induction_on f $ Ξ» f, rfl /-- Lift a binary function `Ξ² β†’ Ξ³ β†’ Ξ΄` to a function `germ l Ξ² β†’ germ l Ξ³ β†’ germ l Ξ΄`. -/ def mapβ‚‚ (op : Ξ² β†’ Ξ³ β†’ Ξ΄) : germ l Ξ² β†’ germ l Ξ³ β†’ germ l Ξ΄ := quotient.mapβ‚‚' (Ξ» f g x, op (f x) (g x)) $ Ξ» f f' Hf g g' Hg, Hg.mp $ Hf.mono $ Ξ» x Hf Hg, by simp only [Hf, Hg] /-- A germ at `l` of maps from `Ξ±` to `Ξ²` tends to `lb : filter Ξ²` if it is represented by a map which tends to `lb` along `l`. -/ protected def tendsto (f : germ l Ξ²) (lb : filter Ξ²) : Prop := lift_on f (Ξ» f, tendsto f l lb) $ Ξ» f g H, propext (tendsto_congr' H) @[simp, norm_cast] lemma coe_tendsto {f : Ξ± β†’ Ξ²} {lb : filter Ξ²} : (f : germ l Ξ²).tendsto lb ↔ tendsto f l lb := iff.rfl alias coe_tendsto ↔ _ filter.tendsto.germ_tendsto /-- Given two germs `f : germ l Ξ²`, and `g : germ lc Ξ±`, where `l : filter Ξ±`, if `g` tends to `l`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto' (f : germ l Ξ²) {lc : filter Ξ³} (g : germ lc Ξ±) (hg : g.tendsto l) : germ lc Ξ² := lift_on f (Ξ» f, g.map f) $ Ξ» f₁ fβ‚‚ hF, (induction_on g $ Ξ» g hg, coe_eq.2 $ hg.eventually hF) hg @[simp] lemma coe_comp_tendsto' (f : Ξ± β†’ Ξ²) {lc : filter Ξ³} {g : germ lc Ξ±} (hg : g.tendsto l) : (f : germ l Ξ²).comp_tendsto' g hg = g.map f := rfl /-- Given a germ `f : germ l Ξ²` and a function `g : Ξ³ β†’ Ξ±`, where `l : filter Ξ±`, if `g` tends to `l` along `lc : filter Ξ³`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto (f : germ l Ξ²) {lc : filter Ξ³} (g : Ξ³ β†’ Ξ±) (hg : tendsto g lc l) : germ lc Ξ² := f.comp_tendsto' _ hg.germ_tendsto @[simp] lemma coe_comp_tendsto (f : Ξ± β†’ Ξ²) {lc : filter Ξ³} {g : Ξ³ β†’ Ξ±} (hg : tendsto g lc l) : (f : germ l Ξ²).comp_tendsto g hg = f ∘ g := rfl @[simp] lemma comp_tendsto'_coe (f : germ l Ξ²) {lc : filter Ξ³} {g : Ξ³ β†’ Ξ±} (hg : tendsto g lc l) : f.comp_tendsto' _ hg.germ_tendsto = f.comp_tendsto g hg := rfl @[simp, norm_cast] lemma const_inj (hl : l β‰  βŠ₯) {a b : Ξ²} : (↑a : germ l Ξ²) = ↑b ↔ a = b := coe_eq.trans $ const_eventually_eq hl @[simp] lemma map_const (l : filter Ξ±) (a : Ξ²) (f : Ξ² β†’ Ξ³) : (↑a : germ l Ξ²).map f = ↑(f a) := rfl @[simp] lemma mapβ‚‚_const (l : filter Ξ±) (b : Ξ²) (c : Ξ³) (f : Ξ² β†’ Ξ³ β†’ Ξ΄) : mapβ‚‚ f (↑b : germ l Ξ²) ↑c = ↑(f b c) := rfl @[simp] lemma const_comp_tendsto {l : filter Ξ±} (b : Ξ²) {lc : filter Ξ³} {g : Ξ³ β†’ Ξ±} (hg : tendsto g lc l) : (↑b : germ l Ξ²).comp_tendsto g hg = ↑b := rfl @[simp] lemma const_comp_tendsto' {l : filter Ξ±} (b : Ξ²) {lc : filter Ξ³} {g : germ lc Ξ±} (hg : g.tendsto l) : (↑b : germ l Ξ²).comp_tendsto' g hg = ↑b := induction_on g (Ξ» _ _, rfl) hg /-- Lift a predicate on `Ξ²` to `germ l Ξ²`. -/ def lift_pred (p : Ξ² β†’ Prop) (f : germ l Ξ²) : Prop := lift_on f (Ξ» f, βˆ€αΆ  x in l, p (f x)) $ Ξ» f g H, propext $ eventually_congr $ H.mono $ Ξ» x hx, hx β–Έ iff.rfl @[simp] lemma lift_pred_coe {p : Ξ² β†’ Prop} {f : Ξ± β†’ Ξ²} : lift_pred p (f : germ l Ξ²) ↔ βˆ€αΆ  x in l, p (f x) := iff.rfl lemma lift_pred_const {p : Ξ² β†’ Prop} {x : Ξ²} (hx : p x) : lift_pred p (↑x : germ l Ξ²) := eventually_of_forall _ $ Ξ» y, hx @[simp] lemma lift_pred_const_iff (hl : l β‰  βŠ₯) {p : Ξ² β†’ Prop} {x : Ξ²} : lift_pred p (↑x : germ l Ξ²) ↔ p x := @eventually_const _ _ hl (p x) /-- Lift a relation `r : Ξ² β†’ Ξ³ β†’ Prop` to `germ l Ξ² β†’ germ l Ξ³ β†’ Prop`. -/ def lift_rel (r : Ξ² β†’ Ξ³ β†’ Prop) (f : germ l Ξ²) (g : germ l Ξ³) : Prop := quotient.lift_onβ‚‚' f g (Ξ» f g, βˆ€αΆ  x in l, r (f x) (g x)) $ Ξ» f g f' g' Hf Hg, propext $ eventually_congr $ Hg.mp $ Hf.mono $ Ξ» x hf hg, hf β–Έ hg β–Έ iff.rfl @[simp] lemma lift_rel_coe {r : Ξ² β†’ Ξ³ β†’ Prop} {f : Ξ± β†’ Ξ²} {g : Ξ± β†’ Ξ³} : lift_rel r (f : germ l Ξ²) g ↔ βˆ€αΆ  x in l, r (f x) (g x) := iff.rfl lemma lift_rel_const {r : Ξ² β†’ Ξ³ β†’ Prop} {x : Ξ²} {y : Ξ³} (h : r x y) : lift_rel r (↑x : germ l Ξ²) ↑y := eventually_of_forall _ $ Ξ» _, h @[simp] lemma lift_rel_const_iff (hl : l β‰  βŠ₯) {r : Ξ² β†’ Ξ³ β†’ Prop} {x : Ξ²} {y : Ξ³} : lift_rel r (↑x : germ l Ξ²) ↑y ↔ r x y := @eventually_const _ _ hl (r x y) instance [inhabited Ξ²] : inhabited (germ l Ξ²) := βŸ¨β†‘(default Ξ²)⟩ section monoid variables {M : Type*} {G : Type*} @[to_additive] instance [has_mul M] : has_mul (germ l M) := ⟨mapβ‚‚ (*)⟩ @[simp, to_additive] lemma coe_mul [has_mul M] (f g : Ξ± β†’ M) : ↑(f * g) = (f * g : germ l M) := rfl attribute [norm_cast] coe_mul coe_add @[to_additive] instance [has_one M] : has_one (germ l M) := βŸ¨β†‘(1:M)⟩ @[simp, to_additive] lemma coe_one [has_one M] : ↑(1 : Ξ± β†’ M) = (1 : germ l M) := rfl attribute [norm_cast] coe_one coe_zero @[to_additive add_semigroup] instance [semigroup M] : semigroup (germ l M) := { mul := (*), mul_assoc := by { rintros ⟨f⟩ ⟨g⟩ ⟨h⟩, simp only [mul_assoc, quot_mk_eq_coe, ← coe_mul] } } @[to_additive add_comm_semigroup] instance [comm_semigroup M] : comm_semigroup (germ l M) := { mul := (*), mul_comm := by { rintros ⟨f⟩ ⟨g⟩, simp only [mul_comm, quot_mk_eq_coe, ← coe_mul] }, .. germ.semigroup } @[to_additive add_left_cancel_semigroup] instance [left_cancel_semigroup M] : left_cancel_semigroup (germ l M) := { mul := (*), mul_left_cancel := Ξ» f₁ fβ‚‚ f₃, induction_on₃ f₁ fβ‚‚ f₃ $ Ξ» f₁ fβ‚‚ f₃ H, coe_eq.2 ((coe_eq.1 H).mono $ Ξ» x, mul_left_cancel), .. germ.semigroup } @[to_additive add_right_cancel_semigroup] instance [right_cancel_semigroup M] : right_cancel_semigroup (germ l M) := { mul := (*), mul_right_cancel := Ξ» f₁ fβ‚‚ f₃, induction_on₃ f₁ fβ‚‚ f₃ $ Ξ» f₁ fβ‚‚ f₃ H, coe_eq.2 $ (coe_eq.1 H).mono $ Ξ» x, mul_right_cancel, .. germ.semigroup } @[to_additive add_monoid] instance [monoid M] : monoid (germ l M) := { mul := (*), one := 1, one_mul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [one_mul] }, mul_one := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [mul_one] }, .. germ.semigroup } /-- coercion from functions to germs as a monoid homomorphism. -/ @[to_additive] def coe_mul_hom [monoid M] (l : filter Ξ±) : (Ξ± β†’ M) β†’* germ l M := ⟨coe, rfl, Ξ» f g, rfl⟩ /-- coercion from functions to germs as an additive monoid homomorphism. -/ add_decl_doc coe_add_hom @[simp, to_additive] lemma coe_coe_mul_hom [monoid M] : (coe_mul_hom l : (Ξ± β†’ M) β†’ germ l M) = coe := rfl @[to_additive add_comm_monoid] instance [comm_monoid M] : comm_monoid (germ l M) := { mul := (*), one := 1, .. germ.comm_semigroup, .. germ.monoid } @[to_additive] instance [has_inv G] : has_inv (germ l G) := ⟨map has_inv.inv⟩ @[simp, to_additive] lemma coe_inv [has_inv G] (f : Ξ± β†’ G) : ↑f⁻¹ = (f⁻¹ : germ l G) := rfl attribute [norm_cast] coe_inv coe_neg @[to_additive add_group] instance [group G] : group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, mul_left_inv := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [mul_left_inv] }, .. germ.monoid } @[simp, norm_cast] lemma coe_sub [add_group G] (f g : Ξ± β†’ G) : ↑(f - g) = (f - g : germ l G) := rfl @[to_additive add_comm_group] instance [comm_group G] : comm_group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, .. germ.group, .. germ.comm_monoid } end monoid section ring variables {R : Type*} /-- If `0 β‰  1` in `Ξ²` and `l` is a non-trivial filter (`l β‰  βŠ₯`), then `0 β‰  1` in `germ l Ξ²`. This cannot be an `instance` because it depends on `l β‰  βŠ₯`. -/ protected lemma nonzero [has_zero R] [has_one R] [nonzero R] (hl : l β‰  βŠ₯) : nonzero (germ l R) := { zero_ne_one := mt (const_inj hl).1 zero_ne_one } instance [mul_zero_class R] : mul_zero_class (germ l R) := { zero := 0, mul := (*), mul_zero := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [mul_zero] }, zero_mul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, rw [zero_mul] } } instance [distrib R] : distrib (germ l R) := { mul := (*), add := (+), left_distrib := Ξ» f g h, induction_on₃ f g h $ Ξ» f g h, by { norm_cast, rw [left_distrib] }, right_distrib := Ξ» f g h, induction_on₃ f g h $ Ξ» f g h, by { norm_cast, rw [right_distrib] } } instance [semiring R] : semiring (germ l R) := { .. germ.add_comm_monoid, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } /-- Coercion `(Ξ± β†’ R) β†’ germ l R` as a `ring_hom`. -/ def coe_ring_hom [semiring R] (l : filter Ξ±) : (Ξ± β†’ R) β†’+* germ l R := { to_fun := coe, .. (coe_mul_hom l : _ β†’* germ l R), .. (coe_add_hom l : _ β†’+ germ l R) } @[simp] lemma coe_coe_ring_hom [semiring R] : (coe_ring_hom l : (Ξ± β†’ R) β†’ germ l R) = coe := rfl instance [ring R] : ring (germ l R) := { .. germ.add_comm_group, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } instance [comm_semiring R] : comm_semiring (germ l R) := { .. germ.semiring, .. germ.comm_monoid } instance [comm_ring R] : comm_ring (germ l R) := { .. germ.ring, .. germ.comm_monoid } end ring section module variables {M N R : Type*} instance [has_scalar M Ξ²] : has_scalar M (germ l Ξ²) := ⟨λ c, map ((β€’) c)⟩ instance has_scalar' [has_scalar M Ξ²] : has_scalar (germ l M) (germ l Ξ²) := ⟨mapβ‚‚ (β€’)⟩ @[simp, norm_cast] lemma coe_smul [has_scalar M Ξ²] (c : M) (f : Ξ± β†’ Ξ²) : ↑(c β€’ f) = (c β€’ f : germ l Ξ²) := rfl @[simp, norm_cast] lemma coe_smul' [has_scalar M Ξ²] (c : Ξ± β†’ M) (f : Ξ± β†’ Ξ²) : ↑(c β€’ f) = (c : germ l M) β€’ (f : germ l Ξ²) := rfl instance [monoid M] [mul_action M Ξ²] : mul_action M (germ l Ξ²) := { one_smul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, simp only [one_smul] }, mul_smul := Ξ» c₁ cβ‚‚ f, induction_on f $ Ξ» f, by { norm_cast, simp only [mul_smul] } } instance mul_action' [monoid M] [mul_action M Ξ²] : mul_action (germ l M) (germ l Ξ²) := { one_smul := Ξ» f, induction_on f $ Ξ» f, by simp only [← coe_one, ← coe_smul', one_smul], mul_smul := Ξ» c₁ cβ‚‚ f, induction_on₃ c₁ cβ‚‚ f $ Ξ» c₁ cβ‚‚ f, by { norm_cast, simp only [mul_smul] } } instance [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action M (germ l N) := { smul_add := Ξ» c f g, induction_onβ‚‚ f g $ Ξ» f g, by { norm_cast, simp only [smul_add] }, smul_zero := Ξ» c, by simp only [← coe_zero, ← coe_smul, smul_zero] } instance distrib_mul_action' [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action (germ l M) (germ l N) := { smul_add := Ξ» c f g, induction_on₃ c f g $ Ξ» c f g, by { norm_cast, simp only [smul_add] }, smul_zero := Ξ» c, induction_on c $ Ξ» c, by simp only [← coe_zero, ← coe_smul', smul_zero] } instance [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (germ l M) := { add_smul := Ξ» c₁ cβ‚‚ f, induction_on f $ Ξ» f, by { norm_cast, simp only [add_smul] }, zero_smul := Ξ» f, induction_on f $ Ξ» f, by { norm_cast, simp only [zero_smul, coe_zero] } } instance semimodule' [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule (germ l R) (germ l M) := { add_smul := Ξ» c₁ cβ‚‚ f, induction_on₃ c₁ cβ‚‚ f $ Ξ» c₁ cβ‚‚ f, by { norm_cast, simp only [add_smul] }, zero_smul := Ξ» f, induction_on f $ Ξ» f, by simp only [← coe_zero, ← coe_smul', zero_smul] } end module instance [has_le Ξ²] : has_le (germ l Ξ²) := ⟨λ f g, quotient.lift_onβ‚‚' f g l.eventually_le $ Ξ» f f' g g' h h', propext $ eventually_le_congr h h'⟩ @[simp] lemma coe_le [has_le Ξ²] : (f : germ l Ξ²) ≀ g ↔ (f ≀ᢠ[l] g) := iff.rfl lemma const_le [has_le Ξ²] {x y : Ξ²} (h : x ≀ y) : (↑x : germ l Ξ²) ≀ ↑y := lift_rel_const h @[simp, norm_cast] lemma const_le_iff [has_le Ξ²] (hl : l β‰  βŠ₯) {x y : Ξ²} : (↑x : germ l Ξ²) ≀ ↑y ↔ x ≀ y := lift_rel_const_iff hl instance [preorder Ξ²] : preorder (germ l Ξ²) := { le := (≀), le_refl := Ξ» f, induction_on f $ eventually_le.refl l, le_trans := Ξ» f₁ fβ‚‚ f₃, induction_on₃ f₁ fβ‚‚ f₃ $ Ξ» f₁ fβ‚‚ f₃, eventually_le.trans } instance [partial_order Ξ²] : partial_order (germ l Ξ²) := { le := (≀), le_antisymm := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g h₁ hβ‚‚, (h₁.antisymm hβ‚‚).germ_eq, .. germ.preorder } instance [has_bot Ξ²] : has_bot (germ l Ξ²) := βŸ¨β†‘(βŠ₯:Ξ²)⟩ @[simp, norm_cast] lemma const_bot [has_bot Ξ²] : (↑(βŠ₯:Ξ²) : germ l Ξ²) = βŠ₯ := rfl instance [order_bot Ξ²] : order_bot (germ l Ξ²) := { bot := βŠ₯, le := (≀), bot_le := Ξ» f, induction_on f $ Ξ» f, eventually_of_forall _ $ Ξ» x, bot_le, .. germ.partial_order } instance [has_top Ξ²] : has_top (germ l Ξ²) := βŸ¨β†‘(⊀:Ξ²)⟩ @[simp, norm_cast] lemma const_top [has_top Ξ²] : (↑(⊀:Ξ²) : germ l Ξ²) = ⊀ := rfl instance [order_top Ξ²] : order_top (germ l Ξ²) := { top := ⊀, le := (≀), le_top := Ξ» f, induction_on f $ Ξ» f, eventually_of_forall _ $ Ξ» x, le_top, .. germ.partial_order } instance [has_sup Ξ²] : has_sup (germ l Ξ²) := ⟨mapβ‚‚ (βŠ”)⟩ @[simp, norm_cast] lemma const_sup [has_sup Ξ²] (a b : Ξ²) : ↑(a βŠ” b) = (↑a βŠ” ↑b : germ l Ξ²) := rfl instance [has_inf Ξ²] : has_inf (germ l Ξ²) := ⟨mapβ‚‚ (βŠ“)⟩ @[simp, norm_cast] lemma const_inf [has_inf Ξ²] (a b : Ξ²) : ↑(a βŠ“ b) = (↑a βŠ“ ↑b : germ l Ξ²) := rfl instance [semilattice_sup Ξ²] : semilattice_sup (germ l Ξ²) := { sup := (βŠ”), le_sup_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall _ $ Ξ» x, le_sup_left, le_sup_right := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall _ $ Ξ» x, le_sup_right, sup_le := Ξ» f₁ fβ‚‚ g, induction_on₃ f₁ fβ‚‚ g $ Ξ» f₁ fβ‚‚ g h₁ hβ‚‚, hβ‚‚.mp $ h₁.mono $ Ξ» x, sup_le, .. germ.partial_order } instance [semilattice_inf Ξ²] : semilattice_inf (germ l Ξ²) := { inf := (βŠ“), inf_le_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall _ $ Ξ» x, inf_le_left, inf_le_right := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g, eventually_of_forall _ $ Ξ» x, inf_le_right, le_inf := Ξ» f₁ fβ‚‚ g, induction_on₃ f₁ fβ‚‚ g $ Ξ» f₁ fβ‚‚ g h₁ hβ‚‚, hβ‚‚.mp $ h₁.mono $ Ξ» x, le_inf, .. germ.partial_order } instance [semilattice_inf_bot Ξ²] : semilattice_inf_bot (germ l Ξ²) := { .. germ.semilattice_inf, .. germ.order_bot } instance [semilattice_sup_bot Ξ²] : semilattice_sup_bot (germ l Ξ²) := { .. germ.semilattice_sup, .. germ.order_bot } instance [semilattice_inf_top Ξ²] : semilattice_inf_top (germ l Ξ²) := { .. germ.semilattice_inf, .. germ.order_top } instance [semilattice_sup_top Ξ²] : semilattice_sup_top (germ l Ξ²) := { .. germ.semilattice_sup, .. germ.order_top } instance [lattice Ξ²] : lattice (germ l Ξ²) := { .. germ.semilattice_sup, .. germ.semilattice_inf } instance [bounded_lattice Ξ²] : bounded_lattice (germ l Ξ²) := { .. germ.lattice, .. germ.order_bot, .. germ.order_top } @[to_additive ordered_cancel_add_comm_monoid] instance [ordered_cancel_comm_monoid Ξ²] : ordered_cancel_comm_monoid (germ l Ξ²) := { mul_le_mul_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g H h, induction_on h $ Ξ» h, H.mono $ Ξ» x H, mul_le_mul_left'' H _, le_of_mul_le_mul_left := Ξ» f g h, induction_on₃ f g h $ Ξ» f g h H, H.mono $ Ξ» x, le_of_mul_le_mul_left', .. germ.partial_order, .. germ.comm_monoid, .. germ.left_cancel_semigroup, .. germ.right_cancel_semigroup } @[to_additive ordered_add_comm_group] instance ordered_comm_group [ordered_comm_group Ξ²] : ordered_comm_group (germ l Ξ²) := { mul_le_mul_left := Ξ» f g, induction_onβ‚‚ f g $ Ξ» f g H h, induction_on h $ Ξ» h, H.mono $ Ξ» x H, mul_le_mul_left'' H _, .. germ.partial_order, .. germ.comm_group } end germ end filter
a0142c98be40c37371711ed3e618a9faf8c4c040
b2e508d02500f1512e1618150413e6be69d9db10
/src/category_theory/opposites.lean
176f9b8d1dd2860c2d97fcf749913ee8976ced48
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
8,155
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.types import category_theory.natural_isomorphism import data.opposite universes v₁ vβ‚‚ u₁ uβ‚‚ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open opposite variables {C : Type u₁} section has_hom variables [π’ž : has_hom.{v₁} C] include π’ž /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cα΅’α΅–. -/ instance has_hom.opposite : has_hom Cα΅’α΅– := { hom := Ξ» X Y, unop Y ⟢ unop X } def has_hom.hom.op {X Y : C} (f : X ⟢ Y) : op Y ⟢ op X := f def has_hom.hom.unop {X Y : Cα΅’α΅–} (f : X ⟢ Y) : unop Y ⟢ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟢ Y) β†’ (op Y ⟢ op X)) := Ξ» _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cα΅’α΅–} : function.injective (has_hom.hom.unop : (X ⟢ Y) β†’ (unop Y ⟢ unop X)) := Ξ» _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟢ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cα΅’α΅–} {f : X ⟢ Y} : f.unop.op = f := rfl end has_hom variables [π’ž : category.{v₁} C] include π’ž instance category.opposite : category.{v₁} Cα΅’α΅– := { comp := Ξ» _ _ _ f g, (g.unop ≫ f.unop).op, id := Ξ» X, (πŸ™ (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟢ Y} {g : Y ⟢ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (πŸ™ X).op = πŸ™ (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cα΅’α΅–} {f : X ⟢ Y} {g : Y ⟢ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cα΅’α΅–} : (πŸ™ X).unop = πŸ™ (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (πŸ™ (op X)).unop = πŸ™ X := rfl @[simp] lemma op_id_unop {X : Cα΅’α΅–} : (πŸ™ (unop X)).op = πŸ™ X := rfl def op_op : (Cα΅’α΅–)α΅’α΅– β₯€ C := { obj := Ξ» X, unop (unop X), map := Ξ» X Y f, f.unop.unop } -- TODO this is an equivalence namespace functor section variables {D : Type uβ‚‚} [π’Ÿ : category.{vβ‚‚} D] include π’Ÿ variables {C D} protected definition op (F : C β₯€ D) : Cα΅’α΅– β₯€ Dα΅’α΅– := { obj := Ξ» X, op (F.obj (unop X)), map := Ξ» X Y f, (F.map f.unop).op } @[simp] lemma op_obj (F : C β₯€ D) (X : Cα΅’α΅–) : (F.op).obj X = op (F.obj (unop X)) := rfl @[simp] lemma op_map (F : C β₯€ D) {X Y : Cα΅’α΅–} (f : X ⟢ Y) : (F.op).map f = (F.map f.unop).op := rfl protected definition unop (F : Cα΅’α΅– β₯€ Dα΅’α΅–) : C β₯€ D := { obj := Ξ» X, unop (F.obj (op X)), map := Ξ» X Y f, (F.map f.op).unop } @[simp] lemma unop_obj (F : Cα΅’α΅– β₯€ Dα΅’α΅–) (X : C) : (F.unop).obj X = unop (F.obj (op X)) := rfl @[simp] lemma unop_map (F : Cα΅’α΅– β₯€ Dα΅’α΅–) {X Y : C} (f : X ⟢ Y) : (F.unop).map f = (F.map f.op).unop := rfl variables (C D) definition op_hom : (C β₯€ D)α΅’α΅– β₯€ (Cα΅’α΅– β₯€ Dα΅’α΅–) := { obj := Ξ» F, (unop F).op, map := Ξ» F G Ξ±, { app := Ξ» X, (Ξ±.unop.app (unop X)).op, naturality' := Ξ» X Y f, has_hom.hom.unop_inj $ eq.symm (Ξ±.unop.naturality f.unop) } } @[simp] lemma op_hom.obj (F : (C β₯€ D)α΅’α΅–) : (op_hom C D).obj F = (unop F).op := rfl @[simp] lemma op_hom.map_app {F G : (C β₯€ D)α΅’α΅–} (Ξ± : F ⟢ G) (X : Cα΅’α΅–) : ((op_hom C D).map Ξ±).app X = (Ξ±.unop.app (unop X)).op := rfl definition op_inv : (Cα΅’α΅– β₯€ Dα΅’α΅–) β₯€ (C β₯€ D)α΅’α΅– := { obj := Ξ» F, op F.unop, map := Ξ» F G Ξ±, has_hom.hom.op { app := Ξ» X, (Ξ±.app (op X)).unop, naturality' := Ξ» X Y f, has_hom.hom.op_inj $ eq.symm (Ξ±.naturality f.op) } } @[simp] lemma op_inv.obj (F : Cα΅’α΅– β₯€ Dα΅’α΅–) : (op_inv C D).obj F = op F.unop := rfl @[simp] lemma op_inv.map_app {F G : Cα΅’α΅– β₯€ Dα΅’α΅–} (Ξ± : F ⟢ G) (X : C) : (((op_inv C D).map Ξ±).unop).app X = (Ξ±.app (op X)).unop := rfl -- TODO show these form an equivalence variables {C D} protected definition left_op (F : C β₯€ Dα΅’α΅–) : Cα΅’α΅– β₯€ D := { obj := Ξ» X, unop (F.obj (unop X)), map := Ξ» X Y f, (F.map f.unop).unop } @[simp] lemma left_op_obj (F : C β₯€ Dα΅’α΅–) (X : Cα΅’α΅–) : (F.left_op).obj X = unop (F.obj (unop X)) := rfl @[simp] lemma left_op_map (F : C β₯€ Dα΅’α΅–) {X Y : Cα΅’α΅–} (f : X ⟢ Y) : (F.left_op).map f = (F.map f.unop).unop := rfl protected definition right_op (F : Cα΅’α΅– β₯€ D) : C β₯€ Dα΅’α΅– := { obj := Ξ» X, op (F.obj (op X)), map := Ξ» X Y f, (F.map f.op).op } @[simp] lemma right_op_obj (F : Cα΅’α΅– β₯€ D) (X : C) : (F.right_op).obj X = op (F.obj (op X)) := rfl @[simp] lemma right_op_map (F : Cα΅’α΅– β₯€ D) {X Y : C} (f : X ⟢ Y) : (F.right_op).map f = (F.map f.op).op := rfl -- TODO show these form an equivalence instance {F : C β₯€ D} [full F] : full F.op := { preimage := Ξ» X Y f, (F.preimage f.unop).op } instance {F : C β₯€ D} [faithful F] : faithful F.op := { injectivity' := Ξ» X Y f g h, has_hom.hom.unop_inj $ by simpa using injectivity F (has_hom.hom.op_inj h) } end section omit π’ž variables (E : Type u₁) [β„° : category.{v₁+1} E] include β„° /-- `functor.hom` is the hom-pairing, sending (X,Y) to X β†’ Y, contravariant in X and covariant in Y. -/ definition hom : Eα΅’α΅– Γ— E β₯€ Type v₁ := { obj := Ξ» p, unop p.1 ⟢ p.2, map := Ξ» X Y f, Ξ» h, f.1.unop ≫ h ≫ f.2 } @[simp] lemma hom_obj (X : Eα΅’α΅– Γ— E) : (functor.hom E).obj X = (unop X.1 ⟢ X.2) := rfl @[simp] lemma hom_pairing_map {X Y : Eα΅’α΅– Γ— E} (f : X ⟢ Y) : (functor.hom E).map f = Ξ» h, f.1.unop ≫ h ≫ f.2 := rfl end end functor namespace nat_trans variables {D : Type uβ‚‚} [π’Ÿ : category.{vβ‚‚} D] include π’Ÿ section variables {F G : C β₯€ D} protected definition op (Ξ± : F ⟢ G) : G.op ⟢ F.op := { app := Ξ» X, (Ξ±.app (unop X)).op, naturality' := begin tidy, erw Ξ±.naturality, refl, end } @[simp] lemma op_app (Ξ± : F ⟢ G) (X) : (nat_trans.op Ξ±).app X = (Ξ±.app (unop X)).op := rfl protected definition unop (Ξ± : F.op ⟢ G.op) : G ⟢ F := { app := Ξ» X, (Ξ±.app (op X)).unop, naturality' := begin tidy, erw Ξ±.naturality, refl, end } @[simp] lemma unop_app (Ξ± : F.op ⟢ G.op) (X) : (nat_trans.unop Ξ±).app X = (Ξ±.app (op X)).unop := rfl end section variables {F G : C β₯€ Dα΅’α΅–} protected definition left_op (Ξ± : F ⟢ G) : G.left_op ⟢ F.left_op := { app := Ξ» X, (Ξ±.app (unop X)).unop, naturality' := begin tidy, erw Ξ±.naturality, refl, end } @[simp] lemma left_op_app (Ξ± : F ⟢ G) (X) : (nat_trans.left_op Ξ±).app X = (Ξ±.app (unop X)).unop := rfl protected definition right_op (Ξ± : F.left_op ⟢ G.left_op) : G ⟢ F := { app := Ξ» X, (Ξ±.app (op X)).op, naturality' := begin tidy, erw Ξ±.naturality, refl, end } @[simp] lemma right_op_app (Ξ± : F.left_op ⟢ G.left_op) (X) : (nat_trans.right_op Ξ±).app X = (Ξ±.app (op X)).op := rfl end end nat_trans namespace iso variables {X Y : C} protected definition op (Ξ± : X β‰… Y) : op Y β‰… op X := { hom := Ξ±.hom.op, inv := Ξ±.inv.op, hom_inv_id' := has_hom.hom.unop_inj Ξ±.inv_hom_id, inv_hom_id' := has_hom.hom.unop_inj Ξ±.hom_inv_id } @[simp] lemma op_hom {Ξ± : X β‰… Y} : Ξ±.op.hom = Ξ±.hom.op := rfl @[simp] lemma op_inv {Ξ± : X β‰… Y} : Ξ±.op.inv = Ξ±.inv.op := rfl end iso namespace nat_iso variables {D : Type uβ‚‚} [π’Ÿ : category.{vβ‚‚} D] include π’Ÿ variables {F G : C β₯€ D} protected definition op (Ξ± : F β‰… G) : G.op β‰… F.op := { hom := nat_trans.op Ξ±.hom, inv := nat_trans.op Ξ±.inv, hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw hom_inv_id_app, refl, end } @[simp] lemma op_hom (Ξ± : F β‰… G) : (nat_iso.op Ξ±).hom = nat_trans.op Ξ±.hom := rfl @[simp] lemma op_inv (Ξ± : F β‰… G) : (nat_iso.op Ξ±).inv = nat_trans.op Ξ±.inv := rfl end nat_iso end category_theory
efc9a80208cc6a8de3c9481c6678d42458b40197
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/stage0/src/Lean/Server/Snapshots.lean
103c4f81aa38fe1dca0243dd12c7e45589db39b7
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
5,040
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.Elab.Import import Lean.Elab.Command /-! One can think of this module as being a partial reimplementation of Lean.Elab.Frontend which also stores a snapshot of the world after each command. Importantly, we allow (re)starting compilation from any snapshot/position in the file for interactive editing purposes. -/ namespace Lean namespace Server namespace Snapshots open Elab /-- What Lean knows about the world after the header and each command. -/ structure Snapshot where /- Where the command which produced this snapshot begins. Note that neighbouring snapshots are *not* necessarily attached beginning-to-end, since inputs outside the grammar advance the parser but do not produce snapshots. -/ beginPos : String.Pos stx : Syntax mpState : Parser.ModuleParserState cmdState : Command.State deriving Inhabited namespace Snapshot def endPos (s : Snapshot) : String.Pos := s.mpState.pos def env (s : Snapshot) : Environment := s.cmdState.env def msgLog (s : Snapshot) : MessageLog := s.cmdState.messages end Snapshot def reparseHeader (contents : String) (header : Snapshot) (opts : Options := {}) : IO Snapshot := do let inputCtx := Parser.mkInputContext contents "<input>" let (_, newHeaderParserState, _) ← Parser.parseHeader inputCtx pure { header with mpState := newHeaderParserState } private def ioErrorFromEmpty (ex : Empty) : IO.Error := nomatch ex /-- Parses the next command occurring after the given snapshot without elaborating it. -/ def parseNextCmd (contents : String) (snap : Snapshot) : IO Syntax := do let inputCtx := Parser.mkInputContext contents "<input>" let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, _, _) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog cmdStx /-- Parse remaining file without elaboration. NOTE that doing so can lead to parse errors or even wrong syntax objects, so it should only be done for reporting preliminary results! -/ partial def parseAhead (contents : String) (snap : Snapshot) : IO (Array Syntax) := do let inputCtx := Parser.mkInputContext contents "<input>" let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } go inputCtx pmctx snap.mpState #[] where go inputCtx pmctx cmdParserState stxs := do let (cmdStx, cmdParserState, _) := Parser.parseCommand inputCtx pmctx cmdParserState snap.msgLog if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then stxs.push cmdStx else go inputCtx pmctx cmdParserState (stxs.push cmdStx) /-- Compiles the next command occurring after the given snapshot. If there is no next command (file ended), returns messages produced through the file. -/ -- NOTE: This code is really very similar to Elab.Frontend. But generalizing it -- over "store snapshots"/"don't store snapshots" would likely result in confusing -- isServer? conditionals and not be worth it due to how short it is. def compileNextCmd (contents : String) (snap : Snapshot) : IO (Sum Snapshot MessageLog) := do let inputCtx := Parser.mkInputContext contents "<input>" let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, cmdParserState, msgLog) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog let cmdPos := cmdStx.getPos?.get! if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then Sum.inr msgLog else let cmdStateRef ← IO.mkRef { snap.cmdState with messages := msgLog } let cmdCtx : Elab.Command.Context := { cmdPos := snap.endPos fileName := inputCtx.fileName fileMap := inputCtx.fileMap } EIO.toIO ioErrorFromEmpty $ Elab.Command.catchExceptions (Elab.Command.elabCommand cmdStx) cmdCtx cmdStateRef let postCmdState ← cmdStateRef.get let postCmdSnap : Snapshot := { beginPos := cmdPos stx := cmdStx mpState := cmdParserState cmdState := postCmdState } Sum.inl postCmdSnap /-- Compiles all commands after the given snapshot. Returns them as a list, together with the final message log. -/ partial def compileCmdsAfter (contents : String) (snap : Snapshot) : IO (List Snapshot Γ— MessageLog) := do let cmdOut ← compileNextCmd contents snap match cmdOut with | Sum.inl snap => let (snaps, msgLog) ← compileCmdsAfter contents snap (snap :: snaps, msgLog) | Sum.inr msgLog => ([], msgLog) end Snapshots end Server end Lean
d27755a90965eba9a1d003b6c018a0b4bb6deaea
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/paracompact.lean
cc09cecc8b3463e2408fcf83115c0143e696726a
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
15,125
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Yury Kudryashov -/ import topology.subset_properties import topology.separation import data.option.basic /-! # Paracompact topological spaces A topological space `X` is said to be paracompact if every open covering of `X` admits a locally finite refinement. The definition requires that each set of the new covering is a subset of one of the sets of the initial covering. However, one can ensure that each open covering `s : ΞΉ β†’ set X` admits a *precise* locally finite refinement, i.e., an open covering `t : ΞΉ β†’ set X` with the same index set such that `βˆ€ i, t i βŠ† s i`, see lemma `precise_refinement`. We also provide a convenience lemma `precise_refinement_set` that deals with open coverings of a closed subset of `X` instead of the whole space. We also prove the following facts. * Every compact space is paracompact, see instance `paracompact_of_compact`. * A locally compact sigma compact Hausdorff space is paracompact, see instance `paracompact_of_locally_compact_sigma_compact`. Moreover, we can choose a locally finite refinement with sets in a given collection of filter bases of `𝓝 x, `x : X`, see `refinement_of_locally_compact_sigma_compact_of_nhds_basis`. For example, in a proper metric space every open covering `⋃ i, s i` admits a refinement `⋃ i, metric.ball (c i) (r i)`. * Every paracompact Hausdorff space is normal. This statement is not an instance to avoid loops in the instance graph. * Every `emetric_space` is a paracompact space, see instance `emetric_space.paracompact_space` in `topology/metric_space/emetric_paracompact`. ## TODO Prove (some of) [Michael's theorems](https://ncatlab.org/nlab/show/Michael%27s+theorem). ## Tags compact space, paracompact space, locally finite covering -/ open set filter function open_locale filter topological_space universes u v /-- A topological space is called paracompact, if every open covering of this space admits a locally finite refinement. We use the same universe for all types in the definition to avoid creating a class like `paracompact_space.{u v}`. Due to lemma `precise_refinement` below, every open covering `s : Ξ± β†’ set X` indexed on `Ξ± : Type v` has a *precise* locally finite refinement, i.e., a locally finite refinement `t : Ξ± β†’ set X` indexed on the same type such that each `βˆ€ i, t i βŠ† s i`. -/ class paracompact_space (X : Type v) [topological_space X] : Prop := (locally_finite_refinement : βˆ€ (Ξ± : Type v) (s : Ξ± β†’ set X) (ho : βˆ€ a, is_open (s a)) (hc : (⋃ a, s a) = univ), βˆƒ (Ξ² : Type v) (t : Ξ² β†’ set X) (ho : βˆ€ b, is_open (t b)) (hc : (⋃ b, t b) = univ), locally_finite t ∧ βˆ€ b, βˆƒ a, t b βŠ† s a) variables {ΞΉ : Type u} {X : Type v} [topological_space X] /-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is, one indexed on the same type with each open set contained in the corresponding original one. -/ lemma precise_refinement [paracompact_space X] (u : ΞΉ β†’ set X) (uo : βˆ€ a, is_open (u a)) (uc : (⋃ i, u i) = univ) : βˆƒ v : ΞΉ β†’ set X, (βˆ€ a, is_open (v a)) ∧ (⋃ i, v i) = univ ∧ locally_finite v ∧ (βˆ€ a, v a βŠ† u a) := begin -- Apply definition to `range u`, then turn existence quantifiers into functions using `choose` have := paracompact_space.locally_finite_refinement (range u) coe (set_coe.forall.2 $ forall_range_iff.2 uo) (by rwa [← sUnion_range, subtype.range_coe]), simp only [set_coe.exists, subtype.coe_mk, exists_range_iff', Union_eq_univ_iff, exists_prop] at this, choose Ξ± t hto hXt htf ind hind, choose t_inv ht_inv using hXt, choose U hxU hU using htf, -- Send each `i` to the union of `t a` over `a ∈ ind ⁻¹' {i}` refine ⟨λ i, ⋃ (a : Ξ±) (ha : ind a = i), t a, _, _, _, _⟩, { exact Ξ» a, is_open_Union (Ξ» a, is_open_Union $ Ξ» ha, hto a) }, { simp only [eq_univ_iff_forall, mem_Union], exact Ξ» x, ⟨ind (t_inv x), _, rfl, ht_inv _⟩ }, { refine Ξ» x, ⟨U x, hxU x, ((hU x).image ind).subset _⟩, simp only [subset_def, mem_Union, mem_set_of_eq, set.nonempty, mem_inter_eq], rintro i ⟨y, ⟨a, rfl, hya⟩, hyU⟩, exact mem_image_of_mem _ ⟨y, hya, hyU⟩ }, { simp only [subset_def, mem_Union], rintro i x ⟨a, rfl, hxa⟩, exact hind _ hxa } end /-- In a paracompact space, every open covering of a closed set admits a locally finite refinement indexed by the same type. -/ lemma precise_refinement_set [paracompact_space X] {s : set X} (hs : is_closed s) (u : ΞΉ β†’ set X) (uo : βˆ€ i, is_open (u i)) (us : s βŠ† ⋃ i, u i) : βˆƒ v : ΞΉ β†’ set X, (βˆ€ i, is_open (v i)) ∧ (s βŠ† ⋃ i, v i) ∧ locally_finite v ∧ (βˆ€ i, v i βŠ† u i) := begin rcases precise_refinement (option.elim sᢜ u) (option.forall.2 ⟨is_open_compl_iff.2 hs, uo⟩) _ with ⟨v, vo, vc, vf, vu⟩, refine ⟨v ∘ some, Ξ» i, vo _, _, vf.comp_injective (option.some_injective _), Ξ» i, vu _⟩, { simp only [Union_option, ← compl_subset_iff_union] at vc, exact subset.trans (subset_compl_comm.1 $ vu option.none) vc }, { simpa only [Union_option, option.elim, ← compl_subset_iff_union, compl_compl] } end /-- A compact space is paracompact. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_compact [compact_space X] : paracompact_space X := begin -- the proof is trivial: we choose a finite subcover using compactness, and use it refine ⟨λ ΞΉ s ho hu, _⟩, rcases compact_univ.elim_finite_subcover _ ho hu.ge with ⟨T, hT⟩, have := hT, simp only [subset_def, mem_Union] at this, choose i hiT hi using Ξ» x, this x (mem_univ x), refine ⟨(T : set ΞΉ), Ξ» t, s t, Ξ» t, ho _, _, locally_finite_of_finite _, Ξ» t, ⟨t, subset.rfl⟩⟩, simpa only [Union_coe_set, ← univ_subset_iff] end /-- Let `X` be a locally compact sigma compact Hausdorff topological space, let `s` be a closed set in `X`. Suppose that for each `x ∈ s` the sets `B x : ΞΉ x β†’ set X` with the predicate `p x : ΞΉ x β†’ Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `Ξ» i, B (c i) (r i)` of `s` such that all β€œcenters” `c i` belong to `s` and each `r i` satisfies `p (c i)`. The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a version of this lemma dealing with a covering of the whole space. In most cases (namely, if `B c r βˆͺ B c r'` is again a set of the form `B c r''`) it is possible to choose `Ξ± = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis_set [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ΞΉ : X β†’ Type u} {p : Ξ  x, ΞΉ x β†’ Prop} {B : Ξ  x, ΞΉ x β†’ set X} {s : set X} (hs : is_closed s) (hB : βˆ€ x ∈ s, (𝓝 x).has_basis (p x) (B x)) : βˆƒ (Ξ± : Type v) (c : Ξ± β†’ X) (r : Ξ  a, ΞΉ (c a)), (βˆ€ a, c a ∈ s ∧ p (c a) (r a)) ∧ (s βŠ† ⋃ a, B (c a) (r a)) ∧ locally_finite (Ξ» a, B (c a) (r a)) := begin classical, -- For technical reasons we prepend two empty sets to the sequence `compact_exhaustion.choice X` set K' : compact_exhaustion X := compact_exhaustion.choice X, set K : compact_exhaustion X := K'.shiftr.shiftr, set Kdiff := Ξ» n, K (n + 1) \ interior (K n), -- Now we restate some properties of `compact_exhaustion` for `K`/`Kdiff` have hKcov : βˆ€ x, x ∈ Kdiff (K'.find x + 1), { intro x, simpa only [K'.find_shiftr] using diff_subset_diff_right interior_subset (K'.shiftr.mem_diff_shiftr_find x) }, have Kdiffc : βˆ€ n, is_compact (Kdiff n ∩ s), from Ξ» n, ((K.is_compact _).diff is_open_interior).inter_right hs, -- Next we choose a finite covering `B (c n i) (r n i)` of each -- `Kdiff (n + 1) ∩ s` such that `B (c n i) (r n i) ∩ s` is disjoint with `K n` have : βˆ€ n (x : Kdiff (n + 1) ∩ s), (K n)ᢜ ∈ 𝓝 (x : X), from Ξ» n x, is_open.mem_nhds (K.is_closed n).is_open_compl (Ξ» hx', x.2.1.2 $ K.subset_interior_succ _ hx'), haveI : βˆ€ n (x : Kdiff n ∩ s), nonempty (ΞΉ x) := Ξ» n x, (hB x x.2.2).nonempty, choose! r hrp hr using (Ξ» n (x : Kdiff (n + 1) ∩ s), (hB x x.2.2).mem_iff.1 (this n x)), have hxr : βˆ€ n x (hx : x ∈ Kdiff (n + 1) ∩ s), B x (r n ⟨x, hx⟩) ∈ 𝓝 x, from Ξ» n x hx, (hB x hx.2).mem_of_mem (hrp _ ⟨x, hx⟩), choose T hT using Ξ» n, (Kdiffc (n + 1)).elim_nhds_subcover' _ (hxr n), set T' : Ξ  n, set β†₯(Kdiff (n + 1) ∩ s) := Ξ» n, T n, -- Finally, we take the union of all these coverings refine ⟨Σ n, T' n, Ξ» a, a.2, Ξ» a, r a.1 a.2, _, _, _⟩, { rintro ⟨n, x, hx⟩, exact ⟨x.2.2, hrp _ _⟩ }, { refine (Ξ» x hx, mem_Union.2 _), rcases mem_Unionβ‚‚.1 (hT _ ⟨hKcov x, hx⟩) with ⟨⟨c, hc⟩, hcT, hcx⟩, exact ⟨⟨_, ⟨c, hc⟩, hcT⟩, hcx⟩ }, { intro x, refine ⟨interior (K (K'.find x + 3)), is_open.mem_nhds is_open_interior (K.subset_interior_succ _ (hKcov x).1), _⟩, have : (⋃ k ≀ K'.find x + 2, (range $ sigma.mk k) : set (Ξ£ n, T' n)).finite, from (finite_le_nat _).bUnion (Ξ» k hk, finite_range _), apply this.subset, rintro ⟨k, c, hc⟩, simp only [mem_Union, mem_set_of_eq, mem_image_eq, subtype.coe_mk], rintro ⟨x, hxB : x ∈ B c (r k c), hxK⟩, refine ⟨k, _, ⟨c, hc⟩, rfl⟩, have := (mem_compl_iff _ _).1 (hr k c hxB), contrapose! this with hnk, exact K.subset hnk (interior_subset hxK) }, end /-- Let `X` be a locally compact sigma compact Hausdorff topological space. Suppose that for each `x` the sets `B x : ΞΉ x β†’ set X` with the predicate `p x : ΞΉ x β†’ Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `Ξ» i, B (c i) (r i)` of `X` such that each `r i` satisfies `p (c i)` The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis_set` for a version of this lemma dealing with a covering of a closed set. In most cases (namely, if `B c r βˆͺ B c r'` is again a set of the form `B c r''`) it is possible to choose `Ξ± = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ΞΉ : X β†’ Type u} {p : Ξ  x, ΞΉ x β†’ Prop} {B : Ξ  x, ΞΉ x β†’ set X} (hB : βˆ€ x, (𝓝 x).has_basis (p x) (B x)) : βˆƒ (Ξ± : Type v) (c : Ξ± β†’ X) (r : Ξ  a, ΞΉ (c a)), (βˆ€ a, p (c a) (r a)) ∧ (⋃ a, B (c a) (r a)) = univ ∧ locally_finite (Ξ» a, B (c a) (r a)) := let ⟨α, c, r, hp, hU, hfin⟩ := refinement_of_locally_compact_sigma_compact_of_nhds_basis_set is_closed_univ (Ξ» x _, hB x) in ⟨α, c, r, Ξ» a, (hp a).2, univ_subset_iff.1 hU, hfin⟩ /-- A locally compact sigma compact Hausdorff space is paracompact. See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a more precise statement. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_locally_compact_sigma_compact [locally_compact_space X] [sigma_compact_space X] [t2_space X] : paracompact_space X := begin refine ⟨λ Ξ± s ho hc, _⟩, choose i hi using Union_eq_univ_iff.1 hc, have : βˆ€ x : X, (𝓝 x).has_basis (Ξ» t : set X, (x ∈ t ∧ is_open t) ∧ t βŠ† s (i x)) id, from Ξ» x : X, (nhds_basis_opens x).restrict_subset (is_open.mem_nhds (ho (i x)) (hi x)), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis this with ⟨β, c, t, hto, htc, htf⟩, exact ⟨β, t, Ξ» x, (hto x).1.2, htc, htf, Ξ» b, ⟨i $ c b, (hto b).2⟩⟩ end /- DieudonnΓ©β€˜s theorem: a paracompact Hausdorff space is normal. Formalization is based on the proof at [ncatlab](https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal). -/ lemma normal_of_paracompact_t2 [t2_space X] [paracompact_space X] : normal_space X := begin /- First we show how to go from points to a set on one side. -/ have : βˆ€ (s t : set X), is_closed s β†’ is_closed t β†’ (βˆ€ x ∈ s, βˆƒ u v, is_open u ∧ is_open v ∧ x ∈ u ∧ t βŠ† v ∧ disjoint u v) β†’ βˆƒ u v, is_open u ∧ is_open v ∧ s βŠ† u ∧ t βŠ† v ∧ disjoint u v, { /- For each `x ∈ s` we choose open disjoint `u x βˆ‹ x` and `v x βŠ‡ t`. The sets `u x` form an open covering of `s`. We choose a locally finite refinement `u' : s β†’ set X`, then `⋃ i, u' i` and `(closure (⋃ i, u' i))ᢜ` are disjoint open neighborhoods of `s` and `t`. -/ intros s t hs ht H, choose u v hu hv hxu htv huv using set_coe.forall'.1 H, rcases precise_refinement_set hs u hu (Ξ» x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu _⟩) with ⟨u', hu'o, hcov', hu'fin, hsub⟩, refine βŸ¨β‹ƒ i, u' i, (closure (⋃ i, u' i))ᢜ, is_open_Union hu'o, is_closed_closure.is_open_compl, hcov', _, disjoint_compl_right.mono le_rfl (compl_le_compl subset_closure)⟩, rw [hu'fin.closure_Union, compl_Union, subset_Inter_iff], refine Ξ» i x hxt hxu, absurd (htv i hxt) (closure_minimal _ (is_closed_compl_iff.2 $ hv _) hxu), exact Ξ» y hyu hyv, huv i ⟨hsub _ hyu, hyv⟩ }, /- Now we apply the lemma twice: first to `s` and `t`, then to `t` and each point of `s`. -/ refine ⟨λ s t hs ht hst, this s t hs ht (Ξ» x hx, _)⟩, rcases this t {x} ht is_closed_singleton (Ξ» y hy, _) with ⟨v, u, hv, hu, htv, hxu, huv⟩, { exact ⟨u, v, hu, hv, singleton_subset_iff.1 hxu, htv, huv.symm⟩ }, { simp_rw singleton_subset_iff, exact t2_separation (hst.symm.ne_of_mem hy hx) } end
0d344f884e8c49bf490d7d6cea48ccb6728118f7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/basic.lean
2fad21eb8ee7e973d3ebaa2ca475122e2f265e82
[ "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
30,970
lean
/- Copyright (c) 2019 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.module.equiv import data.bracket import linear_algebra.basic import tactic.noncomm_ring /-! # Lie algebras This file defines Lie rings and Lie algebras over a commutative ring together with their modules, morphisms and equivalences, as well as various lemmas to make these definitions usable. ## Main definitions * `lie_ring` * `lie_algebra` * `lie_ring_module` * `lie_module` * `lie_hom` * `lie_equiv` * `lie_module_hom` * `lie_module_equiv` ## Notation Working over a fixed commutative ring `R`, we introduce the notations: * `L →ₗ⁅R⁆ L'` for a morphism of Lie algebras, * `L ≃ₗ⁅R⁆ L'` for an equivalence of Lie algebras, * `M →ₗ⁅R,L⁆ N` for a morphism of Lie algebra modules `M`, `N` over a Lie algebra `L`, * `M ≃ₗ⁅R,L⁆ N` for an equivalence of Lie algebra modules `M`, `N` over a Lie algebra `L`. ## Implementation notes Lie algebras are defined as modules with a compatible Lie ring structure and thus, like modules, are partially unbundled. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*](bourbaki1975) ## Tags lie bracket, jacobi identity, lie ring, lie algebra, lie module -/ universes u v w w₁ wβ‚‚ open function /-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the Jacobi identity. -/ @[protect_proj] class lie_ring (L : Type v) extends add_comm_group L, has_bracket L L := (add_lie : βˆ€ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆) (lie_add : βˆ€ (x y z : L), ⁅x, y + z⁆ = ⁅x, y⁆ + ⁅x, z⁆) (lie_self : βˆ€ (x : L), ⁅x, x⁆ = 0) (leibniz_lie : βˆ€ (x y z : L), ⁅x, ⁅y, z⁆⁆ = ⁅⁅x, y⁆, z⁆ + ⁅y, ⁅x, z⁆⁆) /-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/ @[protect_proj] class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] extends module R L := (lie_smul : βˆ€ (t : R) (x y : L), ⁅x, t β€’ y⁆ = t β€’ ⁅x, y⁆) /-- A Lie ring module is an additive group, together with an additive action of a Lie ring on this group, such that the Lie bracket acts as the commutator of endomorphisms. (For representations of Lie *algebras* see `lie_module`.) -/ @[protect_proj] class lie_ring_module (L : Type v) (M : Type w) [lie_ring L] [add_comm_group M] extends has_bracket L M := (add_lie : βˆ€ (x y : L) (m : M), ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆) (lie_add : βˆ€ (x : L) (m n : M), ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆) (leibniz_lie : βˆ€ (x y : L) (m : M), ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆) /-- A Lie module is a module over a commutative ring, together with a linear action of a Lie algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/ @[protect_proj] class lie_module (R : Type u) (L : Type v) (M : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] [lie_ring_module L M] := (smul_lie : βˆ€ (t : R) (x : L) (m : M), ⁅t β€’ x, m⁆ = t β€’ ⁅x, m⁆) (lie_smul : βˆ€ (t : R) (x : L) (m : M), ⁅x, t β€’ m⁆ = t β€’ ⁅x, m⁆) section basic_properties variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] variables (t : R) (x y z : L) (m n : M) @[simp] lemma add_lie : ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆ := lie_ring_module.add_lie x y m @[simp] lemma lie_add : ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆ := lie_ring_module.lie_add x m n @[simp] lemma smul_lie : ⁅t β€’ x, m⁆ = t β€’ ⁅x, m⁆ := lie_module.smul_lie t x m @[simp] lemma lie_smul : ⁅x, t β€’ m⁆ = t β€’ ⁅x, m⁆ := lie_module.lie_smul t x m lemma leibniz_lie : ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆ := lie_ring_module.leibniz_lie x y m @[simp] lemma lie_zero : ⁅x, 0⁆ = (0 : M) := (add_monoid_hom.mk' _ (lie_add x)).map_zero @[simp] lemma zero_lie : ⁅(0 : L), m⁆ = 0 := (add_monoid_hom.mk' (Ξ» (x : L), ⁅x, m⁆) (Ξ» x y, add_lie x y m)).map_zero @[simp] lemma lie_self : ⁅x, x⁆ = 0 := lie_ring.lie_self x instance lie_ring_self_module : lie_ring_module L L := { ..(infer_instance : lie_ring L) } @[simp] lemma lie_skew : -⁅y, x⁆ = ⁅x, y⁆ := have h : ⁅x + y, x⁆ + ⁅x + y, y⁆ = 0, { rw ← lie_add, apply lie_self, }, by simpa [neg_eq_iff_add_eq_zero] using h /-- Every Lie algebra is a module over itself. -/ instance lie_algebra_self_module : lie_module R L L := { smul_lie := Ξ» t x m, by rw [←lie_skew, ←lie_skew x m, lie_algebra.lie_smul, smul_neg], lie_smul := by apply lie_algebra.lie_smul, } @[simp] lemma neg_lie : ⁅-x, m⁆ = -⁅x, m⁆ := by { rw [←sub_eq_zero, sub_neg_eq_add, ←add_lie], simp, } @[simp] lemma lie_neg : ⁅x, -m⁆ = -⁅x, m⁆ := by { rw [←sub_eq_zero, sub_neg_eq_add, ←lie_add], simp, } @[simp] lemma sub_lie : ⁅x - y, m⁆ = ⁅x, m⁆ - ⁅y, m⁆ := by simp [sub_eq_add_neg] @[simp] lemma lie_sub : ⁅x, m - n⁆ = ⁅x, m⁆ - ⁅x, n⁆ := by simp [sub_eq_add_neg] @[simp] lemma nsmul_lie (n : β„•) : ⁅n β€’ x, m⁆ = n β€’ ⁅x, m⁆ := add_monoid_hom.map_nsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, Ξ» _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_nsmul (n : β„•) : ⁅x, n β€’ m⁆ = n β€’ ⁅x, m⁆ := add_monoid_hom.map_nsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, Ξ» _ _, lie_add _ _ _⟩ _ _ @[simp] lemma zsmul_lie (a : β„€) : ⁅a β€’ x, m⁆ = a β€’ ⁅x, m⁆ := add_monoid_hom.map_zsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, Ξ» _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_zsmul (a : β„€) : ⁅x, a β€’ m⁆ = a β€’ ⁅x, m⁆ := add_monoid_hom.map_zsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, Ξ» _ _, lie_add _ _ _⟩ _ _ @[simp] lemma lie_lie : ⁅⁅x, y⁆, m⁆ = ⁅x, ⁅y, m⁆⁆ - ⁅y, ⁅x, m⁆⁆ := by rw [leibniz_lie, add_sub_cancel] lemma lie_jacobi : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 := by { rw [← neg_neg ⁅x, y⁆, lie_neg z, lie_skew y x, ← lie_skew, lie_lie], abel, } instance lie_ring.int_lie_algebra : lie_algebra β„€ L := { lie_smul := Ξ» n x y, lie_zsmul x y n, } instance : lie_ring_module L (M β†’β‚—[R] N) := { bracket := Ξ» x f, { to_fun := Ξ» m, ⁅x, f m⁆ - f ⁅x, m⁆, map_add' := Ξ» m n, by { simp only [lie_add, linear_map.map_add], abel, }, map_smul' := Ξ» t m, by simp only [smul_sub, linear_map.map_smul, lie_smul, ring_hom.id_apply] }, add_lie := Ξ» x y f, by { ext n, simp only [add_lie, linear_map.coe_mk, linear_map.add_apply, linear_map.map_add], abel, }, lie_add := Ξ» x f g, by { ext n, simp only [linear_map.coe_mk, lie_add, linear_map.add_apply], abel, }, leibniz_lie := Ξ» x y f, by { ext n, simp only [lie_lie, linear_map.coe_mk, linear_map.map_sub, linear_map.add_apply, lie_sub], abel, }, } @[simp] lemma lie_hom.lie_apply (f : M β†’β‚—[R] N) (x : L) (m : M) : ⁅x, f⁆ m = ⁅x, f m⁆ - f ⁅x, m⁆ := rfl instance : lie_module R L (M β†’β‚—[R] N) := { smul_lie := Ξ» t x f, by { ext n, simp only [smul_sub, smul_lie, linear_map.smul_apply, lie_hom.lie_apply, linear_map.map_smul], }, lie_smul := Ξ» t x f, by { ext n, simp only [smul_sub, linear_map.smul_apply, lie_hom.lie_apply, lie_smul], }, } end basic_properties /-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/ structure lie_hom (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L β†’β‚—[R] L' := (map_lie' : βˆ€ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆) attribute [nolint doc_blame] lie_hom.to_linear_map notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := lie_hom R L L' namespace lie_hom variables {R : Type u} {L₁ : Type v} {Lβ‚‚ : Type w} {L₃ : Type w₁} variables [comm_ring R] variables [lie_ring L₁] [lie_algebra R L₁] variables [lie_ring Lβ‚‚] [lie_algebra R Lβ‚‚] variables [lie_ring L₃] [lie_algebra R L₃] instance : has_coe (L₁ →ₗ⁅R⁆ Lβ‚‚) (L₁ β†’β‚—[R] Lβ‚‚) := ⟨lie_hom.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ →ₗ⁅R⁆ Lβ‚‚) (Ξ» _, L₁ β†’ Lβ‚‚) := ⟨λ f, f.to_linear_map.to_fun⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚ := h initialize_simps_projections lie_hom (to_linear_map_to_fun β†’ apply) @[simp, norm_cast] lemma coe_to_linear_map (f : L₁ →ₗ⁅R⁆ Lβ‚‚) : ((f : L₁ β†’β‚—[R] Lβ‚‚) : L₁ β†’ Lβ‚‚) = f := rfl @[simp] lemma to_fun_eq_coe (f : L₁ →ₗ⁅R⁆ Lβ‚‚) : f.to_fun = ⇑f := rfl @[simp] lemma map_smul (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (c : R) (x : L₁) : f (c β€’ x) = c β€’ f x := linear_map.map_smul (f : L₁ β†’β‚—[R] Lβ‚‚) c x @[simp] lemma map_add (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (x y : L₁) : f (x + y) = (f x) + (f y) := linear_map.map_add (f : L₁ β†’β‚—[R] Lβ‚‚) x y @[simp] lemma map_sub (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (x y : L₁) : f (x - y) = (f x) - (f y) := linear_map.map_sub (f : L₁ β†’β‚—[R] Lβ‚‚) x y @[simp] lemma map_neg (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (x : L₁) : f (-x) = -(f x) := linear_map.map_neg (f : L₁ β†’β‚—[R] Lβ‚‚) x @[simp] lemma map_lie (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (x y : L₁) : f ⁅x, y⁆ = ⁅f x, f y⁆ := lie_hom.map_lie' f @[simp] lemma map_zero (f : L₁ →ₗ⁅R⁆ Lβ‚‚) : f 0 = 0 := (f : L₁ β†’β‚—[R] Lβ‚‚).map_zero /-- The identity map is a morphism of Lie algebras. -/ def id : L₁ →ₗ⁅R⁆ L₁ := { map_lie' := Ξ» x y, rfl, .. (linear_map.id : L₁ β†’β‚—[R] L₁) } @[simp] lemma coe_id : ((id : L₁ →ₗ⁅R⁆ L₁) : L₁ β†’ L₁) = _root_.id := rfl lemma id_apply (x : L₁) : (id : L₁ →ₗ⁅R⁆ L₁) x = x := rfl /-- The constant 0 map is a Lie algebra morphism. -/ instance : has_zero (L₁ →ₗ⁅R⁆ Lβ‚‚) := ⟨{ map_lie' := by simp, ..(0 : L₁ β†’β‚—[R] Lβ‚‚)}⟩ @[norm_cast, simp] lemma coe_zero : ((0 : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚) = 0 := rfl lemma zero_apply (x : L₁) : (0 : L₁ →ₗ⁅R⁆ Lβ‚‚) x = 0 := rfl /-- The identity map is a Lie algebra morphism. -/ instance : has_one (L₁ →ₗ⁅R⁆ L₁) := ⟨id⟩ @[simp] lemma coe_one : ((1 : (L₁ →ₗ⁅R⁆ L₁)) : L₁ β†’ L₁) = _root_.id := rfl lemma one_apply (x : L₁) : (1 : (L₁ →ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ →ₗ⁅R⁆ Lβ‚‚) := ⟨0⟩ lemma coe_injective : @function.injective (L₁ →ₗ⁅R⁆ Lβ‚‚) (L₁ β†’ Lβ‚‚) coe_fn := by rintro ⟨⟨f, _⟩⟩ ⟨⟨g, _⟩⟩ ⟨h⟩; congr @[ext] lemma ext {f g : L₁ →ₗ⁅R⁆ Lβ‚‚} (h : βˆ€ x, f x = g x) : f = g := coe_injective $ funext h lemma ext_iff {f g : L₁ →ₗ⁅R⁆ Lβ‚‚} : f = g ↔ βˆ€ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ lemma congr_fun {f g : L₁ →ₗ⁅R⁆ Lβ‚‚} (h : f = g) (x : L₁) : f x = g x := h β–Έ rfl @[simp] lemma mk_coe (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (h₁ hβ‚‚ h₃) : (⟨⟨f, h₁, hβ‚‚βŸ©, hβ‚ƒβŸ© : L₁ →ₗ⁅R⁆ Lβ‚‚) = f := by { ext, refl, } @[simp] lemma coe_mk (f : L₁ β†’ Lβ‚‚) (h₁ hβ‚‚ h₃) : ((⟨⟨f, h₁, hβ‚‚βŸ©, hβ‚ƒβŸ© : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚) = f := rfl /-- The composition of morphisms is a morphism. -/ def comp (f : Lβ‚‚ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ →ₗ⁅R⁆ L₃ := { map_lie' := Ξ» x y, by { change f (g ⁅x, y⁆) = ⁅f (g x), f (g y)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma comp_apply (f : Lβ‚‚ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ Lβ‚‚) (x : L₁) : f.comp g x = f (g x) := rfl @[norm_cast, simp] lemma coe_comp (f : Lβ‚‚ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ Lβ‚‚) : (f.comp g : L₁ β†’ L₃) = f ∘ g := rfl @[norm_cast, simp] lemma coe_linear_map_comp (f : Lβ‚‚ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ Lβ‚‚) : (f.comp g : L₁ β†’β‚—[R] L₃) = (f : Lβ‚‚ β†’β‚—[R] L₃).comp (g : L₁ β†’β‚—[R] Lβ‚‚) := rfl @[simp] lemma comp_id (f : L₁ →ₗ⁅R⁆ Lβ‚‚) : f.comp (id : L₁ →ₗ⁅R⁆ L₁) = f := by { ext, refl, } @[simp] lemma id_comp (f : L₁ →ₗ⁅R⁆ Lβ‚‚) : (id : Lβ‚‚ →ₗ⁅R⁆ Lβ‚‚).comp f = f := by { ext, refl, } /-- The inverse of a bijective morphism is a morphism. -/ def inverse (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (g : Lβ‚‚ β†’ L₁) (h₁ : function.left_inverse g f) (hβ‚‚ : function.right_inverse g f) : Lβ‚‚ →ₗ⁅R⁆ L₁ := { map_lie' := Ξ» x y, calc g ⁅x, y⁆ = g ⁅f (g x), f (g y)⁆ : by { conv_lhs { rw [←hβ‚‚ x, ←hβ‚‚ y], }, } ... = g (f ⁅g x, g y⁆) : by rw map_lie ... = ⁅g x, g y⁆ : (h₁ _), ..linear_map.inverse f.to_linear_map g h₁ hβ‚‚ } end lie_hom section module_pull_back variables {R : Type u} {L₁ : Type v} {Lβ‚‚ : Type w} (M : Type w₁) variables [comm_ring R] [lie_ring L₁] [lie_algebra R L₁] [lie_ring Lβ‚‚] [lie_algebra R Lβ‚‚] variables [add_comm_group M] [lie_ring_module Lβ‚‚ M] variables (f : L₁ →ₗ⁅R⁆ Lβ‚‚) include f /-- A Lie ring module may be pulled back along a morphism of Lie algebras. See note [reducible non-instances]. -/ @[reducible] def lie_ring_module.comp_lie_hom : lie_ring_module L₁ M := { bracket := Ξ» x m, ⁅f x, m⁆, lie_add := Ξ» x, lie_add (f x), add_lie := Ξ» x y m, by simp only [lie_hom.map_add, add_lie], leibniz_lie := Ξ» x y m, by simp only [lie_lie, sub_add_cancel, lie_hom.map_lie], } lemma lie_ring_module.comp_lie_hom_apply (x : L₁) (m : M) : by haveI := lie_ring_module.comp_lie_hom M f; exact ⁅x, m⁆ = ⁅f x, m⁆ := rfl /-- A Lie module may be pulled back along a morphism of Lie algebras. See note [reducible non-instances]. -/ @[reducible] def lie_module.comp_lie_hom [module R M] [lie_module R Lβ‚‚ M] : @lie_module R L₁ M _ _ _ _ _ (lie_ring_module.comp_lie_hom M f) := { smul_lie := Ξ» t x m, by simp only [smul_lie, lie_hom.map_smul], lie_smul := Ξ» t x m, by simp only [lie_smul], } end module_pull_back /-- An equivalence of Lie algebras is a morphism which is also a linear equivalence. We could instead define an equivalence to be a morphism which is also a (plain) equivalence. However it is more convenient to define via linear equivalence to get `.to_linear_equiv` for free. -/ structure lie_equiv (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ⁅R⁆ L' := (inv_fun : L' β†’ L) (left_inv : function.left_inverse inv_fun to_lie_hom.to_fun) (right_inv : function.right_inverse inv_fun to_lie_hom.to_fun) attribute [nolint doc_blame] lie_equiv.to_lie_hom notation L ` ≃ₗ⁅`:50 R `⁆ ` L' := lie_equiv R L L' namespace lie_equiv variables {R : Type u} {L₁ : Type v} {Lβ‚‚ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring Lβ‚‚] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R Lβ‚‚] [lie_algebra R L₃] /-- Consider an equivalence of Lie algebras as a linear equivalence. -/ def to_linear_equiv (f : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : L₁ ≃ₗ[R] Lβ‚‚ := { ..f.to_lie_hom, ..f } instance has_coe_to_lie_hom : has_coe (L₁ ≃ₗ⁅R⁆ Lβ‚‚) (L₁ →ₗ⁅R⁆ Lβ‚‚) := ⟨to_lie_hom⟩ instance has_coe_to_linear_equiv : has_coe (L₁ ≃ₗ⁅R⁆ Lβ‚‚) (L₁ ≃ₗ[R] Lβ‚‚) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ ≃ₗ⁅R⁆ Lβ‚‚) (Ξ» _, L₁ β†’ Lβ‚‚) := ⟨λ e, e.to_lie_hom.to_fun⟩ @[simp, norm_cast] lemma coe_to_lie_hom (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : ((e : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : ((e : L₁ ≃ₗ[R] Lβ‚‚) : L₁ β†’ Lβ‚‚) = e := rfl @[simp] lemma to_linear_equiv_mk (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (g h₁ hβ‚‚) : (mk f g h₁ hβ‚‚ : L₁ ≃ₗ[R] Lβ‚‚) = { inv_fun := g, left_inv := h₁, right_inv := hβ‚‚, .. f } := rfl lemma coe_linear_equiv_injective : injective (coe : (L₁ ≃ₗ⁅R⁆ Lβ‚‚) β†’ (L₁ ≃ₗ[R] Lβ‚‚)) := begin intros f₁ fβ‚‚ h, cases f₁, cases fβ‚‚, dsimp at h, simp only at h, congr, exacts [lie_hom.coe_injective h.1, h.2] end lemma coe_injective : @injective (L₁ ≃ₗ⁅R⁆ Lβ‚‚) (L₁ β†’ Lβ‚‚) coe_fn := linear_equiv.coe_injective.comp coe_linear_equiv_injective @[ext] lemma ext {f g : L₁ ≃ₗ⁅R⁆ Lβ‚‚} (h : βˆ€ x, f x = g x) : f = g := coe_injective $ funext h instance : has_one (L₁ ≃ₗ⁅R⁆ L₁) := ⟨{ map_lie' := Ξ» x y, rfl, ..(1 : L₁ ≃ₗ[R] L₁)}⟩ @[simp] lemma one_apply (x : L₁) : (1 : (L₁ ≃ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ ≃ₗ⁅R⁆ L₁) := ⟨1⟩ /-- Lie algebra equivalences are reflexive. -/ @[refl] def refl : L₁ ≃ₗ⁅R⁆ L₁ := 1 @[simp] lemma refl_apply (x : L₁) : (refl : L₁ ≃ₗ⁅R⁆ L₁) x = x := rfl /-- Lie algebra equivalences are symmetric. -/ @[symm] def symm (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : Lβ‚‚ ≃ₗ⁅R⁆ L₁ := { ..lie_hom.inverse e.to_lie_hom e.inv_fun e.left_inv e.right_inv, ..e.to_linear_equiv.symm } @[simp] lemma symm_symm (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : e.symm.symm = e := by { ext, refl } @[simp] lemma apply_symm_apply (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : βˆ€ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : βˆ€ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply @[simp] theorem refl_symm : (refl : L₁ ≃ₗ⁅R⁆ L₁).symm = refl := rfl /-- Lie algebra equivalences are transitive. -/ @[trans] def trans (e₁ : L₁ ≃ₗ⁅R⁆ Lβ‚‚) (eβ‚‚ : Lβ‚‚ ≃ₗ⁅R⁆ L₃) : L₁ ≃ₗ⁅R⁆ L₃ := { ..lie_hom.comp eβ‚‚.to_lie_hom e₁.to_lie_hom, ..linear_equiv.trans e₁.to_linear_equiv eβ‚‚.to_linear_equiv } @[simp] lemma self_trans_symm (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : e.trans e.symm = refl := ext e.symm_apply_apply @[simp] lemma symm_trans_self (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : e.symm.trans e = refl := e.symm.self_trans_symm @[simp] lemma trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ Lβ‚‚) (eβ‚‚ : Lβ‚‚ ≃ₗ⁅R⁆ L₃) (x : L₁) : (e₁.trans eβ‚‚) x = eβ‚‚ (e₁ x) := rfl @[simp] lemma symm_trans (e₁ : L₁ ≃ₗ⁅R⁆ Lβ‚‚) (eβ‚‚ : Lβ‚‚ ≃ₗ⁅R⁆ L₃) : (e₁.trans eβ‚‚).symm = eβ‚‚.symm.trans e₁.symm := rfl protected lemma bijective (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : function.bijective ((e : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚) := e.to_linear_equiv.bijective protected lemma injective (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : function.injective ((e : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚) := e.to_linear_equiv.injective protected lemma surjective (e : L₁ ≃ₗ⁅R⁆ Lβ‚‚) : function.surjective ((e : L₁ →ₗ⁅R⁆ Lβ‚‚) : L₁ β†’ Lβ‚‚) := e.to_linear_equiv.surjective /-- A bijective morphism of Lie algebras yields an equivalence of Lie algebras. -/ @[simps] noncomputable def of_bijective (f : L₁ →ₗ⁅R⁆ Lβ‚‚) (h₁ : function.injective f) (hβ‚‚ : function.surjective f) : L₁ ≃ₗ⁅R⁆ Lβ‚‚ := { to_fun := f, map_lie' := f.map_lie, .. (linear_equiv.of_bijective (f : L₁ β†’β‚—[R] Lβ‚‚) h₁ hβ‚‚), } end lie_equiv section lie_module_morphisms variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) (P : Type wβ‚‚) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [add_comm_group N] [add_comm_group P] variables [module R M] [module R N] [module R P] variables [lie_ring_module L M] [lie_ring_module L N] [lie_ring_module L P] variables [lie_module R L M] [lie_module R L N] [lie_module R L P] /-- A morphism of Lie algebra modules is a linear map which commutes with the action of the Lie algebra. -/ structure lie_module_hom extends M β†’β‚—[R] N := (map_lie' : βˆ€ {x : L} {m : M}, to_fun ⁅x, m⁆ = ⁅x, to_fun m⁆) attribute [nolint doc_blame] lie_module_hom.to_linear_map notation M ` →ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_hom R L M N namespace lie_module_hom variables {R L M N P} instance : has_coe (M →ₗ⁅R,L⁆ N) (M β†’β‚—[R] N) := ⟨lie_module_hom.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (M →ₗ⁅R,L⁆ N) (Ξ» _, M β†’ N) := ⟨λ f, f.to_linear_map.to_fun⟩ @[simp, norm_cast] lemma coe_to_linear_map (f : M →ₗ⁅R,L⁆ N) : ((f : M β†’β‚—[R] N) : M β†’ N) = f := rfl @[simp] lemma map_smul (f : M →ₗ⁅R,L⁆ N) (c : R) (x : M) : f (c β€’ x) = c β€’ f x := linear_map.map_smul (f : M β†’β‚—[R] N) c x @[simp] lemma map_add (f : M →ₗ⁅R,L⁆ N) (x y : M) : f (x + y) = (f x) + (f y) := linear_map.map_add (f : M β†’β‚—[R] N) x y @[simp] lemma map_sub (f : M →ₗ⁅R,L⁆ N) (x y : M) : f (x - y) = (f x) - (f y) := linear_map.map_sub (f : M β†’β‚—[R] N) x y @[simp] lemma map_neg (f : M →ₗ⁅R,L⁆ N) (x : M) : f (-x) = -(f x) := linear_map.map_neg (f : M β†’β‚—[R] N) x @[simp] lemma map_lie (f : M →ₗ⁅R,L⁆ N) (x : L) (m : M) : f ⁅x, m⁆ = ⁅x, f m⁆ := lie_module_hom.map_lie' f lemma map_lieβ‚‚ (f : M →ₗ⁅R,L⁆ N β†’β‚—[R] P) (x : L) (m : M) (n : N) : ⁅x, f m n⁆ = f ⁅x, m⁆ n + f m ⁅x, n⁆ := by simp only [sub_add_cancel, map_lie, lie_hom.lie_apply] @[simp] lemma map_zero (f : M →ₗ⁅R,L⁆ N) : f 0 = 0 := linear_map.map_zero (f : M β†’β‚—[R] N) /-- The identity map is a morphism of Lie modules. -/ def id : M →ₗ⁅R,L⁆ M := { map_lie' := Ξ» x m, rfl, .. (linear_map.id : M β†’β‚—[R] M) } @[simp] lemma coe_id : ((id : M →ₗ⁅R,L⁆ M) : M β†’ M) = _root_.id := rfl lemma id_apply (x : M) : (id : M →ₗ⁅R,L⁆ M) x = x := rfl /-- The constant 0 map is a Lie module morphism. -/ instance : has_zero (M →ₗ⁅R,L⁆ N) := ⟨{ map_lie' := by simp, ..(0 : M β†’β‚—[R] N) }⟩ @[norm_cast, simp] lemma coe_zero : ((0 : M →ₗ⁅R,L⁆ N) : M β†’ N) = 0 := rfl lemma zero_apply (m : M) : (0 : M →ₗ⁅R,L⁆ N) m = 0 := rfl /-- The identity map is a Lie module morphism. -/ instance : has_one (M →ₗ⁅R,L⁆ M) := ⟨id⟩ instance : inhabited (M →ₗ⁅R,L⁆ N) := ⟨0⟩ lemma coe_injective : @function.injective (M →ₗ⁅R,L⁆ N) (M β†’ N) coe_fn := by { rintros ⟨⟨f, _⟩⟩ ⟨⟨g, _⟩⟩ ⟨h⟩, congr, } @[ext] lemma ext {f g : M →ₗ⁅R,L⁆ N} (h : βˆ€ m, f m = g m) : f = g := coe_injective $ funext h lemma ext_iff {f g : M →ₗ⁅R,L⁆ N} : f = g ↔ βˆ€ m, f m = g m := ⟨by { rintro rfl m, refl, }, ext⟩ lemma congr_fun {f g : M →ₗ⁅R,L⁆ N} (h : f = g) (x : M) : f x = g x := h β–Έ rfl @[simp] lemma mk_coe (f : M →ₗ⁅R,L⁆ N) (h) : (⟨f, h⟩ : M →ₗ⁅R,L⁆ N) = f := by { ext, refl, } @[simp] lemma coe_mk (f : M β†’β‚—[R] N) (h) : ((⟨f, h⟩ : M →ₗ⁅R,L⁆ N) : M β†’ N) = f := by { ext, refl, } @[norm_cast, simp] lemma coe_linear_mk (f : M β†’β‚—[R] N) (h) : ((⟨f, h⟩ : M →ₗ⁅R,L⁆ N) : M β†’β‚—[R] N) = f := by { ext, refl, } /-- The composition of Lie module morphisms is a morphism. -/ def comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : M →ₗ⁅R,L⁆ P := { map_lie' := Ξ» x m, by { change f (g ⁅x, m⁆) = ⁅x, f (g m)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma comp_apply (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) (m : M) : f.comp g m = f (g m) := rfl @[norm_cast, simp] lemma coe_comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : (f.comp g : M β†’ P) = f ∘ g := rfl @[norm_cast, simp] lemma coe_linear_map_comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : (f.comp g : M β†’β‚—[R] P) = (f : N β†’β‚—[R] P).comp (g : M β†’β‚—[R] N) := rfl /-- The inverse of a bijective morphism of Lie modules is a morphism of Lie modules. -/ def inverse (f : M →ₗ⁅R,L⁆ N) (g : N β†’ M) (h₁ : function.left_inverse g f) (hβ‚‚ : function.right_inverse g f) : N →ₗ⁅R,L⁆ M := { map_lie' := Ξ» x n, calc g ⁅x, n⁆ = g ⁅x, f (g n)⁆ : by rw hβ‚‚ ... = g (f ⁅x, g n⁆) : by rw map_lie ... = ⁅x, g n⁆ : (h₁ _), ..linear_map.inverse f.to_linear_map g h₁ hβ‚‚ } instance : has_add (M →ₗ⁅R,L⁆ N) := { add := Ξ» f g, { map_lie' := by simp, ..((f : M β†’β‚—[R] N) + (g : M β†’β‚—[R] N)) }, } instance : has_sub (M →ₗ⁅R,L⁆ N) := { sub := Ξ» f g, { map_lie' := by simp, ..((f : M β†’β‚—[R] N) - (g : M β†’β‚—[R] N)) }, } instance : has_neg (M →ₗ⁅R,L⁆ N) := { neg := Ξ» f, { map_lie' := by simp, ..(-(f : (M β†’β‚—[R] N))) }, } @[norm_cast, simp] lemma coe_add (f g : M →ₗ⁅R,L⁆ N) : ⇑(f + g) = f + g := rfl lemma add_apply (f g : M →ₗ⁅R,L⁆ N) (m : M) : (f + g) m = f m + g m := rfl @[norm_cast, simp] lemma coe_sub (f g : M →ₗ⁅R,L⁆ N) : ⇑(f - g) = f - g := rfl lemma sub_apply (f g : M →ₗ⁅R,L⁆ N) (m : M) : (f - g) m = f m - g m := rfl @[norm_cast, simp] lemma coe_neg (f : M →ₗ⁅R,L⁆ N) : ⇑(-f) = -f := rfl lemma neg_apply (f : M →ₗ⁅R,L⁆ N) (m : M) : (-f) m = -(f m) := rfl instance has_nsmul : has_smul β„• (M →ₗ⁅R,L⁆ N) := { smul := Ξ» n f, { map_lie' := Ξ» x m, by simp, ..(n β€’ (f : M β†’β‚—[R] N)) } } @[norm_cast, simp] lemma coe_nsmul (n : β„•) (f : M →ₗ⁅R,L⁆ N) : ⇑(n β€’ f) = n β€’ f := rfl lemma nsmul_apply (n : β„•) (f : M →ₗ⁅R,L⁆ N) (m : M) : (n β€’ f) m = n β€’ f m := rfl instance has_zsmul : has_smul β„€ (M →ₗ⁅R,L⁆ N) := { smul := Ξ» z f, { map_lie' := Ξ» x m, by simp, ..(z β€’ (f : M β†’β‚—[R] N)) } } @[norm_cast, simp] lemma coe_zsmul (z : β„€) (f : M →ₗ⁅R,L⁆ N) : ⇑(z β€’ f) = z β€’ f := rfl lemma zsmul_apply (z : β„€) (f : M →ₗ⁅R,L⁆ N) (m : M) : (z β€’ f) m = z β€’ f m := rfl instance : add_comm_group (M →ₗ⁅R,L⁆ N) := coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (Ξ» _ _, coe_nsmul _ _) (Ξ» _ _, coe_zsmul _ _) instance : has_smul R (M →ₗ⁅R,L⁆ N) := { smul := Ξ» t f, { map_lie' := by simp, ..(t β€’ (f : M β†’β‚—[R] N)) }, } @[norm_cast, simp] lemma coe_smul (t : R) (f : M →ₗ⁅R,L⁆ N) : ⇑(t β€’ f) = t β€’ f := rfl lemma smul_apply (t : R) (f : M →ₗ⁅R,L⁆ N) (m : M) : (t β€’ f) m = t β€’ (f m) := rfl instance : module R (M →ₗ⁅R,L⁆ N) := function.injective.module R ⟨λ f, f.to_linear_map.to_fun, rfl, coe_add⟩ coe_injective coe_smul end lie_module_hom /-- An equivalence of Lie algebra modules is a linear equivalence which is also a morphism of Lie algebra modules. -/ structure lie_module_equiv extends M →ₗ⁅R,L⁆ N := (inv_fun : N β†’ M) (left_inv : function.left_inverse inv_fun to_fun) (right_inv : function.right_inverse inv_fun to_fun) attribute [nolint doc_blame] lie_module_equiv.to_lie_module_hom notation M ` ≃ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_equiv R L M N namespace lie_module_equiv variables {R L M N P} /-- View an equivalence of Lie modules as a linear equivalence. -/ @[ancestor] def to_linear_equiv (e : M ≃ₗ⁅R,L⁆ N) : M ≃ₗ[R] N := { ..e } /-- View an equivalence of Lie modules as a type level equivalence. -/ @[ancestor] def to_equiv (e : M ≃ₗ⁅R,L⁆ N) : M ≃ N := { ..e } instance has_coe_to_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ N) := ⟨to_equiv⟩ instance has_coe_to_lie_module_hom : has_coe (M ≃ₗ⁅R,L⁆ N) (M →ₗ⁅R,L⁆ N) := ⟨to_lie_module_hom⟩ instance has_coe_to_linear_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ₗ[R] N) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (M ≃ₗ⁅R,L⁆ N) (Ξ» _, M β†’ N) := ⟨λ e, e.to_lie_module_hom.to_fun⟩ lemma injective (e : M ≃ₗ⁅R,L⁆ N) : function.injective e := e.to_equiv.injective @[simp] lemma coe_mk (f : M →ₗ⁅R,L⁆ N) (inv_fun h₁ hβ‚‚) : ((⟨f, inv_fun, h₁, hβ‚‚βŸ© : M ≃ₗ⁅R,L⁆ N) : M β†’ N) = f := rfl @[simp, norm_cast] lemma coe_to_lie_module_hom (e : M ≃ₗ⁅R,L⁆ N) : ((e : M →ₗ⁅R,L⁆ N) : M β†’ N) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : M ≃ₗ⁅R,L⁆ N) : ((e : M ≃ₗ[R] N) : M β†’ N) = e := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ⁅R,L⁆ N) β†’ M ≃ N) := Ξ» e₁ eβ‚‚ h, begin rcases e₁ with ⟨⟨⟩⟩, rcases eβ‚‚ with ⟨⟨⟩⟩, have inj := equiv.mk.inj h, dsimp at inj, apply lie_module_equiv.mk.inj_eq.mpr, split, { congr, ext, rw inj.1 }, { exact inj.2 }, end @[ext] lemma ext (e₁ eβ‚‚ : M ≃ₗ⁅R,L⁆ N) (h : βˆ€ m, e₁ m = eβ‚‚ m) : e₁ = eβ‚‚ := to_equiv_injective (equiv.ext h) instance : has_one (M ≃ₗ⁅R,L⁆ M) := ⟨{ map_lie' := Ξ» x m, rfl, ..(1 : M ≃ₗ[R] M) }⟩ @[simp] lemma one_apply (m : M) : (1 : (M ≃ₗ⁅R,L⁆ M)) m = m := rfl instance : inhabited (M ≃ₗ⁅R,L⁆ M) := ⟨1⟩ /-- Lie module equivalences are reflexive. -/ @[refl] def refl : M ≃ₗ⁅R,L⁆ M := 1 @[simp] lemma refl_apply (m : M) : (refl : M ≃ₗ⁅R,L⁆ M) m = m := rfl /-- Lie module equivalences are syemmtric. -/ @[symm] def symm (e : M ≃ₗ⁅R,L⁆ N) : N ≃ₗ⁅R,L⁆ M := { ..lie_module_hom.inverse e.to_lie_module_hom e.inv_fun e.left_inv e.right_inv, ..(e : M ≃ₗ[R] N).symm } @[simp] lemma apply_symm_apply (e : M ≃ₗ⁅R,L⁆ N) : βˆ€ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : M ≃ₗ⁅R,L⁆ N) : βˆ€ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply @[simp] lemma symm_symm (e : M ≃ₗ⁅R,L⁆ N) : e.symm.symm = e := by { ext, apply_fun e.symm using e.symm.injective, simp, } /-- Lie module equivalences are transitive. -/ @[trans] def trans (e₁ : M ≃ₗ⁅R,L⁆ N) (eβ‚‚ : N ≃ₗ⁅R,L⁆ P) : M ≃ₗ⁅R,L⁆ P := { ..lie_module_hom.comp eβ‚‚.to_lie_module_hom e₁.to_lie_module_hom, ..linear_equiv.trans e₁.to_linear_equiv eβ‚‚.to_linear_equiv } @[simp] lemma trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (eβ‚‚ : N ≃ₗ⁅R,L⁆ P) (m : M) : (e₁.trans eβ‚‚) m = eβ‚‚ (e₁ m) := rfl @[simp] lemma symm_trans (e₁ : M ≃ₗ⁅R,L⁆ N) (eβ‚‚ : N ≃ₗ⁅R,L⁆ P) : (e₁.trans eβ‚‚).symm = eβ‚‚.symm.trans e₁.symm := rfl @[simp] lemma self_trans_symm (e : M ≃ₗ⁅R,L⁆ N) : e.trans e.symm = refl := ext _ _ e.symm_apply_apply @[simp] lemma symm_trans_self (e : M ≃ₗ⁅R,L⁆ N) : e.symm.trans e = refl := ext _ _ e.apply_symm_apply end lie_module_equiv end lie_module_morphisms
210420818b8af5ddd7f724e4a16603d0c6520a80
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/crash.lean
782278b8158b29b5748bb20f938d812e2e8bfc2b
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
145
lean
-- section hypothesis P : Prop. definition crash := assume H : P, have H' : Β¬ P, from H, _. end
9ada01a1fce49ffa73110549529153adfeb5b8a1
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/int/div.lean
f7185ec7bd7856441ecad491d77eac9f5f96f143
[ "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
29,608
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Definitions and properties of div and mod, following the SSReflect library. Following SSReflect and the SMTlib standard, we define a % b so that 0 ≀ a % b < |b| when b β‰  0. -/ import data.int.order data.nat.div open [coercions] [reduce_hints] nat open [declarations] [classes] nat (succ) open algebra open eq.ops namespace int /- definitions -/ protected definition div (a b : β„€) : β„€ := sign b * (match a with | of_nat m := of_nat (m / (nat_abs b)) | -[1+m] := -[1+ ((m:nat) / (nat_abs b))] end) definition int_has_div [reducible] [instance] [priority int.prio] : has_div int := has_div.mk int.div lemma of_nat_div_eq (m : nat) (b : β„€) : (of_nat m) / b = sign b * of_nat (m / (nat_abs b)) := rfl lemma neg_succ_div_eq (m: nat) (b : β„€) : -[1+m] / b = sign b * -[1+ (m / (nat_abs b))] := rfl lemma div_def (a b : β„€) : a / b = sign b * (match a with | of_nat m := of_nat (m / (nat_abs b)) | -[1+m] := -[1+ ((m:nat) / (nat_abs b))] end) := rfl protected definition mod (a b : β„€) : β„€ := a - a / b * b definition int_has_mod [reducible] [instance] [priority int.prio] : has_mod int := has_mod.mk int.mod lemma mod_def (a b : β„€) : a % b = a - a / b * b := rfl notation [priority int.prio] a ≑ b `[mod `:0 c:0 `]` := a % c = b % c /- / -/ theorem of_nat_div (m n : nat) : of_nat (m / n) = (of_nat m) / (of_nat n) := nat.cases_on n (begin rewrite [of_nat_div_eq, of_nat_zero, sign_zero, zero_mul, nat.div_zero] end) (take (n : nat), by rewrite [of_nat_div_eq, sign_of_succ, one_mul]) theorem neg_succ_of_nat_div (m : nat) {b : β„€} (H : b > 0) : -[1+m] / b = -(m / b + 1) := calc -[1+m] / b = sign b * _ : rfl ... = -[1+(m / (nat_abs b))] : by rewrite [sign_of_pos H, one_mul] ... = -(m / b + 1) : by rewrite [of_nat_div_eq, sign_of_pos H, one_mul] protected theorem div_neg (a b : β„€) : a / -b = -(a / b) := begin induction a, rewrite [*of_nat_div_eq, sign_neg, neg_mul_eq_neg_mul, nat_abs_neg], rewrite [*neg_succ_div_eq, sign_neg, neg_mul_eq_neg_mul, nat_abs_neg], end theorem div_of_neg_of_pos {a b : β„€} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := obtain (m : nat) (H1 : a = -[1+m]), from exists_eq_neg_succ_of_nat Ha, calc a / b = -(m / b + 1) : by rewrite [H1, neg_succ_of_nat_div _ Hb] ... = -((-a -1) / b + 1) : by rewrite [H1, neg_succ_of_nat_eq', neg_sub, sub_neg_eq_add, add.comm 1, add_sub_cancel] protected theorem div_nonneg {a b : β„€} (Ha : a β‰₯ 0) (Hb : b β‰₯ 0) : a / b β‰₯ 0 := obtain (m : β„•) (Hm : a = m), from exists_eq_of_nat Ha, obtain (n : β„•) (Hn : b = n), from exists_eq_of_nat Hb, calc a / b = m / n : by rewrite [Hm, Hn] ... β‰₯ 0 : by rewrite -of_nat_div; apply trivial protected theorem div_nonpos {a b : β„€} (Ha : a β‰₯ 0) (Hb : b ≀ 0) : a / b ≀ 0 := calc a / b = -(a / -b) : by rewrite [int.div_neg, neg_neg] ... ≀ 0 : neg_nonpos_of_nonneg (int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)) theorem div_neg' {a b : β„€} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := have -a - 1 β‰₯ 0, from le_sub_one_of_lt (neg_pos_of_neg Ha), have (-a - 1) / b + 1 > 0, from lt_add_one_of_le (int.div_nonneg this (le_of_lt Hb)), calc a / b = -((-a - 1) / b + 1) : div_of_neg_of_pos Ha Hb ... < 0 : neg_neg_of_pos this protected theorem zero_div (b : β„€) : 0 / b = 0 := by rewrite [of_nat_div_eq, nat.zero_div, of_nat_zero, mul_zero] protected theorem div_zero (a : β„€) : a / 0 = 0 := by rewrite [div_def, sign_zero, zero_mul] protected theorem div_one (a : β„€) : a / 1 = a := assert (1 : int) > 0, from dec_trivial, int.cases_on a (take m : nat, by rewrite [-of_nat_one, -of_nat_div, nat.div_one]) (take m : nat, by rewrite [!neg_succ_of_nat_div this, -of_nat_one, -of_nat_div, nat.div_one]) theorem eq_div_mul_add_mod (a b : β„€) : a = a / b * b + a % b := !add.comm β–Έ eq_add_of_sub_eq rfl theorem div_eq_zero_of_lt {a b : β„€} : 0 ≀ a β†’ a < b β†’ a / b = 0 := int.cases_on a (take (m : nat), assume H, int.cases_on b (take (n : nat), assume H : m < n, show m / n = 0, by rewrite [-of_nat_div, nat.div_eq_zero_of_lt (lt_of_of_nat_lt_of_nat H)]) (take (n : nat), assume H : m < -[1+n], have H1 : Β¬(m < -[1+n]), from dec_trivial, absurd H H1)) (take (m : nat), assume H : 0 ≀ -[1+m], have Β¬ (0 ≀ -[1+m]), from dec_trivial, absurd H this) theorem div_eq_zero_of_lt_abs {a b : β„€} (H1 : 0 ≀ a) (H2 : a < abs b) : a / b = 0 := lt.by_cases (suppose b < 0, assert a < -b, from abs_of_neg this β–Έ H2, calc a / b = - (a / -b) : by rewrite [int.div_neg, neg_neg] ... = 0 : by rewrite [div_eq_zero_of_lt H1 this, neg_zero]) (suppose b = 0, this⁻¹ β–Έ !int.div_zero) (suppose b > 0, have a < b, from abs_of_pos this β–Έ H2, div_eq_zero_of_lt H1 this) private theorem add_mul_div_self_aux1 {a : β„€} {k : β„•} (n : β„•) (H1 : a β‰₯ 0) (H2 : k > 0) : (a + n * k) / k = a / k + n := obtain (m : nat) (Hm : a = of_nat m), from exists_eq_of_nat H1, begin subst Hm, rewrite [-of_nat_mul, -of_nat_add, -*of_nat_div, -of_nat_add, !nat.add_mul_div_self H2] end private theorem add_mul_div_self_aux2 {a : β„€} {k : β„•} (n : β„•) (H1 : a < 0) (H2 : k > 0) : (a + n * k) / k = a / k + n := obtain m (Hm : a = -[1+m]), from exists_eq_neg_succ_of_nat H1, or.elim (nat.lt_or_ge m (n * k)) (assume m_lt_nk : m < n * k, assert H3 : m + 1 ≀ n * k, from nat.succ_le_of_lt m_lt_nk, assert H4 : m / k + 1 ≀ n, from nat.succ_le_of_lt (nat.div_lt_of_lt_mul m_lt_nk), have (-[1+m] + n * k) / k = -[1+m] / k + n, from calc (-[1+m] + n * k) / k = of_nat ((k * n - (m + 1)) / k) : by rewrite [add.comm, neg_succ_of_nat_eq, of_nat_div, algebra.mul.comm k n, of_nat_sub H3] ... = of_nat (n - m / k - 1) : nat.mul_sub_div_of_lt (!nat.mul_comm β–Έ m_lt_nk) ... = -[1+m] / k + n : by rewrite [nat.sub_sub, of_nat_sub H4, int.add_comm, sub_eq_add_neg, !neg_succ_of_nat_div (of_nat_lt_of_nat_of_lt H2), of_nat_add, of_nat_div], Hm⁻¹ β–Έ this) (assume nk_le_m : n * k ≀ m, have -[1+m] / k + n = (-[1+m] + n * k) / k, from calc -[1+m] / k + n = -(of_nat ((m - n * k + n * k) / k) + 1) + n : by rewrite [neg_succ_of_nat_div m (of_nat_lt_of_nat_of_lt H2), nat.sub_add_cancel nk_le_m, of_nat_div] ... = -(of_nat ((m - n * k) / k + n) + 1) + n : nat.add_mul_div_self H2 ... = -(of_nat (m - n * k) / k + 1) : by rewrite [of_nat_add, *neg_add, add.right_comm, neg_add_cancel_right, of_nat_div] ... = -[1+(m - n * k)] / k : neg_succ_of_nat_div _ (of_nat_lt_of_nat_of_lt H2) ... = -(of_nat(m - n * k) + 1) / k : rfl ... = -(of_nat m - of_nat(n * k) + 1) / k : of_nat_sub nk_le_m ... = (-(of_nat m + 1) + n * k) / k : by rewrite [sub_eq_add_neg, -*add.assoc, *neg_add, neg_neg, add.right_comm] ... = (-[1+m] + n * k) / k : rfl, Hm⁻¹ β–Έ this⁻¹) private theorem add_mul_div_self_aux3 (a : β„€) {b c : β„€} (H1 : b β‰₯ 0) (H2 : c > 0) : (a + b * c) / c = a / c + b := obtain (n : nat) (Hn : b = of_nat n), from exists_eq_of_nat H1, obtain (k : nat) (Hk : c = of_nat k), from exists_eq_of_nat (le_of_lt H2), have knz : k β‰  0, from assume kz, !lt.irrefl (kz β–Έ Hk β–Έ H2), have kgt0 : (#nat k > 0), from nat.pos_of_ne_zero knz, have H3 : (a + n * k) / k = a / k + n, from or.elim (lt_or_ge a 0) (assume Ha : a < 0, add_mul_div_self_aux2 _ Ha kgt0) (assume Ha : a β‰₯ 0, add_mul_div_self_aux1 _ Ha kgt0), Hn⁻¹ β–Έ Hk⁻¹ β–Έ H3 private theorem add_mul_div_self_aux4 (a b : β„€) {c : β„€} (H : c > 0) : (a + b * c) / c = a / c + b := or.elim (le.total 0 b) (assume H1 : 0 ≀ b, add_mul_div_self_aux3 _ H1 H) (assume H1 : 0 β‰₯ b, eq.symm (calc a / c + b = (a + b * c + -b * c) / c + b : by rewrite [-neg_mul_eq_neg_mul, add_neg_cancel_right] ... = (a + b * c) / c + - b + b : add_mul_div_self_aux3 _ (neg_nonneg_of_nonpos H1) H ... = (a + b * c) / c : neg_add_cancel_right)) protected theorem add_mul_div_self (a b : β„€) {c : β„€} (H : c β‰  0) : (a + b * c) / c = a / c + b := lt.by_cases (assume H1 : 0 < c, !add_mul_div_self_aux4 H1) (assume H1 : 0 = c, absurd H1⁻¹ H) (assume H1 : 0 > c, have H2 : -c > 0, from neg_pos_of_neg H1, calc (a + b * c) / c = - ((a + -b * -c) / -c) : by rewrite [int.div_neg, neg_mul_neg, neg_neg] ... = -(a / -c + -b) : !add_mul_div_self_aux4 H2 ... = a / c + b : by rewrite [int.div_neg, neg_add, *neg_neg]) protected theorem add_mul_div_self_left (a : β„€) {b : β„€} (c : β„€) (H : b β‰  0) : (a + b * c) / b = a / b + c := !mul.comm β–Έ !int.add_mul_div_self H protected theorem mul_div_cancel (a : β„€) {b : β„€} (H : b β‰  0) : a * b / b = a := calc a * b / b = (0 + a * b) / b : zero_add ... = 0 / b + a : !int.add_mul_div_self H ... = a : by rewrite [int.zero_div, zero_add] protected theorem mul_div_cancel_left {a : β„€} (b : β„€) (H : a β‰  0) : a * b / a = b := !mul.comm β–Έ int.mul_div_cancel b H protected theorem div_self {a : β„€} (H : a β‰  0) : a / a = 1 := !mul_one β–Έ !int.mul_div_cancel_left H /- mod -/ theorem of_nat_mod (m n : nat) : m % n = of_nat (m % n) := have H : m = of_nat (m % n) + m / n * n, from calc m = of_nat (m / n * n + m % n) : nat.eq_div_mul_add_mod ... = of_nat (m / n) * n + of_nat (m % n) : rfl ... = m / n * n + of_nat (m % n) : of_nat_div ... = of_nat (m % n) + m / n * n : add.comm, calc m % n = m - m / n * n : rfl ... = of_nat (m % n) : sub_eq_of_eq_add H theorem neg_succ_of_nat_mod (m : β„•) {b : β„€} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := calc -[1+m] % b = -(m + 1) - -[1+m] / b * b : rfl ... = -(m + 1) - -(m / b + 1) * b : neg_succ_of_nat_div _ bpos ... = -m + -1 + (b + m / b * b) : by rewrite [neg_add, -neg_mul_eq_neg_mul, sub_neg_eq_add, right_distrib, one_mul, (add.comm b)] ... = b + -1 + (-m + m / b * b) : by rewrite [-*add.assoc, add.comm (-m), add.right_comm (-1), (add.comm b)] ... = b - 1 - m % b : by rewrite [(mod_def), *sub_eq_add_neg, neg_add, neg_neg] -- it seems the parser has difficulty here, because "mod" is a token? theorem mod_neg (a b : β„€) : a % -b = a % b := calc a % -b = a - (a / -b) * -b : rfl ... = a - -(a / b) * -b : int.div_neg ... = a - a / b * b : neg_mul_neg ... = a % b : rfl theorem mod_abs (a b : β„€) : a % (abs b) = a % b := abs.by_cases rfl !mod_neg theorem zero_mod (b : β„€) : 0 % b = 0 := by rewrite [(mod_def), int.zero_div, zero_mul, sub_zero] theorem mod_zero (a : β„€) : a % 0 = a := by rewrite [(mod_def), mul_zero, sub_zero] theorem mod_one (a : β„€) : a % 1 = 0 := calc a % 1 = a - a / 1 * 1 : rfl ... = 0 : by rewrite [mul_one, int.div_one, sub_self] private lemma of_nat_mod_abs (m : β„•) (b : β„€) : m % (abs b) = of_nat (m % (nat_abs b)) := calc m % (abs b) = m % (nat_abs b) : of_nat_nat_abs ... = of_nat (m % (nat_abs b)) : of_nat_mod private lemma of_nat_mod_abs_lt (m : β„•) {b : β„€} (H : b β‰  0) : m % (abs b) < (abs b) := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : (#nat nat_abs b > 0), from lt_of_of_nat_lt_of_nat (!of_nat_nat_abs⁻¹ β–Έ H1), calc m % (abs b) = of_nat (m % (nat_abs b)) : of_nat_mod_abs m b ... < nat_abs b : of_nat_lt_of_nat_of_lt (!nat.mod_lt H2) ... = abs b : of_nat_nat_abs _ theorem mod_eq_of_lt {a b : β„€} (H1 : 0 ≀ a) (H2 : a < b) : a % b = a := obtain (m : nat) (Hm : a = of_nat m), from exists_eq_of_nat H1, obtain (n : nat) (Hn : b = of_nat n), from exists_eq_of_nat (le_of_lt (lt_of_le_of_lt H1 H2)), begin revert H2, rewrite [Hm, Hn, of_nat_mod, of_nat_lt_of_nat_iff, of_nat_eq_of_nat_iff], apply nat.mod_eq_of_lt end theorem mod_nonneg (a : β„€) {b : β„€} (H : b β‰  0) : a % b β‰₯ 0 := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : a % (abs b) β‰₯ 0, from int.cases_on a (take m : nat, (of_nat_mod_abs m b)⁻¹ β–Έ of_nat_nonneg (nat.mod m (nat_abs b))) (take m : nat, have H3 : 1 + m % (abs b) ≀ (abs b), from (!add.comm β–Έ add_one_le_of_lt (of_nat_mod_abs_lt m H)), calc -[1+m] % (abs b) = abs b - 1 - m % (abs b) : neg_succ_of_nat_mod _ H1 ... = abs b - (1 + m % (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc] ... β‰₯ 0 : iff.mpr !sub_nonneg_iff_le H3), !mod_abs β–Έ H2 theorem mod_lt (a : β„€) {b : β„€} (H : b β‰  0) : a % b < (abs b) := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : a % (abs b) < abs b, from int.cases_on a (take m, of_nat_mod_abs_lt m H) (take m : nat, have H3 : abs b β‰  0, from assume H', H (eq_zero_of_abs_eq_zero H'), have H4 : 1 + m % (abs b) > 0, from add_pos_of_pos_of_nonneg dec_trivial (mod_nonneg _ H3), calc -[1+m] % (abs b) = abs b - 1 - m % (abs b) : neg_succ_of_nat_mod _ H1 ... = abs b - (1 + m % (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc] ... < abs b : sub_lt_self _ H4), !mod_abs β–Έ H2 theorem add_mul_mod_self {a b c : β„€} : (a + b * c) % c = a % c := decidable.by_cases (assume cz : c = 0, by rewrite [cz, mul_zero, add_zero]) (assume cnz, by rewrite [(mod_def), !int.add_mul_div_self cnz, right_distrib, sub_add_eq_sub_sub_swap, add_sub_cancel]) theorem add_mul_mod_self_left (a b c : β„€) : (a + b * c) % b = a % b := !mul.comm β–Έ !add_mul_mod_self theorem add_mod_self {a b : β„€} : (a + b) % b = a % b := by rewrite -(int.mul_one b) at {1}; apply add_mul_mod_self_left theorem add_mod_self_left {a b : β„€} : (a + b) % a = b % a := !add.comm β–Έ !add_mod_self theorem mod_add_mod (m n k : β„€) : (m % n + k) % n = (m + k) % n := by rewrite [eq_div_mul_add_mod m n at {2}, add.assoc, add.comm (m / n * n), add_mul_mod_self] theorem add_mod_mod (m n k : β„€) : (m + n % k) % k = (m + n) % k := by rewrite [add.comm, mod_add_mod, add.comm] theorem add_mod_eq_add_mod_right {m n k : β„€} (i : β„€) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rewrite [-mod_add_mod, -mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : β„€} (i : β„€) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rewrite [add.comm, add_mod_eq_add_mod_right _ H, add.comm] theorem mod_eq_mod_of_add_mod_eq_add_mod_right {m n k i : β„€} (H : (m + i) % n = (k + i) % n) : m % n = k % n := assert H1 : (m + i + (-i)) % n = (k + i + (-i)) % n, from add_mod_eq_add_mod_right _ H, by rewrite [*add_neg_cancel_right at H1]; apply H1 theorem mod_eq_mod_of_add_mod_eq_add_mod_left {m n k i : β„€} : (i + m) % n = (i + k) % n β†’ m % n = k % n := by rewrite [add.comm i m, add.comm i k]; apply mod_eq_mod_of_add_mod_eq_add_mod_right theorem mul_mod_left (a b : β„€) : (a * b) % b = 0 := by rewrite [-zero_add (a * b), add_mul_mod_self, zero_mod] theorem mul_mod_right (a b : β„€) : (a * b) % a = 0 := !mul.comm β–Έ !mul_mod_left theorem mod_self {a : β„€} : a % a = 0 := decidable.by_cases (assume H : a = 0, H⁻¹ β–Έ !mod_zero) (assume H : a β‰  0, calc a % a = a - a / a * a : rfl ... = 0 : by rewrite [!int.div_self H, one_mul, sub_self]) theorem mod_lt_of_pos (a : β„€) {b : β„€} (H : b > 0) : a % b < b := !abs_of_pos H β–Έ !mod_lt (ne.symm (ne_of_lt H)) /- properties of / and % -/ theorem mul_div_mul_of_pos_aux {a : β„€} (b : β„€) {c : β„€} (H1 : a > 0) (H2 : c > 0) : a * b / (a * c) = b / c := have H3 : a * c β‰  0, from ne.symm (ne_of_lt (mul_pos H1 H2)), have H4 : a * (b % c) < a * c, from mul_lt_mul_of_pos_left (!mod_lt_of_pos H2) H1, have H5 : a * (b % c) β‰₯ 0, from mul_nonneg (le_of_lt H1) (!mod_nonneg (ne.symm (ne_of_lt H2))), calc a * b / (a * c) = a * (b / c * c + b % c) / (a * c) : eq_div_mul_add_mod ... = (a * (b % c) + a * c * (b / c)) / (a * c) : by rewrite [!add.comm, int.left_distrib, mul.comm _ c, -!mul.assoc] ... = a * (b % c) / (a * c) + b / c : !int.add_mul_div_self_left H3 ... = 0 + b / c : {!div_eq_zero_of_lt H5 H4} ... = b / c : zero_add theorem mul_div_mul_of_pos {a : β„€} (b c : β„€) (H : a > 0) : a * b / (a * c) = b / c := lt.by_cases (assume H1 : c < 0, have H2 : -c > 0, from neg_pos_of_neg H1, calc a * b / (a * c) = - (a * b / (a * -c)) : by rewrite [-neg_mul_eq_mul_neg, int.div_neg, neg_neg] ... = - (b / -c) : mul_div_mul_of_pos_aux _ H H2 ... = b / c : by rewrite [int.div_neg, neg_neg]) (assume H1 : c = 0, calc a * b / (a * c) = 0 : by rewrite [H1, mul_zero, int.div_zero] ... = b / c : by rewrite [H1, int.div_zero]) (assume H1 : c > 0, mul_div_mul_of_pos_aux _ H H1) theorem mul_div_mul_of_pos_left (a : β„€) {b : β„€} (c : β„€) (H : b > 0) : a * b / (c * b) = a / c := !mul.comm β–Έ !mul.comm β–Έ !mul_div_mul_of_pos H theorem mul_mod_mul_of_pos {a : β„€} (b c : β„€) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rewrite [(mod_def), mod_def, !mul_div_mul_of_pos H, mul_sub_left_distrib, mul.left_comm] theorem lt_div_add_one_mul_self (a : β„€) {b : β„€} (H : b > 0) : a < (a / b + 1) * b := have H : a - a / b * b < b, from !mod_lt_of_pos H, calc a < a / b * b + b : iff.mpr !lt_add_iff_sub_lt_left H ... = (a / b + 1) * b : by rewrite [right_distrib, one_mul] theorem div_le_of_nonneg_of_nonneg {a b : β„€} (Ha : a β‰₯ 0) (Hb : b β‰₯ 0) : a / b ≀ a := obtain (m : β„•) (Hm : a = m), from exists_eq_of_nat Ha, obtain (n : β„•) (Hn : b = n), from exists_eq_of_nat Hb, calc a / b = of_nat (m / n) : by rewrite [Hm, Hn, of_nat_div] ... ≀ m : of_nat_le_of_nat_of_le !nat.div_le_self ... = a : Hm theorem abs_div_le_abs (a b : β„€) : abs (a / b) ≀ abs a := have H : βˆ€a b, b > 0 β†’ abs (a / b) ≀ abs a, from take a b, assume H1 : b > 0, or.elim (le_or_gt 0 a) (assume H2 : 0 ≀ a, have H3 : 0 ≀ b, from le_of_lt H1, calc abs (a / b) = a / b : abs_of_nonneg (int.div_nonneg H2 H3) ... ≀ a : div_le_of_nonneg_of_nonneg H2 H3 ... = abs a : abs_of_nonneg H2) (assume H2 : a < 0, have H3 : -a - 1 β‰₯ 0, from le_sub_one_of_lt (neg_pos_of_neg H2), have H4 : (-a - 1) / b + 1 β‰₯ 0, from add_nonneg (int.div_nonneg H3 (le_of_lt H1)) (of_nat_le_of_nat_of_le !nat.zero_le), have H5 : (-a - 1) / b ≀ -a - 1, from div_le_of_nonneg_of_nonneg H3 (le_of_lt H1), calc abs (a / b) = abs ((-a - 1) / b + 1) : by rewrite [div_of_neg_of_pos H2 H1, abs_neg] ... = (-a - 1) / b + 1 : abs_of_nonneg H4 ... ≀ -a - 1 + 1 : add_le_add_right H5 _ ... = abs a : by rewrite [sub_add_cancel, abs_of_neg H2]), lt.by_cases (assume H1 : b < 0, calc abs (a / b) = abs (a / -b) : by rewrite [int.div_neg, abs_neg] ... ≀ abs a : H _ _ (neg_pos_of_neg H1)) (assume H1 : b = 0, calc abs (a / b) = 0 : by rewrite [H1, int.div_zero, abs_zero] ... ≀ abs a : abs_nonneg) (assume H1 : b > 0, H _ _ H1) theorem div_mul_cancel_of_mod_eq_zero {a b : β„€} (H : a % b = 0) : a / b * b = a := by rewrite [eq_div_mul_add_mod a b at {2}, H, add_zero] theorem mul_div_cancel_of_mod_eq_zero {a b : β„€} (H : a % b = 0) : b * (a / b) = a := !mul.comm β–Έ div_mul_cancel_of_mod_eq_zero H /- dvd -/ theorem dvd_of_of_nat_dvd_of_nat {m n : β„•} : of_nat m ∣ of_nat n β†’ (#nat m ∣ n) := nat.by_cases_zero_pos n (assume H, dvd_zero m) (take n' : β„•, assume H1 : (#nat n' > 0), have H2 : of_nat n' > 0, from of_nat_pos H1, assume H3 : of_nat m ∣ of_nat n', dvd.elim H3 (take c, assume H4 : of_nat n' = of_nat m * c, have H5 : c > 0, from pos_of_mul_pos_left (H4 β–Έ H2) !of_nat_nonneg, obtain k (H6 : c = of_nat k), from exists_eq_of_nat (le_of_lt H5), have H7 : n' = (#nat m * k), from (of_nat.inj (H6 β–Έ H4)), dvd.intro H7⁻¹)) theorem of_nat_dvd_of_nat_of_dvd {m n : β„•} (H : #nat m ∣ n) : of_nat m ∣ of_nat n := dvd.elim H (take k, assume H1 : #nat n = m * k, dvd.intro (H1⁻¹ β–Έ rfl)) theorem of_nat_dvd_of_nat_iff (m n : β„•) : of_nat m ∣ of_nat n ↔ m ∣ n := iff.intro dvd_of_of_nat_dvd_of_nat of_nat_dvd_of_nat_of_dvd theorem dvd.antisymm {a b : β„€} (H1 : a β‰₯ 0) (H2 : b β‰₯ 0) : a ∣ b β†’ b ∣ a β†’ a = b := begin rewrite [-abs_of_nonneg H1, -abs_of_nonneg H2, -*of_nat_nat_abs], rewrite [*of_nat_dvd_of_nat_iff, *of_nat_eq_of_nat_iff], apply nat.dvd.antisymm end theorem dvd_of_mod_eq_zero {a b : β„€} (H : b % a = 0) : a ∣ b := dvd.intro (!mul.comm β–Έ div_mul_cancel_of_mod_eq_zero H) theorem mod_eq_zero_of_dvd {a b : β„€} (H : a ∣ b) : b % a = 0 := dvd.elim H (take z, assume H1 : b = a * z, H1⁻¹ β–Έ !mul_mod_right) theorem dvd_iff_mod_eq_zero (a b : β„€) : a ∣ b ↔ b % a = 0 := iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero definition dvd.decidable_rel [instance] : decidable_rel dvd := take a n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero) protected theorem div_mul_cancel {a b : β„€} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : β„€} (H : a ∣ b) : a * (b / a) = b := !mul.comm β–Έ !int.div_mul_cancel H protected theorem mul_div_assoc (a : β„€) {b c : β„€} (H : c ∣ b) : (a * b) / c = a * (b / c) := decidable.by_cases (assume cz : c = 0, by rewrite [cz, *int.div_zero, mul_zero]) (assume cnz : c β‰  0, obtain d (H' : b = d * c), from exists_eq_mul_left_of_dvd H, by rewrite [H', -mul.assoc, *(!int.mul_div_cancel cnz)]) theorem div_dvd_div {a b c : β„€} (H1 : a ∣ b) (H2 : b ∣ c) : b / a ∣ c / a := have H3 : b = b / a * a, from (int.div_mul_cancel H1)⁻¹, have H4 : c = c / a * a, from (int.div_mul_cancel (dvd.trans H1 H2))⁻¹, decidable.by_cases (assume H5 : a = 0, have H6: c / a = 0, from (congr_arg _ H5 ⬝ !int.div_zero), H6⁻¹ β–Έ !dvd_zero) (assume H5 : a β‰  0, dvd_of_mul_dvd_mul_right H5 (H3 β–Έ H4 β–Έ H2)) protected theorem div_eq_iff_eq_mul_right {a b : β„€} (c : β„€) (H : b β‰  0) (H' : b ∣ a) : a / b = c ↔ a = b * c := iff.intro (assume H1, by rewrite [-H1, int.mul_div_cancel' H']) (assume H1, by rewrite [H1, !int.mul_div_cancel_left H]) protected theorem div_eq_iff_eq_mul_left {a b : β„€} (c : β„€) (H : b β‰  0) (H' : b ∣ a) : a / b = c ↔ a = c * b := !mul.comm β–Έ !int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_right {a b c : β„€} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := calc a = b * (a / b) : int.mul_div_cancel' H1 ... = b * c : H2 protected theorem div_eq_of_eq_mul_right {a b c : β„€} (H1 : b β‰  0) (H2 : a = b * c) : a / b = c := calc a / b = b * c / b : H2 ... = c : !int.mul_div_cancel_left H1 protected theorem eq_mul_of_div_eq_left {a b c : β„€} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := !mul.comm β–Έ !int.eq_mul_of_div_eq_right H1 H2 protected theorem div_eq_of_eq_mul_left {a b c : β„€} (H1 : b β‰  0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (!mul.comm β–Έ H2) theorem neg_div_of_dvd {a b : β„€} (H : b ∣ a) : -a / b = -(a / b) := decidable.by_cases (assume H1 : b = 0, by rewrite [H1, *int.div_zero, neg_zero]) (assume H1 : b β‰  0, dvd.elim H (take c, assume H' : a = b * c, by rewrite [H', neg_mul_eq_mul_neg, *!int.mul_div_cancel_left H1])) protected theorem sign_eq_div_abs (a : β„€) : sign a = a / (abs a) := decidable.by_cases (suppose a = 0, by subst a) (suppose a β‰  0, have abs a β‰  0, from assume H, this (eq_zero_of_abs_eq_zero H), have abs a ∣ a, from abs_dvd_of_dvd !dvd.refl, eq.symm (iff.mpr (!int.div_eq_iff_eq_mul_left `abs a β‰  0` this) !eq_sign_mul_abs)) theorem le_of_dvd {a b : β„€} (bpos : b > 0) (H : a ∣ b) : a ≀ b := or.elim !le_or_gt (suppose a ≀ 0, le.trans this (le_of_lt bpos)) (suppose a > 0, obtain c (Hc : b = a * c), from exists_eq_mul_right_of_dvd H, have a * c > 0, by rewrite -Hc; exact bpos, have c > 0, from pos_of_mul_pos_left this (le_of_lt `a > 0`), show a ≀ b, from calc a = a * 1 : mul_one ... ≀ a * c : mul_le_mul_of_nonneg_left (add_one_le_of_lt `c > 0`) (le_of_lt `a > 0`) ... = b : Hc) /- / and ordering -/ protected theorem div_mul_le (a : β„€) {b : β„€} (H : b β‰  0) : a / b * b ≀ a := calc a = a / b * b + a % b : eq_div_mul_add_mod ... β‰₯ a / b * b : le_add_of_nonneg_right (!mod_nonneg H) protected theorem div_le_of_le_mul {a b c : β„€} (H : c > 0) (H' : a ≀ b * c) : a / c ≀ b := le_of_mul_le_mul_right (calc a / c * c = a / c * c + 0 : add_zero ... ≀ a / c * c + a % c : add_le_add_left (!mod_nonneg (ne_of_gt H)) ... = a : eq_div_mul_add_mod ... ≀ b * c : H') H protected theorem div_le_self (a : β„€) {b : β„€} (H1 : a β‰₯ 0) (H2 : b β‰₯ 0) : a / b ≀ a := or.elim (lt_or_eq_of_le H2) (assume H3 : b > 0, have H4 : b β‰₯ 1, from add_one_le_of_lt H3, have H5 : a ≀ a * b, from calc a = a * 1 : mul_one ... ≀ a * b : !mul_le_mul_of_nonneg_left H4 H1, int.div_le_of_le_mul H3 H5) (assume H3 : 0 = b, by rewrite [-H3, int.div_zero]; apply H1) protected theorem mul_le_of_le_div {a b c : β„€} (H1 : c > 0) (H2 : a ≀ b / c) : a * c ≀ b := calc a * c ≀ b / c * c : !mul_le_mul_of_nonneg_right H2 (le_of_lt H1) ... ≀ b : !int.div_mul_le (ne_of_gt H1) protected theorem le_div_of_mul_le {a b c : β„€} (H1 : c > 0) (H2 : a * c ≀ b) : a ≀ b / c := have H3 : a * c < (b / c + 1) * c, from calc a * c ≀ b : H2 ... = b / c * c + b % c : eq_div_mul_add_mod ... < b / c * c + c : add_lt_add_left (!mod_lt_of_pos H1) ... = (b / c + 1) * c : by rewrite [right_distrib, one_mul], le_of_lt_add_one (lt_of_mul_lt_mul_right H3 (le_of_lt H1)) protected theorem le_div_iff_mul_le {a b c : β„€} (H : c > 0) : a ≀ b / c ↔ a * c ≀ b := iff.intro (!int.mul_le_of_le_div H) (!int.le_div_of_mul_le H) protected theorem div_le_div {a b c : β„€} (H : c > 0) (H' : a ≀ b) : a / c ≀ b / c := int.le_div_of_mul_le H (le.trans (!int.div_mul_le (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : β„€} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_mul_lt_mul_right (calc a / c * c = a / c * c + 0 : add_zero ... ≀ a / c * c + a % c : add_le_add_left (!mod_nonneg (ne_of_gt H)) ... = a : eq_div_mul_add_mod ... < b * c : H') (le_of_lt H) protected theorem lt_mul_of_div_lt {a b c : β„€} (H1 : c > 0) (H2 : a / c < b) : a < b * c := assert H3 : (a / c + 1) * c ≀ b * c, from !mul_le_mul_of_nonneg_right (add_one_le_of_lt H2) (le_of_lt H1), have H4 : a / c * c + c ≀ b * c, by rewrite [right_distrib at H3, one_mul at H3]; apply H3, calc a = a / c * c + a % c : eq_div_mul_add_mod ... < a / c * c + c : add_lt_add_left (!mod_lt_of_pos H1) ... ≀ b * c : H4 protected theorem div_lt_iff_lt_mul {a b c : β„€} (H : c > 0) : a / c < b ↔ a < b * c := iff.intro (!int.lt_mul_of_div_lt H) (!int.div_lt_of_lt_mul H) protected theorem div_le_iff_le_mul_of_div {a b : β„€} (c : β„€) (H : b > 0) (H' : b ∣ a) : a / b ≀ c ↔ a ≀ c * b := by rewrite [propext (!le_iff_mul_le_mul_right H), !int.div_mul_cancel H'] protected theorem le_mul_of_div_le_of_div {a b c : β„€} (H1 : b > 0) (H2 : b ∣ a) (H3 : a / b ≀ c) : a ≀ c * b := iff.mp (!int.div_le_iff_le_mul_of_div H1 H2) H3 theorem div_pos_of_pos_of_dvd {a b : β„€} (H1 : a > 0) (H2 : b β‰₯ 0) (H3 : b ∣ a) : a / b > 0 := have H4 : b β‰  0, from (assume H5 : b = 0, have H6 : a = 0, from eq_zero_of_zero_dvd (H5 β–Έ H3), ne_of_gt H1 H6), have H6 : (a / b) * b > 0, by rewrite (int.div_mul_cancel H3); apply H1, pos_of_mul_pos_right H6 H2 theorem div_eq_div_of_dvd_of_dvd {a b c d : β„€} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b β‰  0) (H4 : d β‰  0) (H5 : a * d = b * c) : a / b = c / d := begin apply int.div_eq_of_eq_mul_right H3, rewrite [-!int.mul_div_assoc H2], apply eq.symm, apply int.div_eq_of_eq_mul_left H4, apply eq.symm H5 end end int
72be0b374659d7c8d05183febf0b9684f9e6cb20
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monad/kleisli.lean
138d9ba68702b4844a0a494b36b0af04ceece425
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,529
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Bhavik Mehta -/ import category_theory.adjunction.basic import category_theory.monad.basic /-! # Kleisli category on a (co)monad This file defines the Kleisli category on a monad `(T, Ξ·_ T, ΞΌ_ T)` as well as the co-Kleisli category on a comonad `(U, Ξ΅_ U, Ξ΄_ U)`. It also defines the Kleisli adjunction which gives rise to the monad `(T, Ξ·_ T, ΞΌ_ T)` as well as the co-Kleisli adjunction which gives rise to the comonad `(U, Ξ΅_ U, Ξ΄_ U)`. ## References * [Riehl, *Category theory in context*, Definition 5.2.9][riehl2017] -/ namespace category_theory universes v u -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u} [category.{v} C] /-- The objects for the Kleisli category of the monad `T : monad C`, which are the same thing as objects of the base category `C`. -/ @[nolint unused_arguments] def kleisli (T : monad C) := C namespace kleisli variables (T : monad C) instance [inhabited C] (T : monad C) : inhabited (kleisli T) := ⟨(default : C)⟩ /-- The Kleisli category on a monad `T`. cf Definition 5.2.9 in [Riehl][riehl2017]. -/ instance kleisli.category : category (kleisli T) := { hom := Ξ» (X Y : C), X ⟢ (T : C β₯€ C).obj Y, id := Ξ» X, T.Ξ·.app X, comp := Ξ» X Y Z f g, f ≫ (T : C β₯€ C).map g ≫ T.ΞΌ.app Z, id_comp' := Ξ» X Y f, begin rw [← T.Ξ·.naturality_assoc f, T.left_unit], apply category.comp_id, end, assoc' := Ξ» W X Y Z f g h, begin simp only [functor.map_comp, category.assoc, monad.assoc], erw T.ΞΌ.naturality_assoc, end } namespace adjunction /-- The left adjoint of the adjunction which induces the monad `(T, Ξ·_ T, ΞΌ_ T)`. -/ @[simps] def to_kleisli : C β₯€ kleisli T := { obj := Ξ» X, (X : kleisli T), map := Ξ» X Y f, (f ≫ T.Ξ·.app Y : _), map_comp' := Ξ» X Y Z f g, by { unfold_projs, simp [← T.Ξ·.naturality g] } } /-- The right adjoint of the adjunction which induces the monad `(T, Ξ·_ T, ΞΌ_ T)`. -/ @[simps] def from_kleisli : kleisli T β₯€ C := { obj := Ξ» X, T.obj X, map := Ξ» X Y f, T.map f ≫ T.ΞΌ.app Y, map_id' := Ξ» X, T.right_unit _, map_comp' := Ξ» X Y Z f g, begin unfold_projs, simp only [functor.map_comp, category.assoc], erw [← T.ΞΌ.naturality_assoc g, T.assoc], refl, end } /-- The Kleisli adjunction which gives rise to the monad `(T, Ξ·_ T, ΞΌ_ T)`. cf Lemma 5.2.11 of [Riehl][riehl2017]. -/ def adj : to_kleisli T ⊣ from_kleisli T := adjunction.mk_of_hom_equiv { hom_equiv := Ξ» X Y, equiv.refl (X ⟢ T.obj Y), hom_equiv_naturality_left_symm' := Ξ» X Y Z f g, begin unfold_projs, dsimp, rw [category.assoc, ← T.Ξ·.naturality_assoc g, functor.id_map], dsimp, simp [monad.left_unit], end } /-- The composition of the adjunction gives the original functor. -/ def to_kleisli_comp_from_kleisli_iso_self : to_kleisli T β‹™ from_kleisli T β‰… T := nat_iso.of_components (Ξ» X, iso.refl _) (Ξ» X Y f, by { dsimp, simp }) end adjunction end kleisli /-- The objects for the co-Kleisli category of the comonad `U : monad C`, which are the same thing as objects of the base category `C`. -/ @[nolint unused_arguments] def cokleisli (U : comonad C) := C namespace cokleisli variables (U : comonad C) instance [inhabited C] (U : comonad C) : inhabited (cokleisli U) := ⟨(default : C)⟩ /-- The co-Kleisli category on a comonad `U`.-/ instance cokleisli.category : category (cokleisli U) := { hom := Ξ» (X Y : C), (U : C β₯€ C).obj X ⟢ Y, id := Ξ» X, U.Ξ΅.app X, comp := Ξ» X Y Z f g, U.Ξ΄.app X ≫ (U : C β₯€ C).map f ≫ g, id_comp' := Ξ» X Y f, by rw U.right_counit_assoc, assoc' := Ξ» W X Y Z f g h, begin unfold_projs, simp only [functor.map_comp, ← category.assoc, U.Ξ΄.naturality_assoc, functor.comp_map, U.coassoc] end } namespace adjunction /-- The right adjoint of the adjunction which induces the comonad `(U, Ξ΅_ U, Ξ΄_ U)`. -/ @[simps] def to_cokleisli : C β₯€ cokleisli U := { obj := Ξ» X, (X : cokleisli U), map := Ξ» X Y f, (U.Ξ΅.app X ≫ f : _), map_comp' := Ξ» X Y Z f g, by { unfold_projs, simp [← U.Ξ΅.naturality g] } } /-- The left adjoint of the adjunction which induces the comonad `(U, Ξ΅_ U, Ξ΄_ U)`. -/ @[simps] def from_cokleisli : cokleisli U β₯€ C := { obj := Ξ» X, U.obj X, map := Ξ» X Y f, U.Ξ΄.app X ≫ U.map f, map_id' := Ξ» X, U.right_counit _, map_comp' := Ξ» X Y Z f g, begin unfold_projs, dsimp, simp only [functor.map_comp, ← category.assoc], rw comonad.coassoc, simp only [category.assoc, nat_trans.naturality, functor.comp_map], end } /-- The co-Kleisli adjunction which gives rise to the monad `(U, Ξ΅_ U, Ξ΄_ U)`. -/ def adj : from_cokleisli U ⊣ to_cokleisli U := adjunction.mk_of_hom_equiv { hom_equiv := Ξ» X Y, equiv.refl (U.obj X ⟢ Y), hom_equiv_naturality_right' := Ξ» X Y Z f g, begin unfold_projs, dsimp, erw [← category.assoc (U.map f), U.Ξ΅.naturality], dsimp, simp only [← category.assoc, comonad.left_counit, category.id_comp] end } /-- The composition of the adjunction gives the original functor. -/ def to_cokleisli_comp_from_cokleisli_iso_self : to_cokleisli U β‹™ from_cokleisli U β‰… U := nat_iso.of_components (Ξ» X, iso.refl _) (Ξ» X Y f, by { dsimp, simp }) end adjunction end cokleisli end category_theory
8dde8ae7e3ab82a996c26c479230b8317ef55d61
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/order/proj_Icc.lean
0885475c3d96123768fbcb1e865fa9ead18880e1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,497
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Patrick Massot -/ import data.set.intervals.proj_Icc import topology.order.basic /-! # Projection onto a closed interval > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that the projection `set.proj_Icc f a b h` is a quotient map, and use it to show that `Icc_extend h f` is continuous if and only if `f` is continuous. -/ open set filter open_locale filter topology variables {Ξ± Ξ² Ξ³ : Type*} [linear_order Ξ±] [topological_space Ξ³] {a b c : Ξ±} {h : a ≀ b} lemma filter.tendsto.Icc_extend (f : Ξ³ β†’ Icc a b β†’ Ξ²) {z : Ξ³} {l : filter Ξ±} {l' : filter Ξ²} (hf : tendsto β†Ώf (𝓝 z Γ—αΆ  l.map (proj_Icc a b h)) l') : tendsto β†Ώ(Icc_extend h ∘ f) (𝓝 z Γ—αΆ  l) l' := show tendsto (β†Ώf ∘ prod.map id (proj_Icc a b h)) (𝓝 z Γ—αΆ  l) l', from hf.comp $ tendsto_id.prod_map tendsto_map variables [topological_space Ξ±] [order_topology Ξ±] [topological_space Ξ²] @[continuity] lemma continuous_proj_Icc : continuous (proj_Icc a b h) := (continuous_const.max $ continuous_const.min continuous_id).subtype_mk _ lemma quotient_map_proj_Icc : quotient_map (proj_Icc a b h) := quotient_map_iff.2 ⟨proj_Icc_surjective h, Ξ» s, ⟨λ hs, hs.preimage continuous_proj_Icc, Ξ» hs, ⟨_, hs, by { ext, simp }⟩⟩⟩ @[simp] lemma continuous_Icc_extend_iff {f : Icc a b β†’ Ξ²} : continuous (Icc_extend h f) ↔ continuous f := quotient_map_proj_Icc.continuous_iff.symm /-- See Note [continuity lemma statement]. -/ lemma continuous.Icc_extend {f : Ξ³ β†’ Icc a b β†’ Ξ²} {g : Ξ³ β†’ Ξ±} (hf : continuous β†Ώf) (hg : continuous g) : continuous (Ξ» a, Icc_extend h (f a) (g a)) := hf.comp $ continuous_id.prod_mk $ continuous_proj_Icc.comp hg /-- A useful special case of `continuous.Icc_extend`. -/ @[continuity] lemma continuous.Icc_extend' {f : Icc a b β†’ Ξ²} (hf : continuous f) : continuous (Icc_extend h f) := hf.comp continuous_proj_Icc lemma continuous_at.Icc_extend {x : Ξ³} (f : Ξ³ β†’ Icc a b β†’ Ξ²) {g : Ξ³ β†’ Ξ±} (hf : continuous_at β†Ώf (x, proj_Icc a b h (g x))) (hg : continuous_at g x) : continuous_at (Ξ» a, Icc_extend h (f a) (g a)) x := show continuous_at (β†Ώf ∘ Ξ» x, (x, proj_Icc a b h (g x))) x, from continuous_at.comp hf $ continuous_at_id.prod $ continuous_proj_Icc.continuous_at.comp hg
4636ff8a91a882e4c3fee05a633c775fef9878e5
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/ordered_monoid.lean
b8037c6a48e3c50128e851ada5a73874164fedc8
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,862
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes HΓΆlzl -/ import algebra.group.with_one import algebra.group.type_tags import algebra.group.prod import algebra.order_functions import order.bounded_lattice import algebra.ordered_monoid_lemmas /-! # Ordered monoids This file develops the basics of ordered monoids. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true open function universe u variable {Ξ± : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that `a ≀ b β†’ c * a ≀ c * b` (multiplication is monotone) -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (Ξ± : Type*) extends comm_monoid Ξ±, partial_order Ξ± := (mul_le_mul_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c * a ≀ c * b) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that `a ≀ b β†’ c + a ≀ c + b` (addition is monotone) -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (Ξ± : Type*) extends add_comm_monoid Ξ±, partial_order Ξ± := (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) attribute [to_additive] ordered_comm_monoid section ordered_instances @[to_additive] instance ordered_comm_monoid.to_covariant_class_left (M : Type*) [ordered_comm_monoid M] : covariant_class M M (*) (≀) := { elim := Ξ» a b c bc, ordered_comm_monoid.mul_le_mul_left _ _ bc a } /- This instance can be proven with `by apply_instance`. However, `with_bot β„•` does not pick up a `covariant_class M M (function.swap (*)) (≀)` instance without it (see PR #7940). -/ @[to_additive] instance ordered_comm_monoid.to_covariant_class_right (M : Type*) [ordered_comm_monoid M] : covariant_class M M (swap (*)) (≀) := covariant_swap_mul_le_of_covariant_mul_le M end ordered_instances /-- An `ordered_comm_monoid` with one-sided 'division' in the sense that if `a ≀ b`, there is some `c` for which `a * c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/ class has_exists_mul_of_le (Ξ± : Type u) [ordered_comm_monoid Ξ±] : Prop := (exists_mul_of_le : βˆ€ {a b : Ξ±}, a ≀ b β†’ βˆƒ (c : Ξ±), b = a * c) /-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that if `a ≀ b`, then there is some `c` for which `a + c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/ class has_exists_add_of_le (Ξ± : Type u) [ordered_add_comm_monoid Ξ±] : Prop := (exists_add_of_le : βˆ€ {a b : Ξ±}, a ≀ b β†’ βˆƒ (c : Ξ±), b = a + c) attribute [to_additive] has_exists_mul_of_le export has_exists_mul_of_le (exists_mul_of_le) export has_exists_add_of_le (exists_add_of_le) /-- A linearly ordered additive commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_add_comm_monoid] class linear_ordered_add_comm_monoid (Ξ± : Type*) extends linear_order Ξ±, ordered_add_comm_monoid Ξ±. /-- A linearly ordered commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_comm_monoid, to_additive] class linear_ordered_comm_monoid (Ξ± : Type*) extends linear_order Ξ±, ordered_comm_monoid Ξ±. /-- A linearly ordered commutative monoid with a zero element. -/ class linear_ordered_comm_monoid_with_zero (Ξ± : Type*) extends linear_ordered_comm_monoid Ξ±, comm_monoid_with_zero Ξ± := (zero_le_one : (0 : Ξ±) ≀ 1) /-- A linearly ordered commutative monoid with an additively absorbing `⊀` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid order_top] class linear_ordered_add_comm_monoid_with_top (Ξ± : Type*) extends linear_ordered_add_comm_monoid Ξ±, order_top Ξ± := (top_add' : βˆ€ x : Ξ±, ⊀ + x = ⊀) section linear_ordered_add_comm_monoid_with_top variables [linear_ordered_add_comm_monoid_with_top Ξ±] {a b : Ξ±} @[simp] lemma top_add (a : Ξ±) : ⊀ + a = ⊀ := linear_ordered_add_comm_monoid_with_top.top_add' a @[simp] lemma add_top (a : Ξ±) : a + ⊀ = ⊀ := trans (add_comm _ _) (top_add _) -- TODO: Generalize to a not-yet-existing typeclass extending `linear_order` and `order_top` @[simp] lemma min_top_left (a : Ξ±) : min (⊀ : Ξ±) a = a := min_eq_right le_top @[simp] lemma min_top_right (a : Ξ±) : min a ⊀ = a := min_eq_left le_top end linear_ordered_add_comm_monoid_with_top /-- Pullback an `ordered_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.ordered_comm_monoid [ordered_comm_monoid Ξ±] {Ξ² : Type*} [has_one Ξ²] [has_mul Ξ²] (f : Ξ² β†’ Ξ±) (hf : function.injective f) (one : f 1 = 1) (mul : βˆ€ x y, f (x * y) = f x * f y) : ordered_comm_monoid Ξ² := { mul_le_mul_left := Ξ» a b ab c, show f (c * a) ≀ f (c * b), by { rw [mul, mul], apply mul_le_mul_left', exact ab }, ..partial_order.lift f hf, ..hf.comm_monoid f one mul } /-- Pullback a `linear_ordered_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid Ξ±] {Ξ² : Type*} [has_one Ξ²] [has_mul Ξ²] (f : Ξ² β†’ Ξ±) (hf : function.injective f) (one : f 1 = 1) (mul : βˆ€ x y, f (x * y) = f x * f y) : linear_ordered_comm_monoid Ξ² := { .. hf.ordered_comm_monoid f one mul, .. linear_order.lift f hf } lemma bit0_pos [ordered_add_comm_monoid Ξ±] {a : Ξ±} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid Ξ±] [preorder Ξ±] : preorder (units Ξ±) := preorder.lift (coe : units Ξ± β†’ Ξ±) @[simp, norm_cast, to_additive] theorem coe_le_coe [monoid Ξ±] [preorder Ξ±] {a b : units Ξ±} : (a : Ξ±) ≀ b ↔ a ≀ b := iff.rfl -- should `to_additive` do this? attribute [norm_cast] add_units.coe_le_coe @[simp, norm_cast, to_additive] theorem coe_lt_coe [monoid Ξ±] [preorder Ξ±] {a b : units Ξ±} : (a : Ξ±) < b ↔ a < b := iff.rfl attribute [norm_cast] add_units.coe_lt_coe @[to_additive] instance [monoid Ξ±] [partial_order Ξ±] : partial_order (units Ξ±) := partial_order.lift coe units.ext @[to_additive] instance [monoid Ξ±] [linear_order Ξ±] : linear_order (units Ξ±) := linear_order.lift coe units.ext @[simp, norm_cast, to_additive] theorem max_coe [monoid Ξ±] [linear_order Ξ±] {a b : units Ξ±} : (↑(max a b) : Ξ±) = max a b := by by_cases b ≀ a; simp [max, h] attribute [norm_cast] add_units.max_coe @[simp, norm_cast, to_additive] theorem min_coe [monoid Ξ±] [linear_order Ξ±] {a b : units Ξ±} : (↑(min a b) : Ξ±) = min a b := by by_cases a ≀ b; simp [min, h] attribute [norm_cast] add_units.min_coe end units namespace with_zero local attribute [semireducible] with_zero instance [preorder Ξ±] : preorder (with_zero Ξ±) := with_bot.preorder instance [partial_order Ξ±] : partial_order (with_zero Ξ±) := with_bot.partial_order instance [partial_order Ξ±] : order_bot (with_zero Ξ±) := with_bot.order_bot lemma zero_le [partial_order Ξ±] (a : with_zero Ξ±) : 0 ≀ a := order_bot.bot_le a lemma zero_lt_coe [preorder Ξ±] (a : Ξ±) : (0 : with_zero Ξ±) < a := with_bot.bot_lt_coe a @[simp, norm_cast] lemma coe_lt_coe [partial_order Ξ±] {a b : Ξ±} : (a : with_zero Ξ±) < b ↔ a < b := with_bot.coe_lt_coe @[simp, norm_cast] lemma coe_le_coe [partial_order Ξ±] {a b : Ξ±} : (a : with_zero Ξ±) ≀ b ↔ a ≀ b := with_bot.coe_le_coe instance [lattice Ξ±] : lattice (with_zero Ξ±) := with_bot.lattice instance [linear_order Ξ±] : linear_order (with_zero Ξ±) := with_bot.linear_order lemma mul_le_mul_left {Ξ± : Type u} [has_mul Ξ±] [preorder Ξ±] [covariant_class Ξ± Ξ± (*) (≀)] : βˆ€ (a b : with_zero Ξ±), a ≀ b β†’ βˆ€ (c : with_zero Ξ±), c * a ≀ c * b := begin rintro (_ | a) (_ | b) h (_ | c); try { exact Ξ» f hf, option.no_confusion hf }, { exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))}, { simp_rw [some_eq_coe] at h ⊒, norm_cast at h ⊒, exact covariant_class.elim _ h } end lemma lt_of_mul_lt_mul_left {Ξ± : Type u} [has_mul Ξ±] [partial_order Ξ±] [contravariant_class Ξ± Ξ± (*) (<)] : βˆ€ (a b c : with_zero Ξ±), a * b < a * c β†’ b < c := begin rintro (_ | a) (_ | b) (_ | c) h; try { exact false.elim (lt_irrefl none h) }, { exact with_zero.zero_lt_coe c }, { exact false.elim (not_le_of_lt h (with_zero.zero_le _)) }, { simp_rw [some_eq_coe] at h ⊒, norm_cast at h ⊒, apply lt_of_mul_lt_mul_left' h } end instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (with_zero Ξ±) := { mul_le_mul_left := with_zero.mul_le_mul_left, ..with_zero.comm_monoid_with_zero, ..with_zero.partial_order } /- Note 1 : the below is not an instance because it requires `zero_le`. It seems like a rather pathological definition because Ξ± already has a zero. Note 2 : there is no multiplicative analogue because it does not seem necessary. Mathematicians might be more likely to use the order-dual version, where all elements are ≀ 1 and then 1 is the top element. -/ /-- If `0` is the least element in `Ξ±`, then `with_zero Ξ±` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid Ξ±] (zero_le : βˆ€ a : Ξ±, 0 ≀ a) : ordered_add_comm_monoid (with_zero Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b h c ca hβ‚‚, cases b with b, { rw le_antisymm h bot_le at hβ‚‚, exact ⟨_, hβ‚‚, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at hβ‚‚, simp at hβ‚‚, simp [hβ‚‚], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at hβ‚‚; simp [-add_comm] at hβ‚‚; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one Ξ±] @[to_additive] instance : has_one (with_top Ξ±) := ⟨(1 : Ξ±)⟩ @[simp, to_additive] lemma coe_one : ((1 : Ξ±) : with_top Ξ±) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : Ξ±} : (a : with_top Ξ±) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : Ξ±} : 1 = (a : with_top Ξ±) ↔ a = 1 := trans eq_comm coe_eq_one attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊀ β‰  (1 : with_top Ξ±) . @[simp, to_additive] theorem one_ne_top : (1 : with_top Ξ±) β‰  ⊀ . end has_one instance [has_add Ξ±] : has_add (with_top Ξ±) := ⟨λ o₁ oβ‚‚, o₁.bind (Ξ» a, oβ‚‚.map (Ξ» b, a + b))⟩ @[norm_cast] lemma coe_add [has_add Ξ±] {a b : Ξ±} : ((a + b : Ξ±) : with_top Ξ±) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add Ξ±] {a : Ξ±} : ((bit0 a : Ξ±) : with_top Ξ±) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add Ξ±] [has_one Ξ±] {a : Ξ±} : ((bit1 a : Ξ±) : with_top Ξ±) = bit1 a := rfl @[simp] lemma add_top [has_add Ξ±] : βˆ€{a : with_top Ξ±}, a + ⊀ = ⊀ | none := rfl | (some a) := rfl @[simp] lemma top_add [has_add Ξ±] {a : with_top Ξ±} : ⊀ + a = ⊀ := rfl lemma add_eq_top [has_add Ξ±] {a b : with_top Ξ±} : a + b = ⊀ ↔ a = ⊀ ∨ b = ⊀ := by cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add, ←with_zero.coe_add] lemma add_lt_top [has_add Ξ±] [partial_order Ξ±] {a b : with_top Ξ±} : a + b < ⊀ ↔ a < ⊀ ∧ b < ⊀ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] lemma add_eq_coe [has_add Ξ±] : βˆ€ {a b : with_top Ξ±} {c : Ξ±}, a + b = c ↔ βˆƒ (a' b' : Ξ±), ↑a' = a ∧ ↑b' = b ∧ a' + b' = c | none b c := by simp [none_eq_top] | (some a) none c := by simp [none_eq_top] | (some a) (some b) c := by simp only [some_eq_coe, ← coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left] instance [add_semigroup Ξ±] : add_semigroup (with_top Ξ±) := { add_assoc := begin repeat { refine with_top.rec_top_coe _ _; try { intro }}; simp [←with_top.coe_add, add_assoc] end, ..with_top.has_add } instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_top Ξ±) := { add_comm := begin repeat { refine with_top.rec_top_coe _ _; try { intro }}; simp [←with_top.coe_add, add_comm] end, ..with_top.add_semigroup } instance [add_monoid Ξ±] : add_monoid (with_top Ξ±) := { zero_add := begin refine with_top.rec_top_coe _ _, { simpa }, { intro, rw [←with_top.coe_zero, ←with_top.coe_add, zero_add] } end, add_zero := begin refine with_top.rec_top_coe _ _, { simpa }, { intro, rw [←with_top.coe_zero, ←with_top.coe_add, add_zero] } end, ..with_top.has_zero, ..with_top.add_semigroup } instance [add_comm_monoid Ξ±] : add_comm_monoid (with_top Ξ±) := { ..with_top.add_monoid, ..with_top.add_comm_semigroup } instance [ordered_add_comm_monoid Ξ±] : ordered_add_comm_monoid (with_top Ξ±) := { add_le_add_left := begin rintros a b h (_|c), { simp [none_eq_top] }, rcases b with (_|b), { simp [none_eq_top] }, rcases le_coe_iff.1 h with ⟨a, rfl, h⟩, simp only [some_eq_coe, ← coe_add, coe_le_coe] at h ⊒, exact add_le_add_left h c end, ..with_top.partial_order, ..with_top.add_comm_monoid } instance [linear_ordered_add_comm_monoid Ξ±] : linear_ordered_add_comm_monoid_with_top (with_top Ξ±) := { top_add' := Ξ» x, with_top.top_add, ..with_top.order_top, ..with_top.linear_order, ..with_top.ordered_add_comm_monoid, ..option.nontrivial } /-- Coercion from `Ξ±` to `with_top Ξ±` as an `add_monoid_hom`. -/ def coe_add_hom [add_monoid Ξ±] : Ξ± β†’+ with_top Ξ± := ⟨coe, rfl, Ξ» _ _, rfl⟩ @[simp] lemma coe_coe_add_hom [add_monoid Ξ±] : ⇑(coe_add_hom : Ξ± β†’+ with_top Ξ±) = coe := rfl @[simp] lemma zero_lt_top [ordered_add_comm_monoid Ξ±] : (0 : with_top Ξ±) < ⊀ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid Ξ±] (a : Ξ±) : (0 : with_top Ξ±) < a ↔ 0 < a := coe_lt_coe end with_top namespace with_bot instance [has_zero Ξ±] : has_zero (with_bot Ξ±) := with_top.has_zero instance [has_one Ξ±] : has_one (with_bot Ξ±) := with_top.has_one instance [add_semigroup Ξ±] : add_semigroup (with_bot Ξ±) := with_top.add_semigroup instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_bot Ξ±) := with_top.add_comm_semigroup instance [add_monoid Ξ±] : add_monoid (with_bot Ξ±) := with_top.add_monoid instance [add_comm_monoid Ξ±] : add_comm_monoid (with_bot Ξ±) := with_top.add_comm_monoid instance [ordered_add_comm_monoid Ξ±] : ordered_add_comm_monoid (with_bot Ξ±) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b h c ca hβ‚‚, cases c with c, {cases hβ‚‚}, cases a with a; cases hβ‚‚, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end instance [linear_ordered_add_comm_monoid Ξ±] : linear_ordered_add_comm_monoid (with_bot Ξ±) := { ..with_bot.linear_order, ..with_bot.ordered_add_comm_monoid } -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero Ξ±] : ((0 : Ξ±) : with_bot Ξ±) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one Ξ±] : ((1 : Ξ±) : with_bot Ξ±) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {Ξ± : Type*} [add_monoid Ξ±] {a : Ξ±} : (a : with_bot Ξ±) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup Ξ±] (a b : Ξ±) : ((a + b : Ξ±) : with_bot Ξ±) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup Ξ±] {a : Ξ±} : ((bit0 a : Ξ±) : with_bot Ξ±) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup Ξ±] [has_one Ξ±] {a : Ξ±} : ((bit1 a : Ξ±) : with_bot Ξ±) = bit1 a := by norm_cast @[simp] lemma bot_add [add_semigroup Ξ±] (a : with_bot Ξ±) : βŠ₯ + a = βŠ₯ := rfl @[simp] lemma add_bot [add_semigroup Ξ±] (a : with_bot Ξ±) : a + βŠ₯ = βŠ₯ := by cases a; refl @[simp] lemma add_eq_bot [add_semigroup Ξ±] {m n : with_bot Ξ±} : m + n = βŠ₯ ↔ m = βŠ₯ ∨ n = βŠ₯ := with_top.add_eq_top end with_bot /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≀ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `ordered_add_comm_group`s. -/ @[protect_proj, ancestor ordered_add_comm_monoid order_bot] class canonically_ordered_add_monoid (Ξ± : Type*) extends ordered_add_comm_monoid Ξ±, order_bot Ξ± := (le_iff_exists_add : βˆ€ a b : Ξ±, a ≀ b ↔ βˆƒ c, b = a + c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≀ b` iff there exists `c` with `b = a * c`. Examples seem rare; it seems more likely that the `order_dual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≀ 1 seem to be more natural that collections of all things β‰₯ 1). -/ @[protect_proj, ancestor ordered_comm_monoid order_bot, to_additive] class canonically_ordered_monoid (Ξ± : Type*) extends ordered_comm_monoid Ξ±, order_bot Ξ± := (le_iff_exists_mul : βˆ€ a b : Ξ±, a ≀ b ↔ βˆƒ c, b = a * c) section canonically_ordered_monoid variables [canonically_ordered_monoid Ξ±] {a b c d : Ξ±} @[to_additive] lemma le_iff_exists_mul : a ≀ b ↔ βˆƒc, b = a * c := canonically_ordered_monoid.le_iff_exists_mul a b @[to_additive] lemma self_le_mul_right (a b : Ξ±) : a ≀ a * b := le_iff_exists_mul.mpr ⟨b, rfl⟩ @[to_additive] lemma self_le_mul_left (a b : Ξ±) : a ≀ b * a := by { rw [mul_comm], exact self_le_mul_right a b } @[simp, to_additive zero_le] lemma one_le (a : Ξ±) : 1 ≀ a := le_iff_exists_mul.mpr ⟨a, (one_mul _).symm⟩ @[simp, to_additive] lemma bot_eq_one : (βŠ₯ : Ξ±) = 1 := le_antisymm bot_le (one_le βŠ₯) @[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 := mul_eq_one_iff' (one_le _) (one_le _) @[simp, to_additive] lemma le_one_iff_eq_one : a ≀ 1 ↔ a = 1 := iff.intro (assume h, le_antisymm h (one_le a)) (assume h, h β–Έ le_refl a) @[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a β‰  1 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (one_le _) hne.symm @[to_additive] lemma exists_pos_mul_of_lt (h : a < b) : βˆƒ c > 1, a * c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le, refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end @[to_additive] lemma le_mul_left (h : a ≀ c) : a ≀ b * c := calc a = 1 * a : by simp ... ≀ b * c : mul_le_mul' (one_le _) h @[to_additive] lemma le_mul_self : a ≀ b * a := le_mul_left (le_refl a) @[to_additive] lemma le_mul_right (h : a ≀ b) : a ≀ b * c := calc a = a * 1 : by simp ... ≀ b * c : mul_le_mul' h (one_le _) @[to_additive] lemma le_self_mul : a ≀ a * c := le_mul_right (le_refl a) @[to_additive] lemma lt_iff_exists_mul [covariant_class Ξ± Ξ± (*) (<)] : a < b ↔ βˆƒ c > 1, b = a * c := begin simp_rw [lt_iff_le_and_ne, and_comm, le_iff_exists_mul, ← exists_and_distrib_left, exists_prop], apply exists_congr, intro c, rw [and.congr_left_iff, gt_iff_lt], rintro rfl, split, { rw [one_lt_iff_ne_one], apply mt, rintro rfl, rw [mul_one] }, { rw [← (self_le_mul_right a c).lt_iff_ne], apply lt_mul_of_one_lt_right' } end -- This instance looks absurd: a monoid already has a zero /-- Adding a new zero to a canonically ordered additive monoid produces another one. -/ instance with_zero.canonically_ordered_add_monoid {Ξ± : Type u} [canonically_ordered_add_monoid Ξ±] : canonically_ordered_add_monoid (with_zero Ξ±) := { le_iff_exists_add := Ξ» a b, begin apply with_zero.cases_on a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, apply with_zero.cases_on b, { intro b', refine iff_of_false (mt (le_antisymm bot_le) (by simp)) (not_exists.mpr (Ξ» c, _)), apply with_zero.cases_on c; simp [←with_zero.coe_add] }, { simp only [le_iff_exists_add, with_zero.coe_le_coe], intros, split; rintro ⟨c, h⟩, { exact ⟨c, congr_arg coe h⟩ }, { induction c using with_zero.cases_on, { refine ⟨0, _⟩, simpa using h }, { refine ⟨c, _⟩, simpa [←with_zero.coe_add] using h } } } end, .. with_zero.order_bot, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid {Ξ± : Type u} [canonically_ordered_add_monoid Ξ±] : canonically_ordered_add_monoid (with_top Ξ±) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≀ ⊀ ↔ βˆƒc, ⊀ = a + c, by simp; refine ⟨⊀, _⟩; cases a; refl | (some a), (some b) := show (a:with_top Ξ±) ≀ ↑b ↔ βˆƒc:with_top Ξ±, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊀ : with_top Ξ±) ≀ b ↔ βˆƒc:with_top Ξ±, ↑b = ⊀ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } @[priority 100, to_additive] instance canonically_ordered_monoid.has_exists_mul_of_le (Ξ± : Type u) [canonically_ordered_monoid Ξ±] : has_exists_mul_of_le Ξ± := { exists_mul_of_le := Ξ» a b hab, le_iff_exists_mul.mp hab } end canonically_ordered_monoid lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m := lt_of_le_of_lt (zero_le _) h /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_add_monoid linear_order] class canonically_linear_ordered_add_monoid (Ξ± : Type*) extends canonically_ordered_add_monoid Ξ±, linear_order Ξ± /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive] class canonically_linear_ordered_monoid (Ξ± : Type*) extends canonically_ordered_monoid Ξ±, linear_order Ξ± section canonically_linear_ordered_monoid variables [canonically_linear_ordered_monoid Ξ±] @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_linear_ordered_monoid.semilattice_sup_bot : semilattice_sup_bot Ξ± := { ..lattice_of_linear_order, ..canonically_ordered_monoid.to_order_bot Ξ± } instance with_top.canonically_linear_ordered_add_monoid (Ξ± : Type*) [canonically_linear_ordered_add_monoid Ξ±] : canonically_linear_ordered_add_monoid (with_top Ξ±) := { .. (infer_instance : canonically_ordered_add_monoid (with_top Ξ±)), .. (infer_instance : linear_order (with_top Ξ±)) } @[to_additive] lemma min_mul_distrib (a b c : Ξ±) : min a (b * c) = min a (min a b * min a c) := begin cases le_total a b with hb hb, { simp [hb, le_mul_right] }, { cases le_total a c with hc hc, { simp [hc, le_mul_left] }, { simp [hb, hc] } } end @[to_additive] lemma min_mul_distrib' (a b c : Ξ±) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b @[simp, to_additive] lemma one_min (a : Ξ±) : min 1 a = 1 := min_eq_left (one_le a) @[simp, to_additive] lemma min_one (a : Ξ±) : min a 1 = 1 := min_eq_right (one_le a) end canonically_linear_ordered_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and monotone. -/ @[protect_proj, ancestor add_cancel_comm_monoid partial_order] class ordered_cancel_add_comm_monoid (Ξ± : Type u) extends add_cancel_comm_monoid Ξ±, partial_order Ξ± := (add_le_add_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c + a ≀ c + b) (le_of_add_le_add_left : βˆ€ a b c : Ξ±, a + b ≀ a + c β†’ b ≀ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor cancel_comm_monoid partial_order, to_additive] class ordered_cancel_comm_monoid (Ξ± : Type u) extends cancel_comm_monoid Ξ±, partial_order Ξ± := (mul_le_mul_left : βˆ€ a b : Ξ±, a ≀ b β†’ βˆ€ c : Ξ±, c * a ≀ c * b) (le_of_mul_le_mul_left : βˆ€ a b c : Ξ±, a * b ≀ a * c β†’ b ≀ c) section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid Ξ±] {a b c d : Ξ±} @[to_additive] lemma ordered_cancel_comm_monoid.lt_of_mul_lt_mul_left : βˆ€ a b c : Ξ±, a * b < a * c β†’ b < c := Ξ» a b c h, lt_of_le_not_le (ordered_cancel_comm_monoid.le_of_mul_le_mul_left a b c h.le) $ mt (Ξ» h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h) @[to_additive] instance ordered_cancel_comm_monoid.to_contravariant_class_left (M : Type*) [ordered_cancel_comm_monoid M] : contravariant_class M M (*) (<) := { elim := Ξ» a b c, ordered_cancel_comm_monoid.lt_of_mul_lt_mul_left _ _ _ } /- This instance can be proven with `by apply_instance`. However, by analogy with the instance `ordered_cancel_comm_monoid.to_covariant_class_right` above, I imagine that without this instance, some Type would not have a `contravariant_class M M (function.swap (*)) (<)` instance. -/ @[to_additive] instance ordered_cancel_comm_monoid.to_contravariant_class_right (M : Type*) [ordered_cancel_comm_monoid M] : contravariant_class M M (swap (*)) (<) := contravariant_swap_mul_lt_of_contravariant_mul_lt M @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid Ξ± := { ..β€Ήordered_cancel_comm_monoid Ξ±β€Ί } /-- Pullback an `ordered_cancel_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_cancel_add_comm_monoid "Pullback an `ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.ordered_cancel_comm_monoid {Ξ² : Type*} [has_one Ξ²] [has_mul Ξ²] (f : Ξ² β†’ Ξ±) (hf : function.injective f) (one : f 1 = 1) (mul : βˆ€ x y, f (x * y) = f x * f y) : ordered_cancel_comm_monoid Ξ² := { le_of_mul_le_mul_left := Ξ» a b c (bc : f (a * b) ≀ f (a * c)), (mul_le_mul_iff_left (f a)).mp (by rwa [← mul, ← mul]), ..hf.left_cancel_semigroup f mul, ..hf.ordered_comm_monoid f one mul } end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid Ξ±] lemma with_top.add_lt_add_iff_left : βˆ€{a b c : with_top Ξ±}, a < ⊀ β†’ (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊀ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_bot.add_lt_add_iff_left : βˆ€{a b c : with_bot Ξ±}, βŠ₯ < a β†’ (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl βŠ₯ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_bot.none_eq_bot, with_bot.some_eq_coe, with_bot.bot_lt_coe, with_bot.coe_lt_coe], { norm_cast, exact with_bot.bot_lt_coe _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top Ξ±} : a < ⊀ β†’ (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c lemma with_bot.add_lt_add_iff_right {a b c : with_bot Ξ±} : βŠ₯ < a β†’ (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_bot.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-! Some lemmas about types that have an ordering and a binary operation, with no rules relating them. -/ @[to_additive] lemma fn_min_mul_fn_max {Ξ²} [linear_order Ξ±] [comm_semigroup Ξ²] (f : Ξ± β†’ Ξ²) (n m : Ξ±) : f (min n m) * f (max n m) = f n * f m := by { cases le_total n m with h h; simp [h, mul_comm] } @[to_additive] lemma min_mul_max [linear_order Ξ±] [comm_semigroup Ξ±] (n m : Ξ±) : min n m * max n m = n * m := fn_min_mul_fn_max id n m /-- A linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_add_comm_monoid linear_ordered_add_comm_monoid] class linear_ordered_cancel_add_comm_monoid (Ξ± : Type u) extends ordered_cancel_add_comm_monoid Ξ±, linear_ordered_add_comm_monoid Ξ± /-- A linearly ordered cancellative commutative monoid is a commutative monoid with a linear order in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_comm_monoid linear_ordered_comm_monoid, to_additive] class linear_ordered_cancel_comm_monoid (Ξ± : Type u) extends ordered_cancel_comm_monoid Ξ±, linear_ordered_comm_monoid Ξ± section covariant_class_mul_le variables [linear_order Ξ±] section has_mul variable [has_mul Ξ±] section left variable [covariant_class Ξ± Ξ± (*) (≀)] @[to_additive] lemma min_mul_mul_left (a b c : Ξ±) : min (a * b) (a * c) = a * min b c := (monotone_id.const_mul' a).map_min.symm @[to_additive] lemma max_mul_mul_left (a b c : Ξ±) : max (a * b) (a * c) = a * max b c := (monotone_id.const_mul' a).map_max.symm end left section right variable [covariant_class Ξ± Ξ± (function.swap (*)) (≀)] @[to_additive] lemma min_mul_mul_right (a b c : Ξ±) : min (a * c) (b * c) = min a b * c := (monotone_id.mul_const' c).map_min.symm @[to_additive] lemma max_mul_mul_right (a b c : Ξ±) : max (a * c) (b * c) = max a b * c := (monotone_id.mul_const' c).map_max.symm end right end has_mul variable [monoid Ξ±] @[to_additive] lemma min_le_mul_of_one_le_right [covariant_class Ξ± Ξ± (*) (≀)] {a b : Ξ±} (hb : 1 ≀ b) : min a b ≀ a * b := min_le_iff.2 $ or.inl $ le_mul_of_one_le_right' hb @[to_additive] lemma min_le_mul_of_one_le_left [covariant_class Ξ± Ξ± (function.swap (*)) (≀)] {a b : Ξ±} (ha : 1 ≀ a) : min a b ≀ a * b := min_le_iff.2 $ or.inr $ le_mul_of_one_le_left' ha @[to_additive] lemma max_le_mul_of_one_le [covariant_class Ξ± Ξ± (*) (≀)] [covariant_class Ξ± Ξ± (function.swap (*)) (≀)] {a b : Ξ±} (ha : 1 ≀ a) (hb : 1 ≀ b) : max a b ≀ a * b := max_le_iff.2 ⟨le_mul_of_one_le_right' hb, le_mul_of_one_le_left' ha⟩ end covariant_class_mul_le section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid Ξ±] /-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_cancel_add_comm_monoid "Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_cancel_comm_monoid {Ξ² : Type*} [has_one Ξ²] [has_mul Ξ²] (f : Ξ² β†’ Ξ±) (hf : function.injective f) (one : f 1 = 1) (mul : βˆ€ x y, f (x * y) = f x * f y) : linear_ordered_cancel_comm_monoid Ξ² := { ..hf.linear_ordered_comm_monoid f one mul, ..hf.ordered_cancel_comm_monoid f one mul } end linear_ordered_cancel_comm_monoid namespace order_dual @[to_additive] instance [h : has_mul Ξ±] : has_mul (order_dual Ξ±) := h @[to_additive] instance [h : has_one Ξ±] : has_one (order_dual Ξ±) := h @[to_additive] instance [h : monoid Ξ±] : monoid (order_dual Ξ±) := h @[to_additive] instance [h : comm_monoid Ξ±] : comm_monoid (order_dual Ξ±) := h @[to_additive] instance [h : cancel_comm_monoid Ξ±] : cancel_comm_monoid (order_dual Ξ±) := h @[to_additive] instance contravariant_class_mul_le [has_le Ξ±] [has_mul Ξ±] [c : contravariant_class Ξ± Ξ± (*) (≀)] : contravariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (≀) := ⟨c.1.flip⟩ @[to_additive] instance covariant_class_mul_le [has_le Ξ±] [has_mul Ξ±] [c : covariant_class Ξ± Ξ± (*) (≀)] : covariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (≀) := ⟨c.1.flip⟩ @[to_additive] instance contravariant_class_swap_mul_le [has_le Ξ±] [has_mul Ξ±] [c : contravariant_class Ξ± Ξ± (swap (*)) (≀)] : contravariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (≀) := ⟨c.1.flip⟩ @[to_additive] instance covariant_class_swap_mul_le [has_le Ξ±] [has_mul Ξ±] [c : covariant_class Ξ± Ξ± (swap (*)) (≀)] : covariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (≀) := ⟨c.1.flip⟩ @[to_additive] instance contravariant_class_mul_lt [has_lt Ξ±] [has_mul Ξ±] [c : contravariant_class Ξ± Ξ± (*) (<)] : contravariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (<) := ⟨c.1.flip⟩ @[to_additive] instance covariant_class_mul_lt [has_lt Ξ±] [has_mul Ξ±] [c : covariant_class Ξ± Ξ± (*) (<)] : covariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (<) := ⟨c.1.flip⟩ @[to_additive] instance contravariant_class_swap_mul_lt [has_lt Ξ±] [has_mul Ξ±] [c : contravariant_class Ξ± Ξ± (swap (*)) (<)] : contravariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (<) := ⟨c.1.flip⟩ @[to_additive] instance covariant_class_swap_mul_lt [has_lt Ξ±] [has_mul Ξ±] [c : covariant_class Ξ± Ξ± (swap (*)) (<)] : covariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (<) := ⟨c.1.flip⟩ @[to_additive] instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (order_dual Ξ±) := { mul_le_mul_left := Ξ» a b h c, mul_le_mul_left' h c, .. order_dual.partial_order Ξ±, .. order_dual.comm_monoid } @[to_additive ordered_cancel_add_comm_monoid.to_contravariant_class] instance ordered_cancel_comm_monoid.to_contravariant_class [ordered_cancel_comm_monoid Ξ±] : contravariant_class (order_dual Ξ±) (order_dual Ξ±) has_mul.mul has_le.le := { elim := Ξ» a b c bc, (ordered_cancel_comm_monoid.le_of_mul_le_mul_left a c b (dual_le.mp bc)) } @[to_additive] instance [ordered_cancel_comm_monoid Ξ±] : ordered_cancel_comm_monoid (order_dual Ξ±) := { le_of_mul_le_mul_left := Ξ» a b c : Ξ±, le_of_mul_le_mul_left', .. order_dual.ordered_comm_monoid, .. order_dual.cancel_comm_monoid } @[to_additive] instance [linear_ordered_cancel_comm_monoid Ξ±] : linear_ordered_cancel_comm_monoid (order_dual Ξ±) := { .. order_dual.linear_order Ξ±, .. order_dual.ordered_cancel_comm_monoid } @[to_additive] instance [linear_ordered_comm_monoid Ξ±] : linear_ordered_comm_monoid (order_dual Ξ±) := { .. order_dual.linear_order Ξ±, .. order_dual.ordered_comm_monoid } end order_dual namespace prod variables {M N : Type*} @[to_additive] instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] : ordered_cancel_comm_monoid (M Γ— N) := { mul_le_mul_left := Ξ» a b h c, ⟨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _⟩, le_of_mul_le_mul_left := Ξ» a b c h, ⟨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2⟩, .. prod.cancel_comm_monoid, .. prod.partial_order M N } end prod section type_tags instance : Ξ  [preorder Ξ±], preorder (multiplicative Ξ±) := id instance : Ξ  [preorder Ξ±], preorder (additive Ξ±) := id instance : Ξ  [partial_order Ξ±], partial_order (multiplicative Ξ±) := id instance : Ξ  [partial_order Ξ±], partial_order (additive Ξ±) := id instance : Ξ  [linear_order Ξ±], linear_order (multiplicative Ξ±) := id instance : Ξ  [linear_order Ξ±], linear_order (additive Ξ±) := id instance [ordered_add_comm_monoid Ξ±] : ordered_comm_monoid (multiplicative Ξ±) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left Ξ± _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid Ξ±] : ordered_add_comm_monoid (additive Ξ±) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left Ξ± _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid Ξ±] : ordered_cancel_comm_monoid (multiplicative Ξ±) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left Ξ± _, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid Ξ±] : ordered_cancel_add_comm_monoid (additive Ξ±) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left Ξ± _, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_monoid Ξ±] : linear_ordered_comm_monoid (multiplicative Ξ±) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_monoid } instance [linear_ordered_comm_monoid Ξ±] : linear_ordered_add_comm_monoid (additive Ξ±) := { ..additive.linear_order, ..additive.ordered_add_comm_monoid } end type_tags
d863e322713fa99e40aa5326062b7aed225ee364
8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4
/software_foundations_lists.lean
190f8ed4fc9ca6e83239e6a2ee5378e15e4f400d
[]
no_license
picrin/lean
420f4d08bb3796b911d56d0938e4410e1da0e072
3d10c509c79704aa3a88ebfb24d08b30ce1137cc
refs/heads/master
1,611,166,610,726
1,536,671,438,000
1,536,671,438,000
60,029,899
0
0
null
null
null
null
UTF-8
Lean
false
false
1,377
lean
--variable alpha : Type --variable a : alpha --variable depends_on_a : alpha β†’ Type --variable b : depends_on_a a --#reduce (sigma.mk a b).2 inductive natprod : Type | pair : nat β†’ nat β†’ natprod definition first : natprod β†’ nat := Ξ» (x : natprod), natprod.rec_on x (Ξ» a b : nat, a) definition second : natprod β†’ nat := Ξ» (x : natprod), natprod.rec_on x (Ξ» a b : nat, b) definition swap_natprod : natprod β†’ natprod := Ξ» (x : natprod), natprod.pair (second x) (first x) inductive natlist : Type | nil : natlist | cons : nat β†’ natlist β†’ natlist definition list_sum : natlist β†’ nat := Ξ» list : natlist, natlist.rec_on list 0 (Ξ» list_element : nat, Ξ» previous_list : natlist, Ξ» IH: nat, list_element + IH) open natlist #reduce list_sum $ cons 2 $ cons 2 nil #eval list_sum $ cons 4 $ cons 3 $ cons 2 nil definition surjective_pairing (a : nat) (b : nat) (p : natprod) : p = natprod.pair (first p) (second p) := natprod.rec_on p (Ξ» a a_1 : nat, eq.refl (natprod.pair a a_1)) definition surjective_swap (a : nat) (b : nat) (p : natprod) : swap_natprod p = natprod.pair (second p) (first p) := natprod.rec_on p (Ξ» a a_1 : nat, eq.refl (natprod.pair a_1 a)) #reduce first (natprod.pair 3 4) --#check cons 5 $ cons 4 $ cons 3 nil --#reduce cons 5 $ cons 4 $ cons 3 nil --#reduce repeat 5 4
00a3272e9da5cf7dd1725dea00b419dcbe3c2cc1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/KeyedDeclsAttribute.lean
c1dd36816b970fd9af85e96d9223963a1d4c4071
[ "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
6,629
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Attributes import Lean.Compiler.InitAttr import Lean.ToExpr import Lean.ScopedEnvExtension import Lean.Compiler.IR.CompilerM /-! A builder for attributes that are applied to declarations of a common type and group them by the given attribute argument (an arbitrary `Name`, currently). Also creates a second "builtin" attribute used for bootstrapping, which saves the applied declarations in an `IO.Ref` instead of an environment extension. Used to register elaborators, macros, tactics, and delaborators. -/ namespace Lean namespace KeyedDeclsAttribute -- could be a parameter as well, but right now it's all names abbrev Key := Name /-- `KeyedDeclsAttribute` definition. Important: `mkConst valueTypeName` and `Ξ³` must be definitionally equal. -/ structure Def (Ξ³ : Type) where builtinName : Name := Name.anonymous -- Builtin attribute name, if any (e.g., `builtinTermElab) name : Name -- Attribute name (e.g., `termElab) descr : String -- Attribute description valueTypeName : Name -- Convert `Syntax` into a `Key`, the default implementation expects an identifier. evalKey : Bool β†’ Syntax β†’ AttrM Key := fun builtin stx => Attribute.Builtin.getId stx deriving Inhabited structure OLeanEntry where key : Key decl : Name -- Name of a declaration stored in the environment which has type `mkConst Def.valueTypeName`. deriving Inhabited structure AttributeEntry (Ξ³ : Type) extends OLeanEntry where /- Recall that we cannot store `Ξ³` into .olean files because it is a closure. Given `OLeanEntry.decl`, we convert it into a `Ξ³` by using the unsafe function `evalConstCheck`. -/ value : Ξ³ abbrev Table (Ξ³ : Type) := SMap Key (List (AttributeEntry Ξ³)) structure ExtensionState (Ξ³ : Type) where newEntries : List OLeanEntry := [] table : Table Ξ³ := {} deriving Inhabited abbrev Extension (Ξ³ : Type) := ScopedEnvExtension OLeanEntry (AttributeEntry Ξ³) (ExtensionState Ξ³) end KeyedDeclsAttribute structure KeyedDeclsAttribute (Ξ³ : Type) where defn : KeyedDeclsAttribute.Def Ξ³ -- imported/builtin instances tableRef : IO.Ref (KeyedDeclsAttribute.Table Ξ³) -- instances from current module ext : KeyedDeclsAttribute.Extension Ξ³ deriving Inhabited namespace KeyedDeclsAttribute def Table.insert {Ξ³ : Type} (table : Table Ξ³) (v : AttributeEntry Ξ³) : Table Ξ³ := match table.find? v.key with | some vs => SMap.insert table v.key (v::vs) | none => SMap.insert table v.key [v] def addBuiltin {Ξ³} (attr : KeyedDeclsAttribute Ξ³) (key : Key) (decl : Name) (value : Ξ³) : IO Unit := attr.tableRef.modify fun m => m.insert { key, decl, value } /-- def _regBuiltin$(declName) : IO Unit := @addBuiltin $(mkConst valueTypeName) $(mkConst attrDeclName) $(key) $(declName) $(mkConst declName) -/ def declareBuiltin {Ξ³} (df : Def Ξ³) (attrDeclName : Name) (env : Environment) (key : Key) (declName : Name) : IO Environment := let name := `_regBuiltin ++ declName let type := mkApp (mkConst `IO) (mkConst `Unit) let val := mkAppN (mkConst `Lean.KeyedDeclsAttribute.addBuiltin) #[mkConst df.valueTypeName, mkConst attrDeclName, toExpr key, toExpr declName, mkConst declName] let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error e => do let msg ← (e.toMessageData {}).toString throw (IO.userError s!"failed to emit registration code for builtin '{declName}': {msg}") | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) protected unsafe def init {Ξ³} (df : Def Ξ³) (attrDeclName : Name) : IO (KeyedDeclsAttribute Ξ³) := do let tableRef ← IO.mkRef ({} : Table Ξ³) let ext : Extension Ξ³ ← registerScopedEnvExtension { name := df.name mkInitial := do return { table := (← tableRef.get) } ofOLeanEntry := fun s entry => do let ctx ← read match ctx.env.evalConstCheck Ξ³ ctx.opts df.valueTypeName entry.decl with | Except.ok f => return { toOLeanEntry := entry, value := f } | Except.error ex => throw (IO.userError ex) addEntry := fun s e => { table := s.table.insert e, newEntries := e.toOLeanEntry :: s.newEntries } toOLeanEntry := (Β·.toOLeanEntry) } unless df.builtinName.isAnonymous do registerBuiltinAttribute { name := df.builtinName, descr := "(builtin) " ++ df.descr, add := fun declName stx kind => do unless kind == AttributeKind.global do throwError "invalid attribute '{df.builtinName}', must be global" let key ← df.evalKey true stx let decl ← getConstInfo declName match decl.type with | Expr.const c _ _ => if c != df.valueTypeName then throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected" else let env ← getEnv let env ← declareBuiltin df attrDeclName env key declName setEnv env | _ => throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected", applicationTime := AttributeApplicationTime.afterCompilation } registerBuiltinAttribute { name := df.name descr := df.descr add := fun constName stx attrKind => do let key ← df.evalKey false stx match IR.getSorryDep (← getEnv) constName with | none => let val ← evalConstCheck Ξ³ df.valueTypeName constName ext.add { key := key, decl := constName, value := val } attrKind | _ => -- If the declaration contains `sorry`, we skip `evalConstCheck` to avoid unnecessary bizarre error message pure () applicationTime := AttributeApplicationTime.afterCompilation } pure { defn := df, tableRef := tableRef, ext := ext } /-- Retrieve entries tagged with `[attr key]` or `[builtinAttr key]`. -/ def getEntries {Ξ³} (attr : KeyedDeclsAttribute Ξ³) (env : Environment) (key : Name) : List (AttributeEntry Ξ³) := (attr.ext.getState env).table.findD key [] /-- Retrieve values tagged with `[attr key]` or `[builtinAttr key]`. -/ def getValues {Ξ³} (attr : KeyedDeclsAttribute Ξ³) (env : Environment) (key : Name) : List Ξ³ := (getEntries attr env key).map AttributeEntry.value end KeyedDeclsAttribute end Lean
ab71eabefd53468f75e8bfa596bb14f05658f6e5
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/set_theory/ordinal.lean
03b681761860a8ca7f453e3064c56bf0d6ed0a4d
[ "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
56,636
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import set_theory.cardinal /-! # Ordinals Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed with a total order, where an ordinal is smaller than another one if it embeds into it as an initial segment (or, equivalently, in any way). This total order is well founded. ## Main definitions * `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). It is denoted by `r β‰Όi s`. * `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by `r β‰Ίi s`. * `ordinal`: the type of ordinals (in a given universe) * `type r`: given a well-founded order `r`, this is the corresponding ordinal * `typein r a`: given a well-founded order `r` on a type `Ξ±`, and `a : Ξ±`, the ordinal corresponding to all elements smaller than `a`. * `enum r o h`: given a well-order `r` on a type `Ξ±`, and an ordinal `o` strictly smaller than the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `Ξ±`. In other words, the elements of `Ξ±` can be enumerated using ordinals up to `type r`. * `card o`: the cardinality of an ordinal `o`. * `lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`. For a version registering additionally that this is an initial segment embedding, see `lift.initial_seg`. For a version regiserting that it is a principal segment embedding if `u < v`, see `lift.principal_seg`. * `omega` is the first infinite ordinal. It is the order type of `β„•`. * `o₁ + oβ‚‚` is the order on the disjoint union of `o₁` and `oβ‚‚` obtained by declaring that every element of `o₁` is smaller than every element of `oβ‚‚`. The main properties of addition (and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here, we only introduce it and prove its basic properties to deduce the fact that the order on ordinals is total (and well founded). * `succ o` is the successor of the ordinal `o`. * `min`: the minimal element of a nonempty indexed family of ordinals * `omin` : the minimal element of a nonempty set of ordinals * `ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality. It is the canonical way to represent a cardinal with an ordinal. ## Notations * `r β‰Όi s`: the type of initial segment embeddings of `r` into `s`. * `r β‰Ίi s`: the type of principal segment embeddings of `r` into `s`. * `Ο‰` is a notation for the first infinite ordinal in the locale ordinal. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} /-! ### Initial segments Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called `initial_seg r s`, and denoted by `r β‰Όi s`. -/ /-- If `r` is a relation on `Ξ±` and `s` in a relation on `Ξ²`, then `f : r β‰Όi s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `Ξ²` then `b` is in the range of `f`. -/ @[nolint has_inhabited_instance] structure initial_seg {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) extends r β†ͺr s := (init : βˆ€ a b, s b (to_rel_embedding a) β†’ βˆƒ a', to_rel_embedding a' = b) local infix ` β‰Όi `:25 := initial_seg namespace initial_seg instance : has_coe (r β‰Όi s) (r β†ͺr s) := ⟨initial_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r β‰Όi s) := ⟨λ _, Ξ± β†’ Ξ², Ξ» f x, (f : r β†ͺr s) x⟩ @[simp] theorem coe_fn_mk (f : r β†ͺr s) (o) : (@initial_seg.mk _ _ r s f o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r β‰Όi s) : (f.to_rel_embedding : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_coe_fn (f : r β‰Όi s) : ((f : r β†ͺr s) : Ξ± β†’ Ξ²) = f := rfl theorem init' (f : r β‰Όi s) {a : Ξ±} {b : Ξ²} : s b (f a) β†’ βˆƒ a', f a' = b := f.init _ _ theorem init_iff (f : r β‰Όi s) {a : Ξ±} {b : Ξ²} : s b (f a) ↔ βˆƒ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r β†ͺr s).map_rel_iff.1 (e.symm β–Έ h)⟩, Ξ» ⟨a', e, h⟩, e β–Έ (f : r β†ͺr s).map_rel_iff.2 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃r s) : r β‰Όi s := ⟨f, Ξ» a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `β‰Όi` is reflexive -/ @[refl] protected def refl (r : Ξ± β†’ Ξ± β†’ Prop) : r β‰Όi r := ⟨rel_embedding.refl _, Ξ» a b h, ⟨_, rfl⟩⟩ /-- Composition of functions shows that `β‰Όi` is transitive -/ @[trans] protected def trans (f : r β‰Όi s) (g : s β‰Όi t) : r β‰Όi t := ⟨f.1.trans g.1, Ξ» a c h, begin simp at h ⊒, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.map_rel_iff.1 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem refl_apply (x : Ξ±) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r β‰Όi s) (g : s β‰Όi t) (a : Ξ±) : (f.trans g) a = g (f a) := rfl theorem unique_of_extensional [is_extensional Ξ² s] : well_founded r β†’ subsingleton (r β‰Όi s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : Ξ± β†’ Ξ²) = g, { cases f, cases g, congr, exact rel_embedding.coe_fn_inj this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (Ξ» x, ⟨λ h, _, Ξ» h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r β†ͺr s).map_rel_iff.2 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r β†ͺr s).map_rel_iff.2 h' } end⟩ instance [is_well_order Ξ² s] : subsingleton (r β‰Όi s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@rel_embedding.well_founded _ _ r s a is_well_order.wf)) a⟩ protected theorem eq [is_well_order Ξ² s] (f g : r β‰Όi s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order Ξ± r] (f : r β‰Όi s) (g : s β‰Όi r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `Ξ±` and `Ξ²` whose images are initial segments, and `Ξ²` is a well-order then `Ξ±` and `Ξ²` are order-isomorphic. -/ def antisymm [is_well_order Ξ² s] (f : r β‰Όi s) (g : s β‰Όi r) : r ≃r s := by haveI := f.to_rel_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.map_rel_iff'⟩ @[simp] theorem antisymm_to_fun [is_well_order Ξ² s] (f : r β‰Όi s) (g : s β‰Όi r) : (antisymm f g : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem antisymm_symm [is_well_order Ξ± r] [is_well_order Ξ² s] (f : r β‰Όi s) (g : s β‰Όi r) : (antisymm f g).symm = antisymm g f := rel_iso.injective_coe_fn rfl theorem eq_or_principal [is_well_order Ξ² s] (f : r β‰Όi s) : surjective f ∨ βˆƒ b, βˆ€ x, s x b ↔ βˆƒ y, f y = x := or_iff_not_imp_right.2 $ Ξ» h b, acc.rec_on (is_well_order.wf.apply b : acc s b) $ Ξ» x H IH, not_forall_not.1 $ Ξ» hn, h ⟨x, Ξ» y, ⟨(IH _), Ξ» ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (Ξ» hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set Ξ²) (f : r β‰Όi s) (H : βˆ€ a, f a ∈ p) : r β‰Όi subrel s p := ⟨rel_embedding.cod_restrict p f H, Ξ» a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r β‰Όi s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def le_add (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) : r β‰Όi sum.lex r s := ⟨⟨⟨sum.inl, Ξ» _ _, sum.inl.inj⟩, Ξ» a b, sum.lex_inl_inl⟩, Ξ» a b, by cases b; [exact Ξ» _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg /-! ### Principal segments Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form `(-∞, top)` for some element `top` of `Ξ²`). The type of these embeddings from `r` to `s` is called `principal_seg r s`, and denoted by `r β‰Ίi s`. Principal segments are in particular initial segments. -/ /-- If `r` is a relation on `Ξ±` and `s` in a relation on `Ξ²`, then `f : r β‰Ίi s` is an order embedding whose range is an open interval `(-∞, top)` for some element `top` of `Ξ²`. Such order embeddings are called principal segments -/ @[nolint has_inhabited_instance] structure principal_seg {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) extends r β†ͺr s := (top : Ξ²) (down : βˆ€ b, s b top ↔ βˆƒ a, to_rel_embedding a = b) local infix ` β‰Ίi `:25 := principal_seg namespace principal_seg instance : has_coe (r β‰Ίi s) (r β†ͺr s) := ⟨principal_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r β‰Ίi s) := ⟨λ _, Ξ± β†’ Ξ², Ξ» f, f⟩ @[simp] theorem coe_fn_mk (f : r β†ͺr s) (t o) : (@principal_seg.mk _ _ r s f t o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r β‰Ίi s) : (f.to_rel_embedding : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_coe_fn (f : r β‰Ίi s) : ((f : r β†ͺr s) : Ξ± β†’ Ξ²) = f := rfl theorem down' (f : r β‰Ίi s) {b : Ξ²} : s b f.top ↔ βˆƒ a, f a = b := f.down _ theorem lt_top (f : r β‰Ίi s) (a : Ξ±) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans Ξ² s] (f : r β‰Ίi s) {a : Ξ±} {b : Ξ²} (h : s b (f a)) : βˆƒ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ /-- A principal segment is in particular an initial segment. -/ instance has_coe_initial_seg [is_trans Ξ² s] : has_coe (r β‰Ίi s) (r β‰Όi s) := ⟨λ f, ⟨f.to_rel_embedding, Ξ» a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans Ξ² s] (f : r β‰Ίi s) : ((f : r β‰Όi s) : Ξ± β†’ Ξ²) = f := rfl theorem init_iff [is_trans Ξ² s] (f : r β‰Ίi s) {a : Ξ±} {b : Ξ²} : s b (f a) ↔ βˆƒ a', f a' = b ∧ r a' a := @initial_seg.init_iff Ξ± Ξ² r s f a b theorem irrefl (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (f : r β‰Ίi r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end /-- Composition of a principal segment with an initial segment, as a principal segment -/ def lt_le (f : r β‰Ίi s) (g : s β‰Όi t) : r β‰Ίi t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, Ξ» a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply (f : r β‰Ίi s) (g : s β‰Όi t) (a : Ξ±) : (f.lt_le g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r β‰Ίi s) (g : s β‰Όi t) : (f.lt_le g).top = g f.top := rfl /-- Composition of two principal segments as a principal segment -/ @[trans] protected def trans [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Ίi t) : r β‰Ίi t := lt_le f g @[simp] theorem trans_apply [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Ίi t) (a : Ξ±) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Ίi t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment, as a principal segment -/ def equiv_lt (f : r ≃r s) (g : s β‰Ίi t) : r β‰Ίi t := ⟨@rel_embedding.trans _ _ _ r s t f g, g.top, Ξ» c, suffices (βˆƒ (a : Ξ²), g a = c) ↔ βˆƒ (a : Ξ±), g (f a) = c, by simpa [g.down], ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩, Ξ» ⟨a, h⟩, ⟨f a, h⟩⟩⟩ /-- Composition of a principal segment with an order isomorphism, as a principal segment -/ def lt_equiv {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} (f : principal_seg r s) (g : s ≃r t) : principal_seg r t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [← g.apply_symm_apply x, g.map_rel_iff, f.down', exists_congr], intro y, exact ⟨congr_arg g, Ξ» h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s β‰Ίi t) (a : Ξ±) : (equiv_lt f g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃r s) (g : s β‰Ίi t) : (equiv_lt f g).top = g.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [is_well_order Ξ² s] : subsingleton (r β‰Ίi s) := ⟨λ f g, begin have ef : (f : Ξ± β†’ Ξ²) = g, { show ((f : r β‰Όi s) : Ξ± β†’ Ξ²) = g, rw @subsingleton.elim _ _ (f : r β‰Όi s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (Ξ» x, _), simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] }, cases f, cases g, have := rel_embedding.coe_fn_inj ef; congr' end⟩ theorem top_eq [is_well_order Ξ³ t] (e : r ≃r s) (f : r β‰Ίi t) (g : s β‰Ίi t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} [is_well_order Ξ³ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) : subrel r {b | r b a} β‰Ίi r := ⟨subrel.rel_embedding _ _, a, Ξ» b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, Ξ» ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set Ξ²) (f : r β‰Ίi s) (H : βˆ€ a, f a ∈ p) (Hβ‚‚ : f.top ∈ p) : r β‰Ίi subrel s p := ⟨rel_embedding.cod_restrict p f H, ⟨f.top, Hβ‚‚βŸ©, Ξ» ⟨b, h⟩, f.down'.trans $ exists_congr $ Ξ» a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r β‰Ίi s) (H Hβ‚‚ a) : cod_restrict p f H Hβ‚‚ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r β‰Ίi s) (H Hβ‚‚) : (cod_restrict p f H Hβ‚‚).top = ⟨f.top, Hβ‚‚βŸ© := rfl end principal_seg /-! ### Properties of initial and principal segments -/ /-- To an initial segment taking values in a well order, one can associate either a principal segment (if the range is not everything, hence one can take as top the minimum of the complement of the range) or an order isomorphism (if the range is everything). -/ def initial_seg.lt_or_eq [is_well_order Ξ² s] (f : r β‰Όi s) : (r β‰Ίi s) βŠ• (r ≃r s) := if h : surjective f then sum.inr (rel_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ theorem initial_seg.lt_or_eq_apply_left [is_well_order Ξ² s] (f : r β‰Όi s) (g : r β‰Ίi s) (a : Ξ±) : g a = f a := @initial_seg.eq Ξ± Ξ² r s _ g f a theorem initial_seg.lt_or_eq_apply_right [is_well_order Ξ² s] (f : r β‰Όi s) (g : r ≃r s) (a : Ξ±) : g a = f a := initial_seg.eq (initial_seg.of_iso g) f a /-- Composition of an initial segment taking values in a well order and a principal segment. -/ def initial_seg.le_lt [is_well_order Ξ² s] [is_trans Ξ³ t] (f : r β‰Όi s) (g : s β‰Ίi t) : r β‰Ίi t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order Ξ² s] [is_trans Ξ³ t] (f : r β‰Όi s) (g : s β‰Ίi t) (a : Ξ±) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] } end namespace rel_embedding /-- Given an order embedding into a well order, collapse the order embedding by filling the gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise, but the proof of the fact that it is an initial segment will be given in `collapse`. -/ def collapse_F [is_well_order Ξ² s] (f : r β†ͺr s) : Ξ  a, {b // Β¬ s (f a) b} := (rel_embedding.well_founded f $ is_well_order.wf).fix $ Ξ» a IH, begin let S := {b | βˆ€ a h, s (IH a h).1 b}, have : f a ∈ S, from Ξ» a' h, ((trichotomous _ _) .resolve_left $ Ξ» h', (IH a' h).2 $ trans (f.map_rel_iff.2 h) h') .resolve_left $ Ξ» h', (IH a' h).2 $ h' β–Έ f.map_rel_iff.2 h, exact ⟨is_well_order.wf.min S ⟨_, this⟩, is_well_order.wf.not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order Ξ² s] (f : r β†ͺr s) {a : Ξ±} : βˆ€ {a'}, r a' a β†’ s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | βˆ€ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order Ξ² s] (f : r β†ͺr s) (a : Ξ±) {b} (h : βˆ€ a' (h : r a' a), s (collapse_F f a').1 b) : Β¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | βˆ€ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding into a well order, by collapsing it to fill the gaps. -/ def collapse [is_well_order Ξ² s] (f : r β†ͺr s) : r β‰Όi s := by haveI := rel_embedding.is_well_order f; exact ⟨rel_embedding.of_monotone (Ξ» a, (collapse_F f a).1) (Ξ» a b, collapse_F.lt f), Ξ» a b, acc.rec_on (is_well_order.wf.apply b : acc s b) (Ξ» b H IH a h, begin let S := {a | Β¬ s (collapse_F f a).1 b}, have : S.nonempty := ⟨_, asymm h⟩, existsi (is_well_order.wf : well_founded r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf : well_founded r).min_mem S this }, { refine collapse_F.not_lt f _ (Ξ» a' h', _), by_contradiction hn, exact is_well_order.wf.not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order Ξ² s] (f : r β†ͺr s) (a) : collapse f a = (collapse_F f a).1 := rfl end rel_embedding /-! ### Well order on an arbitrary type -/ section well_ordering_thm parameter {Οƒ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (Οƒ β†ͺ cardinal.{u}) := embedding.total.resolve_left $ Ξ» ⟨⟨f, hf⟩⟩, let g : Οƒ β†’ cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≀ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : Οƒ β†ͺ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- Any type can be endowed with a well order, obtained by pulling back the well order over cardinals by some embedding. -/ def well_ordering_rel : Οƒ β†’ Οƒ β†’ Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order Οƒ well_ordering_rel := (rel_embedding.preimage _ _).is_well_order end well_ordering_thm /-! ### Definition of ordinals -/ /-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient of this type. -/ structure Well_order : Type (u+1) := (Ξ± : Type u) (r : Ξ± β†’ Ξ± β†’ Prop) (wo : is_well_order Ξ± r) attribute [instance] Well_order.wo namespace Well_order instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩ end Well_order /-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order isomorphism. -/ instance ordinal.is_equivalent : setoid Well_order := { r := Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s), iseqv := ⟨λ⟨α, r, _⟩, ⟨rel_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, ⟨e₁.trans eβ‚‚βŸ©βŸ© } /-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. For the embedding as a principal segment, see `typein.principal_seg`. -/ def typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r = type s ↔ nonempty (r ≃r s) := quotient.eq @[simp] lemma type_out (o : ordinal) : type o.out.r = o := by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl } @[elab_as_eliminator] theorem induction_on {C : ordinal β†’ Prop} (o : ordinal) (H : βˆ€ Ξ± r [is_well_order Ξ± r], by exactI C (type r)) : C o := quot.induction_on o $ Ξ» ⟨α, r, wo⟩, @H Ξ± r wo /-! ### The order on ordinals -/ /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≀ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_onβ‚‚ a b (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r β‰Όi s)) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, propext ⟨ Ξ» ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, Ξ» ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r ≀ type s ↔ nonempty (r β‰Όi s) := iff.rfl theorem type_le' {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r ≀ type s ↔ nonempty (r β†ͺr s) := ⟨λ ⟨f⟩, ⟨f⟩, Ξ» ⟨f⟩, ⟨f.collapse⟩⟩ /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_onβ‚‚ a b (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r β‰Ίi s)) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, by exactI propext ⟨ Ξ» ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, Ξ» ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r < type s ↔ nonempty (r β‰Ίi s) := iff.rfl instance : partial_order ordinal := { le := (≀), lt := (<), le_refl := quot.ind $ by exact Ξ» ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := Ξ» a b c, quotient.induction_on₃ a b c $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := Ξ» a b, quotient.induction_onβ‚‚ a b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, Ξ» ⟨g⟩, (f.lt_le g).irrefl _⟩, Ξ» ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (Ξ» g, ⟨g⟩) (Ξ» g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := Ξ» x b, show x ≀ b β†’ b ≀ x β†’ x = b, from quotient.induction_onβ‚‚ x b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨hβ‚βŸ© ⟨hβ‚‚βŸ©, by exactI quot.sound ⟨initial_seg.antisymm h₁ hβ‚‚βŸ© } /-- Given two ordinals `Ξ± ≀ Ξ²`, then `initial_seg_out Ξ± Ξ²` is the initial segment embedding of `Ξ±` to `Ξ²`, as map from a model type for `Ξ±` to a model type for `Ξ²`. -/ def initial_seg_out {Ξ± Ξ² : ordinal} (h : Ξ± ≀ Ξ²) : initial_seg Ξ±.out.r Ξ².out.r := begin rw [←quotient.out_eq Ξ±, ←quotient.out_eq Ξ²] at h, revert h, cases quotient.out Ξ±, cases quotient.out Ξ², exact classical.choice end /-- Given two ordinals `Ξ± < Ξ²`, then `principal_seg_out Ξ± Ξ²` is the principal segment embedding of `Ξ±` to `Ξ²`, as map from a model type for `Ξ±` to a model type for `Ξ²`. -/ def principal_seg_out {Ξ± Ξ² : ordinal} (h : Ξ± < Ξ²) : principal_seg Ξ±.out.r Ξ².out.r := begin rw [←quotient.out_eq Ξ±, ←quotient.out_eq Ξ²] at h, revert h, cases quotient.out Ξ±, cases quotient.out Ξ², exact classical.choice end /-- Given two ordinals `Ξ± = Ξ²`, then `rel_iso_out Ξ± Ξ²` is the order isomorphism between two model types for `Ξ±` and `Ξ²`. -/ def rel_iso_out {Ξ± Ξ² : ordinal} (h : Ξ± = Ξ²) : rel_iso Ξ±.out.r Ξ².out.r := begin rw [←quotient.out_eq Ξ±, ←quotient.out_eq Ξ²] at h, revert h, cases quotient.out Ξ±, cases quotient.out Ξ², exact classical.choice ∘ quotient.exact end theorem typein_lt_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : r β‰Ίi s) : typein s f.top = type r := eq.symm $ quot.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ f f.lt_top) (Ξ» ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : r β‰Όi s) (a : Ξ±) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ ((subrel.rel_embedding _ _).trans f) (Ξ» ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.2 h)) (Ξ» ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.1 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {a b : Ξ±} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, Ξ» h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (Ξ» x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {o} (h : o < type r) : βˆƒ a, typein r a = o := induction_on o (Ξ» Ξ² s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma typein_injective (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : injective (typein r) := injective_of_increasing r (<) (typein r) (Ξ» x y, (typein_lt_typein r).2) theorem typein_inj (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {a b} : typein r a = typein r b ↔ a = b := injective.eq_iff (typein_injective r) /-! ### Enumerating elements in a well-order with ordinals. -/ /-- `enum r o h` is the `o`-th element of `Ξ±` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `Ξ±`. -/ def enum (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (o) : o < type r β†’ Ξ± := quot.rec_on o (Ξ» ⟨β, s, _⟩ h, (classical.choice h).top) $ Ξ» ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (Ξ» (Hβ‚‚ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : βˆ€ {o e} (H : o < type r), @@eq.rec (Ξ» (o : ordinal), o < type r β†’ Ξ±) (Ξ» (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this Hβ‚‚).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice Hβ‚‚)) end theorem enum_type {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : s β‰Ίi r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (rel_iso.refl _) _ _ @[simp] theorem enum_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein /-- A well order `r` is order isomorphic to the set of ordinals strictly smaller than the ordinal version of `r`. -/ def typein_iso (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : r ≃r subrel (<) (< type r) := ⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, Ξ» x, enum r x.1 x.2, Ξ» y, enum_typein r y, Ξ» ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩, Ξ» a b, (typein_lt_typein r)⟩ theorem enum_lt {r : Ξ± β†’ Ξ± β†’ Prop} [is_well_order Ξ± r] {o₁ oβ‚‚ : ordinal} (h₁ : o₁ < type r) (hβ‚‚ : oβ‚‚ < type r) : r (enum r o₁ h₁) (enum r oβ‚‚ hβ‚‚) ↔ o₁ < oβ‚‚ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma rel_iso_enum' {Ξ± Ξ² : Type u} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : rel_iso r s) (o : ordinal) : βˆ€(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros Ξ³ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma rel_iso_enum {Ξ± Ξ² : Type u} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : rel_iso r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := rel_iso_enum' _ _ _ _ theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ Ξ» Ξ± r wo, by exactI suffices βˆ€ a, acc (<) (typein r a), from ⟨_, Ξ» o h, let ⟨a, e⟩ := typein_surj r h in e β–Έ this a⟩, Ξ» a, acc.rec_on (wo.wf.apply a) $ Ξ» x H IH, ⟨_, Ξ» o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- Principal segment version of the `typein` function, embedding a well order into ordinals as a principal segment. -/ def typein.principal_seg {Ξ± : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : @principal_seg Ξ± ordinal.{u} r (<) := ⟨rel_embedding.of_monotone (typein r) (Ξ» a b, (typein_lt_typein r).2), type r, Ξ» b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, Ξ» ⟨a, e⟩, e β–Έ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : (typein.principal_seg r : Ξ± β†’ ordinal) = typein r := rfl /-! ### Cardinality of ordinals -/ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (Ξ» ⟨α, r, _⟩, mk Ξ±) $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : card (type r) = mk Ξ± := rfl lemma card_typein {r : Ξ± β†’ Ξ± β†’ Prop} [wo : is_well_order Ξ± r] (x : Ξ±) : mk {y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ oβ‚‚ : ordinal} : o₁ ≀ oβ‚‚ β†’ card o₁ ≀ card oβ‚‚ := induction_on o₁ $ Ξ» Ξ± r _, induction_on oβ‚‚ $ Ξ» Ξ² s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ instance : inhabited ordinal := ⟨0⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨empty_equiv_pempty.symm, Ξ» _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl protected theorem zero_le (o : ordinal) : 0 ≀ o := induction_on o $ Ξ» Ξ± r _, ⟨⟨⟨embedding.of_not_nonempty $ Ξ» ⟨a⟩, a.elim, Ξ» a, a.elim⟩, Ξ» a, a.elim⟩⟩ @[simp] protected theorem le_zero {o : ordinal} : o ≀ 0 ↔ o = 0 := by simp only [le_antisymm_iff, ordinal.zero_le, and_true] protected theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o β‰  0 := by simp only [lt_iff_le_and_ne, ordinal.zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨punit_equiv_punit, Ξ» _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl /-! ### Lifting ordinals to a higher universe -/ /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version, see `lift.initial_seg`. -/ def lift (o : ordinal.{u}) : ordinal.{max u v} := quotient.lift_on o (Ξ» ⟨α, r, wo⟩, @type _ _ (@rel_embedding.is_well_order _ _ (@equiv.ulift.{v} Ξ± ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{v} r) wo)) $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {Ξ±} (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : βˆƒ wo', lift (type r) = @type _ (@equiv.ulift.{v} Ξ± ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ Ξ» a, induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : βˆ€ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $ (rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {Ξ± : Type u} {Ξ² : Type v} {r s} [is_well_order Ξ± r] [is_well_order Ξ² s] : lift.{u (max v w)} (type r) ≀ lift.{v (max u w)} (type s) ↔ nonempty (r β‰Όi s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, Ξ» ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {Ξ± : Type u} {Ξ² : Type v} {r s} [is_well_order Ξ± r] [is_well_order Ξ² s] : lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃r s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $ f.trans (rel_iso.preimage equiv.ulift s)⟩, Ξ» ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {Ξ± : Type u} {Ξ² : Type v} {r s} [is_well_order Ξ± r] [is_well_order Ξ² s] : lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r β‰Ίi s) := by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max v w)} Ξ± ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{(max v w)} r) _; haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max u w)} Ξ² ⁻¹'o s) s (rel_iso.preimage equiv.ulift.{(max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, Ξ» ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≀ lift b ↔ a ≀ b := induction_on a $ Ξ» Ξ± r _, induction_on b $ Ξ» Ξ² s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨pempty_equiv_pempty, Ξ» a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨punit_equiv_punit, Ξ» a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ Ξ» Ξ± r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≀ a.lift) : βˆƒ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (Ξ» Ξ±, induction_on b $ Ξ» Ξ² s _ e', begin resetI, rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (mk Ξ²), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := rel_iso.preimage f s, haveI := (g : ⇑f ⁻¹'o s β†ͺr s).is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≀ lift a) : βˆƒ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≀ lift a ↔ βˆƒ a', lift a' = b ∧ a' ≀ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm β–Έ h⟩, Ξ» ⟨a', e, h⟩, e β–Έ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ βˆƒ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm β–Έ h⟩, Ξ» ⟨a', e, h⟩, e β–Έ lift_lt.2 h⟩ /-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as an initial segment when `u ≀ v`. -/ def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{u v}, Ξ» a b, lift_inj.1⟩, Ξ» a b, lift_lt⟩, Ξ» a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal β†’ ordinal) = lift := rfl /-! ### The first infinite ordinal `omega` -/ /-- `Ο‰` is the first infinite ordinal, defined as the order type of `β„•`. -/ def omega : ordinal.{u} := lift $ @type β„• (<) _ localized "notation `Ο‰` := ordinal.omega.{0}" in ordinal theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /-! ### Definition and first properties of addition on ordinals In this paragraph, we introduce the addition on ordinals, and prove just enough properties to deduce that the order on ordinals is total (and therefore well-founded). Further properties of the addition, together with properties of the other operations, are proved in `ordinal_arithmetic.lean`. -/ /-- `o₁ + oβ‚‚` is the order on the disjoint union of `o₁` and `oβ‚‚` obtained by declaring that every element of `o₁` is smaller than every element of `oβ‚‚`. -/ instance : has_add ordinal.{u} := ⟨λo₁ oβ‚‚, quotient.lift_onβ‚‚ o₁ oβ‚‚ (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α βŠ• Ξ², sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order β†’ Well_order β†’ ordinal) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩ @[simp] theorem card_add (o₁ oβ‚‚ : ordinal) : card (o₁ + oβ‚‚) = card o₁ + card oβ‚‚ := induction_on o₁ $ Ξ» Ξ± r _, induction_on oβ‚‚ $ Ξ» Ξ² s _, rfl @[simp] theorem card_nat (n : β„•) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] @[simp] theorem type_add {Ξ± Ξ² : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) [is_well_order Ξ± r] [is_well_order Ξ² s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := Ξ» o, induction_on o $ Ξ» Ξ± r _, eq.symm $ quotient.sound ⟨⟨(pempty_sum Ξ±).symm, Ξ» a b, sum.lex_inr_inr⟩⟩, add_zero := Ξ» o, induction_on o $ Ξ» Ξ± r _, eq.symm $ quotient.sound ⟨⟨(sum_pempty Ξ±).symm, Ξ» a b, sum.lex_inl_inl⟩⟩, add_assoc := Ξ» o₁ oβ‚‚ o₃, quotient.induction_on₃ o₁ oβ‚‚ o₃ $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, Ξ» a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_le_add_left {a b : ordinal} : a ≀ b β†’ βˆ€ c, c + a ≀ c + b := induction_on a $ Ξ» α₁ r₁ _, induction_on b $ Ξ» Ξ±β‚‚ rβ‚‚ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ Ξ» Ξ² s _, ⟨⟨⟨(embedding.refl _).sum_map f, Ξ» a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, Ξ» a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≀ a + b := by simpa only [add_zero] using add_le_add_left (ordinal.zero_le b) a theorem add_le_add_right {a b : ordinal} : a ≀ b β†’ βˆ€ c, a + c ≀ b + c := induction_on a $ Ξ» α₁ r₁ hr₁, induction_on b $ Ξ» Ξ±β‚‚ rβ‚‚ hrβ‚‚ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ Ξ» Ξ² s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hrβ‚‚ hs)).2 ⟨⟨f.sum_map (embedding.refl _), Ξ» a b, begin split; intro H, { cases a with a a; cases b with b b; cases H; constructor; [rwa ← fo, assumption] }, { cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≀ b + a := by simpa only [zero_add] using add_le_add_right (ordinal.zero_le b) a theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ Ξ» Ξ± r _, ⟨⟨⟨⟨λ x, sum.inl x, Ξ» _ _, sum.inl.inj⟩, Ξ» _ _, sum.lex_inl_inl⟩, sum.inr punit.star, Ξ» b, sum.rec_on b (Ξ» x, ⟨λ _, ⟨x, rfl⟩, Ξ» _, sum.lex.sep _ _⟩) (Ξ» x, sum.lex_inr_inr.trans ⟨false.elim, Ξ» ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_le {a b : ordinal} : succ a ≀ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ Ξ» Ξ± r hr, induction_on b $ Ξ» Ξ² s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@rel_embedding.of_monotone (Ξ± βŠ• punit) Ξ² _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (Ξ» a b, _), Ξ» a b, _⟩⟩, { exact f }, { exact Ξ» _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.map_rel_iff.2 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ theorem le_total (a b : ordinal) : a ≀ b ∨ b ≀ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl hβ‚‚ := induction_on a (Ξ» α₁ r₁ _, induction_on b $ Ξ» Ξ±β‚‚ rβ‚‚ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ rβ‚‚) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ hβ‚‚ end instance : linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } instance : is_well_order ordinal (<) := ⟨wf⟩ @[simp] lemma typein_le_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {x x' : Ξ±} : typein r x ≀ typein r x' ↔ Β¬r x' x := by rw [←not_lt, typein_lt_typein] lemma enum_le_enum (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : Β¬r (enum r o' ho') (enum r o ho) ↔ o ≀ o' := by rw [←@not_lt _ _ o' o, enum_lt ho'] /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ /-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as a principal segment when `u < v`. -/ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := βŸ¨β†‘lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine Ξ» b, induction_on b _, introsI Ξ² s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊒, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, introsI Ξ± r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩, { exact Ξ» b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine Ξ» a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.map_rel_iff.2 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, introsI Ξ± r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal β†’ ordinal) = lift.{u (max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-! ### Minimum -/ /-- The minimal element of a nonempty family of ordinals -/ def min {ΞΉ} (I : nonempty ΞΉ) (f : ΞΉ β†’ ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in ⟨_, set.mem_range_self i⟩) theorem min_eq {ΞΉ} (I) (f : ΞΉ β†’ ordinal) : βˆƒ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ΞΉ I} (f : ΞΉ β†’ ordinal) (i) : min I f ≀ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ΞΉ I} {f : ΞΉ β†’ ordinal} {a} : a ≀ min I f ↔ βˆ€ i, a ≀ f i := ⟨λ h i, le_trans h (min_le _ _), Ξ» h, let ⟨i, e⟩ := min_eq I f in e.symm β–Έ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : βˆƒ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm β–Έ h theorem le_omin {S H a} : a ≀ omin S H ↔ βˆ€ i ∈ S, a ≀ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≀ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ΞΉ} (I) (f : ΞΉ β†’ ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ Ξ» a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ Ξ» j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) end ordinal /-! ### Representing a cardinal with an ordinal -/ namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/ def ord (c : cardinal) : ordinal := begin let ΞΉ := Ξ» Ξ±, {r // is_well_order Ξ± r}, have : Ξ  Ξ±, ΞΉ Ξ± := Ξ» Ξ±, ⟨well_ordering_rel, by apply_instance⟩, let F := Ξ» Ξ±, ordinal.min ⟨this _⟩ (Ξ» i:ΞΉ Ξ±, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : βˆ€ {Ξ± Ξ²}, Ξ± β‰ˆ Ξ² β†’ F Ξ± ≀ F Ξ², from Ξ» Ξ± Ξ² h, le_antisymm (this h) (this (setoid.symm h)), intros Ξ± Ξ² h, cases h with f, refine ordinal.le_min.2 (Ξ» i, _), haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨rel_iso.preimage f i.1⟩, exact ordinal.min_le (Ξ» i:ΞΉ Ξ±, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end @[nolint def_lemma doc_blame] -- TODO: This should be a theorem but Lean fails to synthesize the placeholder def ord_eq_min (Ξ± : Type u) : ord (mk Ξ±) = @ordinal.min _ _ (Ξ» i:{r // is_well_order Ξ± r}, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (Ξ±) : βˆƒ (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r], ord (mk Ξ±) = @type Ξ± r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order Ξ± r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (Ξ» i:{r // is_well_order Ξ± r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : ord (mk Ξ±) ≀ ordinal.type r := @ordinal.min_le {r // is_well_order Ξ± r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (Ξ» i:{r // is_well_order Ξ± r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≀ o ↔ c ≀ o.card := quotient.induction_on c $ Ξ» Ξ±, induction_on o $ Ξ» Ξ² s _, let ⟨r, _, e⟩ := ord_eq Ξ± in begin resetI, simp only [mk_def, card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := rel_embedding.preimage f s, haveI := rel_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ Ξ» Ξ±, let ⟨r, _, e⟩ := ord_eq Ξ± in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≀ o := ord_le.2 (le_refl _) lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord := by { rw [lt_ord], apply cardinal.lt_succ_self } @[simp] theorem ord_le_ord {c₁ cβ‚‚} : ord c₁ ≀ ord cβ‚‚ ↔ c₁ ≀ cβ‚‚ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ cβ‚‚} : ord c₁ < ord cβ‚‚ ↔ c₁ < cβ‚‚ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : β„•) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ Ξ» o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end lemma mk_ord_out (c : cardinal) : mk c.ord.out.Ξ± = c := by rw [←card_type c.ord.out.r, type_out, card_ord] lemma card_typein_lt (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (x : Ξ±) (h : ord (mk Ξ±) = type r) : card (typein r x) < mk Ξ± := by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.Ξ±) : card (typein c.ord.out.r x) < c := by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`. -/ def ord.order_embedding : cardinal β†ͺo ordinal := rel_embedding.order_embedding_of_lt_embedding (rel_embedding.of_monotone cardinal.ord $ Ξ» a b, cardinal.ord_lt_ord.2) @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal β†’ ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ def univ := lift.{(u+1) v} (mk ordinal) theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ Ξ» o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ βˆƒ c', c = lift.{u (u+1)} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, Ξ» ⟨c', e⟩, e.symm β–Έ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ βˆƒ c', c = lift.{u (max (u+1) v)} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, Ξ» ⟨c', e⟩, e.symm β–Έ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl end ordinal
1f92301df4977250be7f083caf95e78d6de6ca81
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/order/ring.lean
140acae0c145819dc1f35beb4baf0a27821be003
[ "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
67,715
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.invertible import algebra.order.group import algebra.order.sub import data.set.intervals.basic /-! # Ordered rings and semirings This file develops the basics of ordered (semi)rings. Each typeclass here comprises * an algebraic class (`semiring`, `comm_semiring`, `ring`, `comm_ring`) * an order class (`partial_order`, `linear_order`) * assumptions on how both interact ((strict) monotonicity, canonicity) For short, * "`+` respects `≀`" means "monotonicity of addition" * "`*` respects `<`" means "strict monotonicity of multiplication by a positive number". ## Typeclasses * `ordered_semiring`: Semiring with a partial order such that `+` respects `≀` and `*` respects `<`. * `ordered_comm_semiring`: Commutative semiring with a partial order such that `+` respects `≀` and `*` respects `<`. * `ordered_ring`: Ring with a partial order such that `+` respects `≀` and `*` respects `<`. * `ordered_comm_ring`: Commutative ring with a partial order such that `+` respects `≀` and `*` respects `<`. * `linear_ordered_semiring`: Semiring with a linear order such that `+` respects `≀` and `*` respects `<`. * `linear_ordered_ring`: Ring with a linear order such that `+` respects `≀` and `*` respects `<`. * `linear_ordered_comm_ring`: Commutative ring with a linear order such that `+` respects `≀` and `*` respects `<`. * `canonically_ordered_comm_semiring`: Commutative semiring with a partial order such that `+` respects `≀`, `*` respects `<`, and `a ≀ b ↔ βˆƒ c, b = a + c`. and some typeclasses to define ordered rings by specifying their nonegative elements: * `nonneg_ring`: To define `ordered_ring`s. * `linear_nonneg_ring`: To define `linear_ordered_ring`s. ## Hierarchy The hardest part of proving order lemmas might be to figure out the correct generality and its corresponding typeclass. Here's an attempt at demystifying it. For each typeclass, we list its immediate predecessors and what conditions are added to each of them. * `ordered_semiring` - `ordered_cancel_add_comm_monoid` & multiplication & `*` respects `<` - `semiring` & partial order structure & `+` respects `≀` & `*` respects `<` * `ordered_comm_semiring` - `ordered_semiring` & commutativity of multiplication - `comm_semiring` & partial order structure & `+` respects `≀` & `*` respects `<` * `ordered_ring` - `ordered_semiring` & additive inverses - `ordered_add_comm_group` & multiplication & `*` respects `<` - `ring` & partial order structure & `+` respects `≀` & `*` respects `<` * `ordered_comm_ring` - `ordered_ring` & commutativity of multiplication - `ordered_comm_semiring` & additive inverses - `comm_ring` & partial order structure & `+` respects `≀` & `*` respects `<` * `linear_ordered_semiring` - `ordered_semiring` & totality of the order & nontriviality - `linear_ordered_add_comm_monoid` & multiplication & nontriviality & `*` respects `<` * `linear_ordered_ring` - `ordered_ring` & totality of the order & nontriviality - `linear_ordered_semiring` & additive inverses - `linear_ordered_add_comm_group` & multiplication & `*` respects `<` - `domain` & linear order structure * `linear_ordered_comm_ring` - `ordered_comm_ring` & totality of the order & nontriviality - `linear_ordered_ring` & commutativity of multiplication - `integral_domain` & linear order structure * `canonically_ordered_comm_semiring` - `canonically_ordered_add_monoid` & multiplication & `*` respects `<` & no zero divisors - `comm_semiring` & `a ≀ b ↔ βˆƒ c, b = a + c` & no zero divisors ## TODO We're still missing some typeclasses, like * `linear_ordered_comm_semiring` * `canonically_ordered_semiring` They have yet to come up in practice. -/ set_option old_structure_cmd true universe u variable {Ξ± : Type u} lemma add_one_le_two_mul [preorder Ξ±] [semiring Ξ±] [covariant_class Ξ± Ξ± (+) (≀)] {a : Ξ±} (a1 : 1 ≀ a) : a + 1 ≀ 2 * a := calc a + 1 ≀ a + a : add_le_add_left a1 a ... = 2 * a : (two_mul _).symm /-- An `ordered_semiring Ξ±` is a semiring `Ξ±` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_semiring (Ξ± : Type u) extends semiring Ξ±, ordered_cancel_add_comm_monoid Ξ± := (zero_le_one : 0 ≀ (1 : Ξ±)) (mul_lt_mul_of_pos_left : βˆ€ a b c : Ξ±, a < b β†’ 0 < c β†’ c * a < c * b) (mul_lt_mul_of_pos_right : βˆ€ a b c : Ξ±, a < b β†’ 0 < c β†’ a * c < b * c) section ordered_semiring variables [ordered_semiring Ξ±] {a b c d : Ξ±} @[simp] lemma zero_le_one : 0 ≀ (1:Ξ±) := ordered_semiring.zero_le_one lemma zero_le_two : 0 ≀ (2:Ξ±) := add_nonneg zero_le_one zero_le_one lemma one_le_two : 1 ≀ (2:Ξ±) := calc (1:Ξ±) = 0 + 1 : (zero_add _).symm ... ≀ 1 + 1 : add_le_add_right zero_le_one _ section nontrivial variables [nontrivial Ξ±] @[simp] lemma zero_lt_one : 0 < (1 : Ξ±) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:Ξ±) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:Ξ±) β‰  0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:Ξ±) := calc (2:Ξ±) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma zero_lt_three : 0 < (3:Ξ±) := add_pos zero_lt_two zero_lt_one lemma zero_lt_four : 0 < (4:Ξ±) := add_pos zero_lt_two zero_lt_two end nontrivial lemma mul_lt_mul_of_pos_left (h₁ : a < b) (hβ‚‚ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ hβ‚‚ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (hβ‚‚ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ hβ‚‚ -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_left [@decidable_rel Ξ± (≀)] (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : c * a ≀ c * b := begin by_cases ba : b ≀ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≀ 0, { simp [c0.antisymm hβ‚‚] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le ba) (hβ‚‚.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_left : a ≀ b β†’ 0 ≀ c β†’ c * a ≀ c * b := by classical; exact decidable.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_right [@decidable_rel Ξ± (≀)] (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : a * c ≀ b * c := begin by_cases ba : b ≀ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≀ 0, { simp [c0.antisymm hβ‚‚] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le ba) (hβ‚‚.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_right : a ≀ b β†’ 0 ≀ c β†’ a * c ≀ b * c := by classical; exact decidable.mul_le_mul_of_nonneg_right -- TODO: there are four variations, depending on which variables we assume to be nonneg -- See Note [decidable namespace] protected lemma decidable.mul_le_mul [@decidable_rel Ξ± (≀)] (hac : a ≀ c) (hbd : b ≀ d) (nn_b : 0 ≀ b) (nn_c : 0 ≀ c) : a * b ≀ c * d := calc a * b ≀ c * b : decidable.mul_le_mul_of_nonneg_right hac nn_b ... ≀ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_le_mul : a ≀ c β†’ b ≀ d β†’ 0 ≀ b β†’ 0 ≀ c β†’ a * b ≀ c * d := by classical; exact decidable.mul_le_mul -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_le_one_le {Ξ± : Type*} [ordered_semiring Ξ±] [@decidable_rel Ξ± (≀)] {a b c : Ξ±} (h₁ : 0 ≀ c) (hβ‚‚ : a ≀ c) (h₃ : 0 ≀ b) (hβ‚„ : b ≀ 1) : a * b ≀ c := by simpa only [mul_one] using decidable.mul_le_mul hβ‚‚ hβ‚„ h₃ h₁ lemma mul_nonneg_le_one_le {Ξ± : Type*} [ordered_semiring Ξ±] {a b c : Ξ±} : 0 ≀ c β†’ a ≀ c β†’ 0 ≀ b β†’ b ≀ 1 β†’ a * b ≀ c := by classical; exact decidable.mul_nonneg_le_one_le -- See Note [decidable namespace] protected lemma decidable.mul_nonneg [@decidable_rel Ξ± (≀)] (ha : 0 ≀ a) (hb : 0 ≀ b) : 0 ≀ a * b := have h : 0 * b ≀ a * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonneg : 0 ≀ a β†’ 0 ≀ b β†’ 0 ≀ a * b := by classical; exact decidable.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonneg_of_nonpos [@decidable_rel Ξ± (≀)] (ha : 0 ≀ a) (hb : b ≀ 0) : a * b ≀ 0 := have h : a * b ≀ a * 0, from decidable.mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonneg_of_nonpos : 0 ≀ a β†’ b ≀ 0 β†’ a * b ≀ 0 := by classical; exact decidable.mul_nonpos_of_nonneg_of_nonpos -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonpos_of_nonneg [@decidable_rel Ξ± (≀)] (ha : a ≀ 0) (hb : 0 ≀ b) : a * b ≀ 0 := have h : a * b ≀ 0 * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_nonpos_of_nonpos_of_nonneg : a ≀ 0 β†’ 0 ≀ b β†’ a * b ≀ 0 := by classical; exact decidable.mul_nonpos_of_nonpos_of_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul [@decidable_rel Ξ± (≀)] (hac : a < c) (hbd : b ≀ d) (pos_b : 0 < b) (nn_c : 0 ≀ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≀ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul : a < c β†’ b ≀ d β†’ 0 < b β†’ 0 ≀ c β†’ a * b < c * d := by classical; exact decidable.mul_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul' [@decidable_rel Ξ± (≀)] (h1 : a ≀ c) (h2 : b < d) (h3 : 0 ≀ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≀ c * b : decidable.mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_lt_mul' : a ≀ c β†’ b < d β†’ 0 ≀ b β†’ 0 < c β†’ a * b < c * d := by classical; exact decidable.mul_lt_mul' lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h -- See Note [decidable namespace] protected lemma decidable.mul_self_lt_mul_self [@decidable_rel Ξ± (≀)] (h1 : 0 ≀ a) (h2 : a < b) : a * a < b * b := decidable.mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_self_lt_mul_self (h1 : 0 ≀ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 -- See Note [decidable namespace] protected lemma decidable.strict_mono_on_mul_self [@decidable_rel Ξ± (≀)] : strict_mono_on (Ξ» x : Ξ±, x * x) (set.Ici 0) := Ξ» x hx y hy hxy, decidable.mul_self_lt_mul_self hx hxy lemma strict_mono_on_mul_self : strict_mono_on (Ξ» x : Ξ±, x * x) (set.Ici 0) := Ξ» x hx y hy hxy, mul_self_lt_mul_self hx hxy -- See Note [decidable namespace] protected lemma decidable.mul_self_le_mul_self [@decidable_rel Ξ± (≀)] (h1 : 0 ≀ a) (h2 : a ≀ b) : a * a ≀ b * b := decidable.mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_le_mul_self (h1 : 0 ≀ a) (h2 : a ≀ b) : a * a ≀ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul'' [@decidable_rel Ξ± (≀)] (h1 : a < c) (h2 : b < d) (h3 : 0 ≀ a) (h4 : 0 ≀ b) : a * b < c * d := h4.lt_or_eq_dec.elim (Ξ» b0, decidable.mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (Ξ» b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma mul_lt_mul'' : a < c β†’ b < d β†’ 0 ≀ a β†’ 0 ≀ b β†’ a * b < c * d := by classical; exact decidable.mul_lt_mul'' -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_right [@decidable_rel Ξ± (≀)] (hb : 0 ≀ b) (h : 1 ≀ a) : b ≀ b * a := suffices b * 1 ≀ b * a, by rwa mul_one at this, decidable.mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_right : 0 ≀ b β†’ 1 ≀ a β†’ b ≀ b * a := by classical; exact decidable.le_mul_of_one_le_right -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_left [@decidable_rel Ξ± (≀)] (hb : 0 ≀ b) (h : 1 ≀ a) : b ≀ a * b := suffices 1 * b ≀ a * b, by rwa one_mul at this, decidable.mul_le_mul_of_nonneg_right h hb lemma le_mul_of_one_le_left : 0 ≀ b β†’ 1 ≀ a β†’ b ≀ a * b := by classical; exact decidable.le_mul_of_one_le_left -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_right [@decidable_rel Ξ± (≀)] (hb : 0 < b) (h : 1 < a) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, decidable.mul_lt_mul' (le_refl _) h zero_le_one hb lemma lt_mul_of_one_lt_right : 0 < b β†’ 1 < a β†’ b < b * a := by classical; exact decidable.lt_mul_of_one_lt_right -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_left [@decidable_rel Ξ± (≀)] (hb : 0 < b) (h : 1 < a) : b < a * b := suffices 1 * b < a * b, by rwa one_mul at this, decidable.mul_lt_mul h (le_refl _) hb (zero_le_one.trans h.le) lemma lt_mul_of_one_lt_left : 0 < b β†’ 1 < a β†’ b < a * b := by classical; exact decidable.lt_mul_of_one_lt_left -- See Note [decidable namespace] protected lemma decidable.add_le_mul_two_add [@decidable_rel Ξ± (≀)] {a b : Ξ±} (a2 : 2 ≀ a) (b0 : 0 ≀ b) : a + (2 + b) ≀ a * (2 + b) := calc a + (2 + b) ≀ a + (a + a * b) : add_le_add_left (add_le_add a2 (decidable.le_mul_of_one_le_left b0 (one_le_two.trans a2))) a ... ≀ a * (2 + b) : by rw [mul_add, mul_two, add_assoc] lemma add_le_mul_two_add {a b : Ξ±} : 2 ≀ a β†’ 0 ≀ b β†’ a + (2 + b) ≀ a * (2 + b) := by classical; exact decidable.add_le_mul_two_add -- See Note [decidable namespace] protected lemma decidable.one_le_mul_of_one_le_of_one_le [@decidable_rel Ξ± (≀)] {a b : Ξ±} (a1 : 1 ≀ a) (b1 : 1 ≀ b) : (1 : Ξ±) ≀ a * b := (mul_one (1 : Ξ±)).symm.le.trans (decidable.mul_le_mul a1 b1 zero_le_one (zero_le_one.trans a1)) lemma one_le_mul_of_one_le_of_one_le {a b : Ξ±} : 1 ≀ a β†’ 1 ≀ b β†’ (1 : Ξ±) ≀ a * b := by classical; exact decidable.one_le_mul_of_one_le_of_one_le /-- Pullback an `ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_semiring {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] (f : Ξ² β†’ Ξ±) (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) : ordered_semiring Ξ² := { zero_le_one := show f 0 ≀ f 1, by simp only [zero, one, zero_le_one], mul_lt_mul_of_pos_left := Ξ» a b c ab c0, show f (c * a) < f (c * b), begin rw [mul, mul], refine mul_lt_mul_of_pos_left ab _, rwa ← zero, end, mul_lt_mul_of_pos_right := Ξ» a b c ab c0, show f (a * c) < f (b * c), begin rw [mul, mul], refine mul_lt_mul_of_pos_right ab _, rwa ← zero, end, ..hf.ordered_cancel_add_comm_monoid f zero add, ..hf.semiring f zero one add mul } section variable [nontrivial Ξ±] lemma bit1_pos (h : 0 ≀ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : Ξ±) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : Ξ±) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end -- See Note [decidable namespace] protected lemma decidable.one_lt_mul [@decidable_rel Ξ± (≀)] (ha : 1 ≀ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : Ξ±)) β–Έ decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul : 1 ≀ a β†’ 1 < b β†’ 1 < a * b := by classical; exact decidable.one_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_le_one [@decidable_rel Ξ± (≀)] (ha : a ≀ 1) (hb' : 0 ≀ b) (hb : b ≀ 1) : a * b ≀ 1 := begin rw ← one_mul (1 : Ξ±), apply decidable.mul_le_mul; {assumption <|> apply zero_le_one} end lemma mul_le_one : a ≀ 1 β†’ 0 ≀ b β†’ b ≀ 1 β†’ a * b ≀ 1 := by classical; exact decidable.mul_le_one -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_le_of_lt [@decidable_rel Ξ± (≀)] (ha : 1 ≀ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_le_of_lt : 1 ≀ a β†’ 1 < b β†’ 1 < a * b := by classical; exact decidable.one_lt_mul_of_le_of_lt -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_lt_of_le [@decidable_rel Ξ± (≀)] (ha : 1 < a) (hb : 1 ≀ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma one_lt_mul_of_lt_of_le : 1 < a β†’ 1 ≀ b β†’ 1 < a * b := by classical; exact decidable.one_lt_mul_of_lt_of_le -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_right [@decidable_rel Ξ± (≀)] (ha : 0 ≀ a) (hb1 : b ≀ 1) : a * b ≀ a := calc a * b ≀ a * 1 : decidable.mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_right : 0 ≀ a β†’ b ≀ 1 β†’ a * b ≀ a := by classical; exact decidable.mul_le_of_le_one_right -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_left [@decidable_rel Ξ± (≀)] (hb : 0 ≀ b) (ha1 : a ≀ 1) : a * b ≀ b := calc a * b ≀ 1 * b : decidable.mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_le_of_le_one_left : 0 ≀ b β†’ a ≀ 1 β†’ a * b ≀ b := by classical; exact decidable.mul_le_of_le_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_left [@decidable_rel Ξ± (≀)] (ha0 : 0 ≀ a) (ha : a < 1) (hb : b ≀ 1) : a * b < 1 := calc a * b ≀ a : decidable.mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_left : 0 ≀ a β†’ a < 1 β†’ b ≀ 1 β†’ a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_right [@decidable_rel Ξ± (≀)] (ha : a ≀ 1) (hb0 : 0 ≀ b) (hb : b < 1) : a * b < 1 := calc a * b ≀ b : decidable.mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_lt_one_of_nonneg_of_lt_one_right : a ≀ 1 β†’ 0 ≀ b β†’ b < 1 β†’ a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_right end ordered_semiring section ordered_comm_semiring /-- An `ordered_comm_semiring Ξ±` is a commutative semiring `Ξ±` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_comm_semiring (Ξ± : Type u) extends ordered_semiring Ξ±, comm_semiring Ξ± /-- Pullback an `ordered_comm_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_semiring [ordered_comm_semiring Ξ±] {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] (f : Ξ² β†’ Ξ±) (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) : ordered_comm_semiring Ξ² := { ..hf.comm_semiring f zero one add mul, ..hf.ordered_semiring f zero one add mul } end ordered_comm_semiring /-- A `linear_ordered_semiring Ξ±` is a nontrivial semiring `Ξ±` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (Ξ± : Type u) extends ordered_semiring Ξ±, linear_ordered_add_comm_monoid Ξ±, nontrivial Ξ± section linear_ordered_semiring variables [linear_ordered_semiring Ξ±] {a b c d : Ξ±} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring Ξ±` and `nontrivial Ξ±`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : Ξ±) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≀ c) : a < b := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (assume h1 : b ≀ a, have h2 : c * b ≀ c * a, from decidable.mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≀ c) : a < b := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (assume h1 : b ≀ a, have h2 : b * c ≀ a * c, from decidable.mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≀ c * b) (hc : 0 < c) : a ≀ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≀ b * c) (hc : 0 < c) : a ≀ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin haveI := @linear_order.decidable_le Ξ± _, rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, lt_imp_lt_of_le_imp_le (Ξ» hb, _) hab⟩, exact decidable.mul_nonpos_of_nonneg_of_nonpos ha.le hb }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, lt_imp_lt_of_le_imp_le (Ξ» hb, _) hab⟩, exact decidable.mul_nonpos_of_nonpos_of_nonneg ha.le hb } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≀ a * b) : (0 ≀ a ∧ 0 ≀ b) ∨ (a ≀ 0 ∧ b ≀ 0) := begin haveI := @linear_order.decidable_le Ξ± _, refine decidable.or_iff_not_and_not.2 _, simp only [not_and, not_le], intros ab nab, apply not_lt_of_le hab _, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (ab ha.le), ((ab le_rfl).asymm (nab le_rfl)).elim, mul_neg_of_neg_of_pos ha (nab ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≀ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ Ξ» h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≀ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ Ξ» h, h.2.not_le hb).1 @[simp] lemma inv_of_pos [invertible a] : 0 < β…Ÿa ↔ 0 < a := begin have : 0 < a * β…Ÿa, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, pos_of_mul_pos_right this h.le, Ξ» h, pos_of_mul_pos_left this h.le⟩ end @[simp] lemma inv_of_nonpos [invertible a] : β…Ÿa ≀ 0 ↔ a ≀ 0 := by simp only [← not_lt, inv_of_pos] lemma nonneg_of_mul_nonneg_left (h : 0 ≀ a * b) (h1 : 0 < a) : 0 ≀ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≀ a * b) (h1 : 0 < b) : 0 ≀ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) @[simp] lemma inv_of_nonneg [invertible a] : 0 ≀ β…Ÿa ↔ 0 ≀ a := begin have : 0 < a * β…Ÿa, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, (pos_of_mul_pos_right this h).le, Ξ» h, (pos_of_mul_pos_left this h).le⟩ end @[simp] lemma inv_of_lt_zero [invertible a] : β…Ÿa < 0 ↔ a < 0 := by simp only [← not_le, inv_of_nonneg] @[simp] lemma inv_of_le_one [invertible a] (h : 1 ≀ a) : β…Ÿa ≀ 1 := by haveI := @linear_order.decidable_le Ξ± _; exact mul_inv_of_self a β–Έ decidable.le_mul_of_one_le_left (inv_of_nonneg.2 $ zero_le_one.trans h) h lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≀ a) : b < 0 := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (assume h2 : b β‰₯ 0, (decidable.mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≀ b) : a < 0 := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (assume h2 : a β‰₯ 0, (decidable.mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≀ 0) (h1 : 0 < a) : b ≀ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≀ 0) (h1 : 0 < b) : a ≀ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≀ c * b ↔ a ≀ b := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨λ h', le_of_mul_le_mul_left h' h, Ξ» h', decidable.mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≀ b * c ↔ a ≀ b := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨λ h', le_of_mul_le_mul_right h' h, Ξ» h', decidable.mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨lt_imp_lt_of_le_imp_le $ Ξ» h', decidable.mul_le_mul_of_nonneg_left h' h.le, Ξ» h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨lt_imp_lt_of_le_imp_le $ Ξ» h', decidable.mul_le_mul_of_nonneg_right h' h.le, Ξ» h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≀ c * b ↔ 0 ≀ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≀ b * c ↔ 0 ≀ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } lemma add_le_mul_of_left_le_right (a2 : 2 ≀ a) (ab : a ≀ b) : a + b ≀ a * b := have 0 < b, from calc 0 < 2 : zero_lt_two ... ≀ a : a2 ... ≀ b : ab, calc a + b ≀ b + b : add_le_add_right ab b ... = 2 * b : (two_mul b).symm ... ≀ a * b : (mul_le_mul_right this).mpr a2 lemma add_le_mul_of_right_le_left (b2 : 2 ≀ b) (ba : b ≀ a) : a + b ≀ a * b := have 0 < a, from calc 0 < 2 : zero_lt_two ... ≀ b : b2 ... ≀ a : ba, calc a + b ≀ a + a : add_le_add_left ba a ... = a * 2 : (mul_two a).symm ... ≀ a * b : (mul_le_mul_left this).mpr b2 lemma add_le_mul (a2 : 2 ≀ a) (b2 : 2 ≀ b) : a + b ≀ a * b := if hab : a ≀ b then add_le_mul_of_left_le_right a2 hab else add_le_mul_of_right_le_left b2 (le_of_not_le hab) lemma add_le_mul' (a2 : 2 ≀ a) (b2 : 2 ≀ b) : a + b ≀ b * a := (le_of_eq (add_comm _ _)).trans (add_le_mul b2 a2) section variables [nontrivial Ξ±] @[simp] lemma bit0_le_bit0 : bit0 a ≀ bit0 b ↔ a ≀ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:Ξ±))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:Ξ±))] @[simp] lemma bit1_le_bit1 : bit1 a ≀ bit1 b ↔ a ≀ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : Ξ±) ≀ bit1 a ↔ 0 ≀ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:Ξ±))] @[simp] lemma one_lt_bit1 : (1 : Ξ±) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:Ξ±))] @[simp] lemma zero_le_bit0 : (0 : Ξ±) ≀ bit0 a ↔ 0 ≀ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:Ξ±))] @[simp] lemma zero_lt_bit0 : (0 : Ξ±) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:Ξ±))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≀ a * b ↔ 1 ≀ a := suffices 1 * b ≀ a * b ↔ 1 ≀ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≀ b * a ↔ 1 ≀ a := suffices b * 1 ≀ b * a ↔ 1 ≀ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb theorem mul_nonneg_iff_right_nonneg_of_pos (ha : 0 < a) : 0 ≀ b * a ↔ 0 ≀ b := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨λ h, nonneg_of_mul_nonneg_right h ha, Ξ» h, decidable.mul_nonneg h ha.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≀ b ↔ a ≀ 1 := ⟨ Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≀ b ↔ a ≀ 1 := ⟨ Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≀ a * b) (hb : b < 0) : a ≀ 0 := le_of_not_gt (Ξ» ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≀ a * b) (ha : a < 0) : b ≀ 0 := le_of_not_gt (Ξ» hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≀ 0) : a < 0 := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (Ξ» ha, absurd h (decidable.mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≀ 0) : b < 0 := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (Ξ» hb, absurd h (decidable.mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {Ξ± : Type*} [linear_ordered_semiring Ξ±] : no_top_order Ξ± := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ /-- Pullback a `linear_ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_semiring {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] [nontrivial Ξ²] (f : Ξ² β†’ Ξ±) (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) : linear_ordered_semiring Ξ² := { ..linear_order.lift f hf, ..β€Ήnontrivial Ξ²β€Ί, ..hf.ordered_semiring f zero one add mul } end linear_ordered_semiring section mono variables {Ξ² : Type*} [linear_ordered_semiring Ξ±] [preorder Ξ²] {f g : Ξ² β†’ Ξ±} {a : Ξ±} lemma monotone_mul_left_of_nonneg (ha : 0 ≀ a) : monotone (Ξ» x, a*x) := by haveI := @linear_order.decidable_le Ξ± _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≀ a) : monotone (Ξ» x, x*a) := by haveI := @linear_order.decidable_le Ξ± _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≀ a) : monotone (Ξ» x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≀ a) : monotone (Ξ» x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : βˆ€ x, 0 ≀ f x) (hg0 : βˆ€ x, 0 ≀ g x) : monotone (Ξ» x, f x * g x) := by haveI := @linear_order.decidable_le Ξ± _; exact Ξ» x y h, decidable.mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (Ξ» x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (Ξ» x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (Ξ» x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (Ξ» x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : βˆ€ x, 0 ≀ f x) (hg0 : βˆ€ x, 0 < g x) : strict_mono (Ξ» x, f x * g x) := by haveI := @linear_order.decidable_le Ξ± _; exact Ξ» x y h, decidable.mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : βˆ€ x, 0 < f x) (hg0 : βˆ€ x, 0 ≀ g x) : strict_mono (Ξ» x, f x * g x) := by haveI := @linear_order.decidable_le Ξ± _; exact Ξ» x y h, decidable.mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : βˆ€ x, 0 ≀ f x) (hg0 : βˆ€ x, 0 ≀ g x) : strict_mono (Ξ» x, f x * g x) := by haveI := @linear_order.decidable_le Ξ± _; exact Ξ» x y h, decidable.mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring Ξ±] {a b c : Ξ±} lemma mul_max_of_nonneg (b c : Ξ±) (ha : 0 ≀ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : Ξ±) (ha : 0 ≀ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : Ξ±) (hc : 0 ≀ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : Ξ±) (hc : 0 ≀ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring Ξ±` is a ring `Ξ±` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_ring (Ξ± : Type u) extends ring Ξ±, ordered_add_comm_group Ξ± := (zero_le_one : 0 ≀ (1 : Ξ±)) (mul_pos : βˆ€ a b : Ξ±, 0 < a β†’ 0 < b β†’ 0 < a * b) section ordered_ring variables [ordered_ring Ξ±] {a b c : Ξ±} -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_nonneg [@decidable_rel Ξ± (≀)] {a b : Ξ±} (h₁ : 0 ≀ a) (hβ‚‚ : 0 ≀ b) : 0 ≀ a * b := begin by_cases ha : a ≀ 0, { simp [le_antisymm ha h₁] }, by_cases hb : b ≀ 0, { simp [le_antisymm hb hβ‚‚] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le ha) (hβ‚‚.lt_of_not_le hb))).1, end lemma ordered_ring.mul_nonneg : 0 ≀ a β†’ 0 ≀ b β†’ 0 ≀ a * b := by classical; exact decidable.ordered_ring.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_left [@decidable_rel Ξ± (≀)] (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : c * a ≀ c * b := begin rw [← sub_nonneg, ← mul_sub], exact decidable.ordered_ring.mul_nonneg hβ‚‚ (sub_nonneg.2 h₁), end lemma ordered_ring.mul_le_mul_of_nonneg_left : a ≀ b β†’ 0 ≀ c β†’ c * a ≀ c * b := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_right [@decidable_rel Ξ± (≀)] (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : a * c ≀ b * c := begin rw [← sub_nonneg, ← sub_mul], exact decidable.ordered_ring.mul_nonneg (sub_nonneg.2 h₁) hβ‚‚, end lemma ordered_ring.mul_le_mul_of_nonneg_right : a ≀ b β†’ 0 ≀ c β†’ a * c ≀ b * c := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_right lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (hβ‚‚ : 0 < c) : c * a < c * b := begin rw [← sub_pos, ← mul_sub], exact ordered_ring.mul_pos _ _ hβ‚‚ (sub_pos.2 h₁), end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (hβ‚‚ : 0 < c) : a * c < b * c := begin rw [← sub_pos, ← sub_mul], exact ordered_ring.mul_pos _ _ (sub_pos.2 h₁) hβ‚‚, end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring Ξ± := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel Ξ± _, le_of_add_le_add_left := @le_of_add_le_add_left Ξ± _ _ _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left Ξ± _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right Ξ± _, ..β€Ήordered_ring Ξ±β€Ί } -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_left [@decidable_rel Ξ± (≀)] {a b c : Ξ±} (h : b ≀ a) (hc : c ≀ 0) : c * a ≀ c * b := have -c β‰₯ 0, from neg_nonneg_of_nonpos hc, have -c * b ≀ -c * a, from decidable.mul_le_mul_of_nonneg_left h this, have -(c * b) ≀ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_left {a b c : Ξ±} : b ≀ a β†’ c ≀ 0 β†’ c * a ≀ c * b := by classical; exact decidable.mul_le_mul_of_nonpos_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_right [@decidable_rel Ξ± (≀)] {a b c : Ξ±} (h : b ≀ a) (hc : c ≀ 0) : a * c ≀ b * c := have -c β‰₯ 0, from neg_nonneg_of_nonpos hc, have b * -c ≀ a * -c, from decidable.mul_le_mul_of_nonneg_right h this, have -(b * c) ≀ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : Ξ±} : b ≀ a β†’ c ≀ 0 β†’ a * c ≀ b * c := by classical; exact decidable.mul_le_mul_of_nonpos_right -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_of_nonpos_of_nonpos [@decidable_rel Ξ± (≀)] {a b : Ξ±} (ha : a ≀ 0) (hb : b ≀ 0) : 0 ≀ a * b := have 0 * b ≀ a * b, from decidable.mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_nonneg_of_nonpos_of_nonpos {a b : Ξ±} : a ≀ 0 β†’ b ≀ 0 β†’ 0 ≀ a * b := by classical; exact decidable.mul_nonneg_of_nonpos_of_nonpos lemma mul_lt_mul_of_neg_left {a b c : Ξ±} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : Ξ±} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : Ξ±} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this /-- Pullback an `ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_ring {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] [has_neg Ξ²] [has_sub Ξ²] (f : Ξ² β†’ Ξ±) (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) : ordered_ring Ξ² := { mul_pos := Ξ» a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero }, ..hf.ordered_semiring f zero one add mul, ..hf.ring f zero one add mul neg sub } lemma le_iff_exists_nonneg_add (a b : Ξ±) : a ≀ b ↔ βˆƒ c β‰₯ 0, b = a + c := ⟨λ h, ⟨b - a, sub_nonneg.mpr h, by simp⟩, Ξ» ⟨c, hc, h⟩, by { rw [h, le_add_iff_nonneg_right], exact hc }⟩ end ordered_ring section ordered_comm_ring /-- An `ordered_comm_ring Ξ±` is a commutative ring `Ξ±` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_comm_ring (Ξ± : Type u) extends ordered_ring Ξ±, comm_ring Ξ± @[priority 100] -- See note [lower instance priority] instance ordered_comm_ring.to_ordered_comm_semiring {Ξ± : Type u} [ordered_comm_ring Ξ±] : ordered_comm_semiring Ξ± := { .. (by apply_instance : ordered_semiring Ξ±), .. β€Ήordered_comm_ring Ξ±β€Ί } /-- Pullback an `ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_ring [ordered_comm_ring Ξ±] {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] [has_neg Ξ²] [has_sub Ξ²] (f : Ξ² β†’ Ξ±) (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) : ordered_comm_ring Ξ² := { ..hf.ordered_ring f zero one add mul neg sub, ..hf.comm_ring f zero one add mul neg sub } end ordered_comm_ring /-- A `linear_ordered_ring Ξ±` is a ring `Ξ±` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class linear_ordered_ring (Ξ± : Type u) extends ordered_ring Ξ±, linear_order Ξ±, nontrivial Ξ± @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring Ξ±] : linear_ordered_add_comm_group Ξ± := { .. s } section linear_ordered_ring variables [linear_ordered_ring Ξ±] {a b c : Ξ±} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring Ξ± := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel Ξ± _, le_of_add_le_add_left := @le_of_add_le_add_left Ξ± _ _ _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left Ξ± _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right Ξ± _, le_total := linear_ordered_ring.le_total, ..β€Ήlinear_ordered_ring Ξ±β€Ί } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain Ξ± := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, refine decidable.or_iff_not_and_not.2 (Ξ» h, _), revert hab, cases lt_or_gt_of_ne h.1 with ha ha; cases lt_or_gt_of_ne h.2 with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. β€Ήlinear_ordered_ring Ξ±β€Ί } @[simp] lemma abs_one : |(1 : Ξ±)| = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : |(2 : Ξ±)| = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : Ξ±) : |a * b| = |a| * |b| := begin haveI := @linear_order.decidable_le Ξ± _, rw [abs_eq (decidable.mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp only [abs_of_nonpos, abs_of_nonneg, true_or, or_true, eq_self_iff_true, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, neg_neg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : monoid_with_zero_hom Ξ± Ξ± := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] lemma abs_mul_abs_self (a : Ξ±) : |a| * |a| = a * a := abs_by_cases (Ξ» x, x * x = a * a) rfl (neg_mul_neg a a) @[simp] lemma abs_mul_self (a : Ξ±) : |a * a| = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, Ξ» h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≀ a * b ↔ 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0 := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, Ξ» h, h.elim (and_imp.2 decidable.mul_nonneg) (and_imp.2 decidable.mul_nonneg_of_nonpos_of_nonpos)⟩ /-- Out of three elements of a `linear_ordered_ring`, two must have the same sign. -/ lemma mul_nonneg_of_three (a b c : Ξ±) : 0 ≀ a * b ∨ 0 ≀ b * c ∨ 0 ≀ c * a := by iterate 3 { rw mul_nonneg_iff }; have := le_total 0 a; have := le_total 0 b; have := le_total 0 c; itauto lemma mul_nonpos_iff : a * b ≀ 0 ↔ 0 ≀ a ∧ b ≀ 0 ∨ a ≀ 0 ∧ 0 ≀ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : Ξ±) : 0 ≀ a * a := abs_mul_self a β–Έ abs_nonneg _ @[simp] lemma neg_le_self_iff : -a ≀ a ↔ 0 ≀ a := by simp [neg_le_iff_add_nonneg, ← two_mul, mul_nonneg_iff, zero_le_one, (@zero_lt_two Ξ± _ _).not_le] @[simp] lemma neg_lt_self_iff : -a < a ↔ 0 < a := by simp [neg_lt_iff_pos_add, ← two_mul, mul_pos_iff, zero_lt_one, (@zero_lt_two Ξ± _ _).not_lt] @[simp] lemma le_neg_self_iff : a ≀ -a ↔ a ≀ 0 := calc a ≀ -a ↔ -(-a) ≀ -a : by rw neg_neg ... ↔ 0 ≀ -a : neg_le_self_iff ... ↔ a ≀ 0 : neg_nonneg @[simp] lemma lt_neg_self_iff : a < -a ↔ a < 0 := calc a < -a ↔ -(-a) < -a : by rw neg_neg ... ↔ 0 < -a : neg_lt_self_iff ... ↔ a < 0 : neg_pos @[simp] lemma abs_eq_self : |a| = a ↔ 0 ≀ a := by simp [abs_eq_max_neg] @[simp] lemma abs_eq_neg_self : |a| = -a ↔ a ≀ 0 := by simp [abs_eq_max_neg] /-- For an element `a` of a linear ordered ring, either `abs a = a` and `0 ≀ a`, or `abs a = -a` and `a < 0`. Use cases on this lemma to automate linarith in inequalities -/ lemma abs_cases (a : Ξ±) : (|a| = a ∧ 0 ≀ a) ∨ (|a| = -a ∧ a < 0) := begin by_cases 0 ≀ a, { left, exact ⟨abs_eq_self.mpr h, h⟩ }, { right, push_neg at h, exact ⟨abs_eq_neg_self.mpr (le_of_lt h), h⟩ } end lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≀ 0) : b < a := have nhc : 0 ≀ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:Ξ±) := neg_lt_zero.2 zero_lt_one lemma le_of_mul_le_of_one_le {a b c : Ξ±} (h : a * c ≀ b) (hb : 0 ≀ b) (hc : 1 ≀ c) : a ≀ b := by haveI := @linear_order.decidable_le Ξ± _; exact have h' : a * c ≀ b * c, from calc a * c ≀ b : h ... = b * 1 : by rewrite mul_one ... ≀ b * c : decidable.mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_sq_le_sq {a b : Ξ±} (hb : 0 ≀ b) (h : a * a ≀ b * b) : a ≀ b := by haveI := @linear_order.decidable_le Ξ± _; exact le_of_not_gt (Ξ»hab, (decidable.mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : Ξ±} (h1 : 0 ≀ a) (h2 : 0 ≀ b) : a ≀ b ↔ a * a ≀ b * b := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨decidable.mul_self_le_mul_self h1, nonneg_le_nonneg_of_sq_le_sq h2⟩ lemma mul_self_lt_mul_self_iff {a b : Ξ±} (h1 : 0 ≀ a) (h2 : 0 ≀ b) : a < b ↔ a * a < b * b := by haveI := @linear_order.decidable_le Ξ± _; exact ((@decidable.strict_mono_on_mul_self Ξ± _ _).lt_iff_lt h1 h2).symm lemma mul_self_inj {a b : Ξ±} (h1 : 0 ≀ a) (h2 : 0 ≀ b) : a * a = b * b ↔ a = b := by haveI := @linear_order.decidable_le Ξ± _; exact (@decidable.strict_mono_on_mul_self Ξ± _ _).inj_on.eq_iff h1 h2 @[simp] lemma mul_le_mul_left_of_neg {a b c : Ξ±} (h : c < 0) : c * a ≀ c * b ↔ b ≀ a := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨le_imp_le_of_lt_imp_lt $ Ξ» h', mul_lt_mul_of_neg_left h' h, Ξ» h', decidable.mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : Ξ±} (h : c < 0) : a * c ≀ b * c ↔ b ≀ a := by haveI := @linear_order.decidable_le Ξ± _; exact ⟨le_imp_le_of_lt_imp_lt $ Ξ» h', mul_lt_mul_of_neg_right h' h, Ξ» h', decidable.mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : Ξ±} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : Ξ±} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : Ξ±) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : Ξ±} (ha : a β‰  0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : Ξ±} (h₁ : x ≀ y) (hβ‚‚ : -x ≀ y) : x * x ≀ y * y := begin haveI := @linear_order.decidable_le Ξ± _, rw [← abs_mul_abs_self x], exact decidable.mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 hβ‚‚, hβ‚βŸ©) end lemma nonneg_of_mul_nonpos_left {a b : Ξ±} (h : a * b ≀ 0) (hb : b < 0) : 0 ≀ a := le_of_not_gt (Ξ» ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : Ξ±} (h : a * b ≀ 0) (ha : a < 0) : 0 ≀ b := le_of_not_gt (Ξ» hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : Ξ±} (h : a * b < 0) (hb : b ≀ 0) : 0 < a := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (Ξ» ha, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : Ξ±} (h : a * b < 0) (ha : a ≀ 0) : 0 < b := by haveI := @linear_order.decidable_le Ξ± _; exact lt_of_not_ge (Ξ» hb, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : Ξ±} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : |a| = |b| ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : |a| < |b| ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : |a| ≀ |b| ↔ a * a ≀ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : |a| ≀ 1 ↔ a * a ≀ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le Ξ± _ a 1 /-- Pullback a `linear_ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_ring {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] [has_neg Ξ²] [has_sub Ξ²] [nontrivial Ξ²] (f : Ξ² β†’ Ξ±) (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) : linear_ordered_ring Ξ² := { ..linear_order.lift f hf, ..β€Ήnontrivial Ξ²β€Ί, ..hf.ordered_ring f zero one add mul neg sub } end linear_ordered_ring /-- A `linear_ordered_comm_ring Ξ±` is a commutative ring `Ξ±` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class linear_ordered_comm_ring (Ξ± : Type u) extends linear_ordered_ring Ξ±, comm_monoid Ξ± @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_ordered_comm_ring [d : linear_ordered_comm_ring Ξ±] : ordered_comm_ring Ξ± := { ..d } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring Ξ±] : integral_domain Ξ± := { ..linear_ordered_ring.to_domain, ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring Ξ±] : linear_ordered_semiring Ξ± := { .. d, ..linear_ordered_ring.to_linear_ordered_semiring } section linear_ordered_comm_ring variables [linear_ordered_comm_ring Ξ±] {a b c d : Ξ±} lemma max_mul_mul_le_max_mul_max (b c : Ξ±) (ha : 0 ≀ a) (hd: 0 ≀ d) : max (a * b) (d * c) ≀ max a c * max d b := by haveI := @linear_order.decidable_le Ξ± _; exact have ba : b * a ≀ max d b * max c a, from decidable.mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≀ max a c * max b d, from decidable.mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_sq (a b : Ξ±) : |a - b| * |a - b| = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp only [mul_add, add_comm, add_left_comm, mul_comm, sub_eq_add_neg, mul_one, mul_neg_eq_neg_mul_symm, neg_add_rev, neg_neg], end end linear_ordered_comm_ring section variables [ring Ξ±] [linear_order Ξ±] {a b : Ξ±} @[simp] lemma abs_dvd (a b : Ξ±) : |a| ∣ b ↔ a ∣ b := by { cases abs_choice a with h h; simp only [h, neg_dvd] } lemma abs_dvd_self (a : Ξ±) : |a| ∣ a := (abs_dvd a a).mpr (dvd_refl a) @[simp] lemma dvd_abs (a b : Ξ±) : a ∣ |b| ↔ a ∣ b := by { cases abs_choice b with h h; simp only [h, dvd_neg] } lemma self_dvd_abs (a : Ξ±) : a ∣ |a| := (dvd_abs a a).mpr (dvd_refl a) lemma abs_dvd_abs (a b : Ξ±) : |a| ∣ |b| ↔ a ∣ b := (abs_dvd _ _).trans (dvd_abs _ _) lemma even_abs {a : Ξ±} : even (|a|) ↔ even a := dvd_abs _ _ lemma odd_abs {a : Ξ±} : odd (abs a) ↔ odd a := by { cases abs_choice a with h h; simp only [h, odd_neg] } end section linear_ordered_comm_ring variables [linear_ordered_comm_ring Ξ±] /-- Pullback a `linear_ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_comm_ring {Ξ² : Type*} [has_zero Ξ²] [has_one Ξ²] [has_add Ξ²] [has_mul Ξ²] [has_neg Ξ²] [has_sub Ξ²] [nontrivial Ξ²] (f : Ξ² β†’ Ξ±) (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) : linear_ordered_comm_ring Ξ² := { ..linear_order.lift f hf, ..β€Ήnontrivial Ξ²β€Ί, ..hf.ordered_comm_ring f zero one add mul neg sub } end linear_ordered_comm_ring namespace ring /-- A positive cone in a ring consists of a positive cone in underlying `add_comm_group`, which contains `1` and such that the positive elements are closed under multiplication. -/ @[nolint has_inhabited_instance] structure positive_cone (Ξ± : Type*) [ring Ξ±] extends add_comm_group.positive_cone Ξ± := (one_nonneg : nonneg 1) (mul_pos : βˆ€ (a b), pos a β†’ pos b β†’ pos (a * b)) /-- Forget that a positive cone in a ring respects the multiplicative structure. -/ add_decl_doc positive_cone.to_positive_cone /-- A positive cone in a ring induces a linear order if `1` is a positive element. -/ @[nolint has_inhabited_instance] structure total_positive_cone (Ξ± : Type*) [ring Ξ±] extends positive_cone Ξ±, add_comm_group.total_positive_cone Ξ± := (one_pos : pos 1) /-- Forget that a `total_positive_cone` in a ring is total. -/ add_decl_doc total_positive_cone.to_positive_cone /-- Forget that a `total_positive_cone` in a ring respects the multiplicative structure. -/ add_decl_doc total_positive_cone.to_total_positive_cone end ring namespace ordered_ring open ring /-- Construct an `ordered_ring` by designating a positive cone in an existing `ring`. -/ def mk_of_positive_cone {Ξ± : Type*} [ring Ξ±] (C : positive_cone Ξ±) : ordered_ring Ξ± := { zero_le_one := by { change C.nonneg (1 - 0), convert C.one_nonneg, simp, }, mul_pos := Ξ» x y xp yp, begin change C.pos (x*y - 0), convert C.mul_pos x y (by { convert xp, simp, }) (by { convert yp, simp, }), simp, end, ..β€Ήring Ξ±β€Ί, ..ordered_add_comm_group.mk_of_positive_cone C.to_positive_cone } end ordered_ring namespace linear_ordered_ring open ring /-- Construct a `linear_ordered_ring` by designating a positive cone in an existing `ring`. -/ def mk_of_positive_cone {Ξ± : Type*} [ring Ξ±] (C : total_positive_cone Ξ±) : linear_ordered_ring Ξ± := { exists_pair_ne := ⟨0, 1, begin intro h, have one_pos := C.one_pos, rw [←h, C.pos_iff] at one_pos, simpa using one_pos, end⟩, ..ordered_ring.mk_of_positive_cone C.to_positive_cone, ..linear_ordered_add_comm_group.mk_of_positive_cone C.to_total_positive_cone, } end linear_ordered_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≀ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_comm_semiring (Ξ± : Type*) extends canonically_ordered_add_monoid Ξ±, comm_semiring Ξ± := (eq_zero_or_eq_zero_of_mul_eq_zero : βˆ€ a b : Ξ±, a * b = 0 β†’ a = 0 ∨ b = 0) namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring Ξ±] {a b : Ξ±} @[priority 100] -- see Note [lower instance priority] instance to_no_zero_divisors : no_zero_divisors Ξ± := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance to_covariant_mul_le : covariant_class Ξ± Ξ± (*) (≀) := begin refine ⟨λ a b c h, _⟩, rcases le_iff_exists_add.1 h with ⟨c, rfl⟩, rw mul_add, apply self_le_add_right end /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial Ξ±] : (0:Ξ±) < 1 := (zero_le 1).lt_of_ne zero_ne_one @[simp] lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_comm_semiring section sub variables [canonically_ordered_comm_semiring Ξ±] {a b c : Ξ±} variables [has_sub Ξ±] [has_ordered_sub Ξ±] lemma sub_mul_ge : a * c - b * c ≀ (a - b) * c := by { rw [sub_le_iff_right, ← add_mul], exact mul_le_mul_right' le_sub_add c } lemma mul_sub_ge : a * b - a * c ≀ a * (b - c) := by simp only [mul_comm a, sub_mul_ge] variables [is_total Ξ± (≀)] namespace add_le_cancellable protected lemma mul_sub (h : add_le_cancellable (a * c)) : a * (b - c) = a * b - a * c := begin cases total_of (≀) b c with hbc hcb, { rw [sub_eq_zero_iff_le.2 hbc, mul_zero, sub_eq_zero_iff_le.2 (mul_le_mul_left' hbc a)] }, { apply h.eq_sub_of_add_eq, rw [← mul_add, sub_add_cancel_of_le hcb] } end protected lemma sub_mul (h : add_le_cancellable (b * c)) : (a - b) * c = a * c - b * c := by { simp only [mul_comm _ c] at *, exact h.mul_sub } end add_le_cancellable variables [contravariant_class Ξ± Ξ± (+) (≀)] lemma mul_sub' (a b c : Ξ±) : a * (b - c) = a * b - a * c := contravariant.add_le_cancellable.mul_sub lemma sub_mul' (a b c : Ξ±) : (a - b) * c = a * c - b * c := contravariant.add_le_cancellable.sub_mul end sub /-! ### Structures involving `*` and `0` on `with_top` and `with_bot` The main results of this section are `with_top.canonically_ordered_comm_semiring` and `with_bot.comm_monoid_with_zero`. -/ namespace with_top instance [nonempty Ξ±] : nontrivial (with_top Ξ±) := option.nontrivial variable [decidable_eq Ξ±] section has_mul variables [has_zero Ξ±] [has_mul Ξ±] instance : mul_zero_class (with_top Ξ±) := { zero := 0, mul := Ξ»m n, if m = 0 ∨ n = 0 then 0 else m.bind (Ξ»a, n.bind $ Ξ»b, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top Ξ±} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (Ξ»a, b.bind $ Ξ»b, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top Ξ±} (h : a β‰  0) : a * ⊀ = ⊀ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top Ξ±} (h : a β‰  0) : ⊀ * a = ⊀ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊀ * ⊀ : with_top Ξ±) = ⊀ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class Ξ±] @[norm_cast] lemma coe_mul {a b : Ξ±} : (↑(a * b) : with_top Ξ±) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : Ξ±} (hb : b β‰  0) : βˆ€{a : with_top Ξ±}, a * b = a.bind (Ξ»a:Ξ±, ↑(a * b)) | none := show (if (⊀:with_top Ξ±) = 0 ∨ (b:with_top Ξ±) = 0 then 0 else ⊀ : with_top Ξ±) = ⊀, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top Ξ±} : a * b = ⊀ ↔ (a β‰  0 ∧ b = ⊀) ∨ (a = ⊀ ∧ b β‰  0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊀ * (b : with_top Ξ±) = ⊀ ↔ b β‰  0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top Ξ±) * ⊀ = ⊀ ↔ a β‰  0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end lemma mul_lt_top [partial_order Ξ±] {a b : with_top Ξ±} (ha : a β‰  ⊀) (hb : b β‰  ⊀) : a * b < ⊀ := begin lift a to Ξ± using ha, lift b to Ξ± using hb, simp only [← coe_mul, coe_lt_top] end end mul_zero_class /-- `nontrivial Ξ±` is needed here as otherwise we have `1 * ⊀ = ⊀` but also `= 0 * ⊀ = 0`. -/ instance [mul_zero_one_class Ξ±] [nontrivial Ξ±] : mul_zero_one_class (with_top Ξ±) := { mul := (*), one := 1, zero := 0, one_mul := Ξ» a, match a with | none := show ((1:Ξ±) : with_top Ξ±) * ⊀ = ⊀, by simp [-with_top.coe_one] | (some a) := show ((1:Ξ±) : with_top Ξ±) * a = a, by simp [coe_mul.symm, -with_top.coe_one] end, mul_one := Ξ» a, match a with | none := show ⊀ * ((1:Ξ±) : with_top Ξ±) = ⊀, by simp [-with_top.coe_one] | (some a) := show ↑a * ((1:Ξ±) : with_top Ξ±) = a, by simp [coe_mul.symm, -with_top.coe_one] end, .. with_top.mul_zero_class } instance [mul_zero_class Ξ±] [no_zero_divisors Ξ±] : no_zero_divisors (with_top Ξ±) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ instance [semigroup_with_zero Ξ±] [no_zero_divisors Ξ±] : semigroup_with_zero (with_top Ξ±) := { mul := (*), zero := 0, mul_assoc := Ξ» a b c, begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end, .. with_top.mul_zero_class } instance [monoid_with_zero Ξ±] [no_zero_divisors Ξ±] [nontrivial Ξ±] : monoid_with_zero (with_top Ξ±) := { .. with_top.mul_zero_one_class, .. with_top.semigroup_with_zero } instance [comm_monoid_with_zero Ξ±] [no_zero_divisors Ξ±] [nontrivial Ξ±] : comm_monoid_with_zero (with_top Ξ±) := { mul := (*), zero := 0, mul_comm := Ξ» a b, begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end, .. with_top.monoid_with_zero } variables [canonically_ordered_comm_semiring Ξ±] private lemma distrib' (a b c : with_top Ξ±) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊀ = a * ⊀ + b * ⊀, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end /-- This instance requires `canonically_ordered_comm_semiring` as it is the smallest class that derives from both `non_assoc_non_unital_semiring` and `canonically_ordered_add_monoid`, both of which are required for distributivity. -/ instance [nontrivial Ξ±] : comm_semiring (with_top Ξ±) := { right_distrib := distrib', left_distrib := assume a b c, by rw [mul_comm, distrib', mul_comm b, mul_comm c]; refl, .. with_top.add_comm_monoid, .. with_top.comm_monoid_with_zero,} instance [nontrivial Ξ±] : canonically_ordered_comm_semiring (with_top Ξ±) := { .. with_top.comm_semiring, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, } end with_top namespace with_bot instance [nonempty Ξ±] : nontrivial (with_bot Ξ±) := option.nontrivial variable [decidable_eq Ξ±] section has_mul variables [has_zero Ξ±] [has_mul Ξ±] instance : mul_zero_class (with_bot Ξ±) := with_top.mul_zero_class lemma mul_def {a b : with_bot Ξ±} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (Ξ»a, b.bind $ Ξ»b, ↑(a * b)) := rfl @[simp] lemma mul_bot {a : with_bot Ξ±} (h : a β‰  0) : a * βŠ₯ = βŠ₯ := with_top.mul_top h @[simp] lemma bot_mul {a : with_bot Ξ±} (h : a β‰  0) : βŠ₯ * a = βŠ₯ := with_top.top_mul h @[simp] lemma bot_mul_bot : (βŠ₯ * βŠ₯ : with_bot Ξ±) = βŠ₯ := with_top.top_mul_top end has_mul section mul_zero_class variables [mul_zero_class Ξ±] @[norm_cast] lemma coe_mul {a b : Ξ±} : (↑(a * b) : with_bot Ξ±) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : Ξ±} (hb : b β‰  0) {a : with_bot Ξ±} : a * b = a.bind (Ξ»a:Ξ±, ↑(a * b)) := with_top.mul_coe hb @[simp] lemma mul_eq_bot_iff {a b : with_bot Ξ±} : a * b = βŠ₯ ↔ (a β‰  0 ∧ b = βŠ₯) ∨ (a = βŠ₯ ∧ b β‰  0) := with_top.mul_eq_top_iff lemma bot_lt_mul [partial_order Ξ±] {a b : with_bot Ξ±} (ha : βŠ₯ < a) (hb : βŠ₯ < b) : βŠ₯ < a * b := begin lift a to Ξ± using ne_bot_of_gt ha, lift b to Ξ± using ne_bot_of_gt hb, simp only [← coe_mul, bot_lt_coe], end end mul_zero_class /-- `nontrivial Ξ±` is needed here as otherwise we have `1 * βŠ₯ = βŠ₯` but also `= 0 * βŠ₯ = 0`. -/ instance [mul_zero_one_class Ξ±] [nontrivial Ξ±] : mul_zero_one_class (with_bot Ξ±) := with_top.mul_zero_one_class instance [mul_zero_class Ξ±] [no_zero_divisors Ξ±] : no_zero_divisors (with_bot Ξ±) := with_top.no_zero_divisors instance [semigroup_with_zero Ξ±] [no_zero_divisors Ξ±] : semigroup_with_zero (with_bot Ξ±) := with_top.semigroup_with_zero instance [monoid_with_zero Ξ±] [no_zero_divisors Ξ±] [nontrivial Ξ±] : monoid_with_zero (with_bot Ξ±) := with_top.monoid_with_zero instance [comm_monoid_with_zero Ξ±] [no_zero_divisors Ξ±] [nontrivial Ξ±] : comm_monoid_with_zero (with_bot Ξ±) := with_top.comm_monoid_with_zero instance [canonically_ordered_comm_semiring Ξ±] [nontrivial Ξ±] : comm_semiring (with_bot Ξ±) := with_top.comm_semiring end with_bot
609a7529bbb4d16c06281546b6a2a58184162112
a523fc1740c8cb84cd0fa0f4b52a760da4e32a5c
/src/missing_mathlib/linear_algebra/basic.lean
28a45135095bb3a0e4235e0bca0280854eb4d574
[]
no_license
abentkamp/spectral
a1aff51e85d30b296a81d256ced1d382345d3396
751645679ef1cb6266316349de9e492eff85484c
refs/heads/master
1,669,994,798,064
1,597,591,646,000
1,597,591,646,000
287,544,072
0
0
null
null
null
null
UTF-8
Lean
false
false
1,290
lean
import linear_algebra.basic universes u v w x variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {Ξ΄ : Type x} {ΞΉ : Type x} namespace linear_map section variables [ring Ξ±] [add_comm_group Ξ²] [add_comm_group Ξ³] [add_comm_group Ξ΄] variables [module Ξ± Ξ²] [module Ξ± Ξ³] [module Ξ± Ξ΄] variables (f g : Ξ² β†’β‚—[Ξ±] Ξ³) include Ξ± lemma comp_eq_mul (f g : Ξ² β†’β‚—[Ξ±] Ξ²) : f.comp g = f * g := rfl def restrict (f : Ξ² β†’β‚—[Ξ±] Ξ³) (p : submodule Ξ± Ξ²) (q : submodule Ξ± Ξ³) (hf : βˆ€ x ∈ p, f x ∈ q) : p β†’β‚—[Ξ±] q := { to_fun := Ξ» x, ⟨f x, hf x.1 x.2⟩, map_add' := begin intros, apply set_coe.ext, simp end, map_smul' := begin intros, apply set_coe.ext, simp end } lemma restrict_apply (f : Ξ² β†’β‚—[Ξ±] Ξ³) (p : submodule Ξ± Ξ²) (q : submodule Ξ± Ξ³) (hf : βˆ€ x ∈ p, f x ∈ q) (x : p) : f.restrict p q hf x = ⟨f x, hf x.1 x.2⟩ := rfl end end linear_map variables {R : field Ξ±} [add_comm_group Ξ²] [add_comm_group Ξ³] variables [vector_space Ξ± Ξ²] [vector_space Ξ± Ξ³] variables (p p' : submodule Ξ± Ξ²) variables {r : Ξ±} {x y : Ξ²} include R lemma vector_space.smul_neq_zero (x : Ξ²) (hr : r β‰  0) : r β€’ x = 0 ↔ x = 0 := begin have := submodule.smul_mem_iff βŠ₯ hr, rwa [submodule.mem_bot, submodule.mem_bot] at this, end
63c11f7f2d4db85ee102a7acac39f863f0478574
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/AsyncList.lean
ef64d7322d2bbdb0f456b2467bff998a725ceaf0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
4,154
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 namespace IO universe u v /-- An async IO list is like a lazy list but instead of being *unevaluated* `Thunk`s, `delayed` suffixes are `Task`s *being evaluated asynchronously*. A delayed suffix can signal the end of computation (successful or due to a failure) with a terminating value of type `Ξ΅`. -/ inductive AsyncList (Ξ΅ : Type u) (Ξ± : Type v) where | cons (hd : Ξ±) (tl : AsyncList Ξ΅ Ξ±) | delayed (tl : Task $ Except Ξ΅ $ AsyncList Ξ΅ Ξ±) | nil namespace AsyncList instance : Inhabited (AsyncList Ξ΅ Ξ±) := ⟨nil⟩ -- TODO(WN): tail-recursion without forcing sync? partial def append : AsyncList Ξ΅ Ξ± β†’ AsyncList Ξ΅ Ξ± β†’ AsyncList Ξ΅ Ξ± | cons hd tl, s => cons hd (append tl s) | delayed ttl, s => delayed (ttl.map $ Except.map (append Β· s)) | nil, s => s instance : Append (AsyncList Ξ΅ Ξ±) := ⟨append⟩ def ofList : List Ξ± β†’ AsyncList Ξ΅ Ξ± := List.foldr AsyncList.cons AsyncList.nil instance : Coe (List Ξ±) (AsyncList Ξ΅ Ξ±) := ⟨ofList⟩ /-- A stateful step computation `f` is applied iteratively, forming an async stream. The stream ends once `f` returns `none` for the first time. For cooperatively cancelling an ongoing computation, we recommend referencing a cancellation token in `f` and checking it when appropriate. -/ partial def unfoldAsync (f : StateT Οƒ (EIO Ξ΅) $ Option Ξ±) (init : Οƒ) : BaseIO (AsyncList Ξ΅ Ξ±) := do let rec step (s : Οƒ) : EIO Ξ΅ (AsyncList Ξ΅ Ξ±) := do let (aNext, sNext) ← f s match aNext with | none => return nil | some aNext => do let tNext ← EIO.asTask (step sNext) return cons aNext $ delayed tNext let tInit ← EIO.asTask (step init) return delayed tInit /-- The computed, synchronous list. If an async tail was present, returns also its terminating value. -/ partial def getAll : AsyncList Ξ΅ Ξ± β†’ List Ξ± Γ— Option Ξ΅ | cons hd tl => let ⟨l, e?⟩ := tl.getAll ⟨hd :: l, e?⟩ | nil => ⟨[], none⟩ | delayed tl => match tl.get with | Except.ok tl => tl.getAll | Except.error e => ⟨[], some e⟩ /-- Spawns a `Task` returning the prefix of elements up to (including) the first element for which `p` is true. When `p` is not true of any element, it returns the entire list. -/ partial def waitUntil (p : Ξ± β†’ Bool) : AsyncList Ξ΅ Ξ± β†’ Task (List Ξ± Γ— Option Ξ΅) | cons hd tl => if !p hd then (tl.waitUntil p).map fun ⟨l, e?⟩ => ⟨hd :: l, e?⟩ else .pure ⟨[hd], none⟩ | nil => .pure ⟨[], none⟩ | delayed tl => tl.bind fun | .ok tl => tl.waitUntil p | .error e => .pure ⟨[], some e⟩ /-- Spawns a `Task` waiting on all elements. -/ def waitAll : AsyncList Ξ΅ Ξ± β†’ Task (List Ξ± Γ— Option Ξ΅) := waitUntil (fun _ => false) /-- Spawns a `Task` acting like `List.find?` but which will wait for tail evalution when necessary to traverse the list. If the tail terminates before a matching element is found, the task throws the terminating value. -/ partial def waitFind? (p : Ξ± β†’ Bool) : AsyncList Ξ΅ Ξ± β†’ Task (Except Ξ΅ (Option Ξ±)) | nil => .pure <| .ok none | cons hd tl => if p hd then .pure <| Except.ok <| some hd else tl.waitFind? p | delayed tl => tl.bind fun | .ok tl => tl.waitFind? p | .error e => .pure <| .error e /-- Retrieve the already-computed prefix of the list. If computation has finished with an error, return it as well. -/ partial def getFinishedPrefix : AsyncList Ξ΅ Ξ± β†’ BaseIO (List Ξ± Γ— Option Ξ΅) | cons hd tl => do let ⟨tl, e?⟩ ← tl.getFinishedPrefix pure ⟨hd :: tl, e?⟩ | nil => pure ⟨[], none⟩ | delayed tl => do if (← hasFinished tl) then match tl.get with | Except.ok tl => tl.getFinishedPrefix | Except.error e => pure ⟨[], some e⟩ else pure ⟨[], none⟩ def waitHead? (as : AsyncList Ξ΅ Ξ±) : Task (Except Ξ΅ (Option Ξ±)) := as.waitFind? fun _ => true end AsyncList end IO
074c4739d133c5e47ac176db7b2d6a5c87fc2966
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/531.hlean
1325896d045754a4925ea550b027cebb4fd4b219
[ "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
4,329
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.hit Authors: Floris van Doorn Declaration of hits -/ structure diagram [class] := (Iob : Type) (Ihom : Type) (ob : Iob β†’ Type) (dom cod : Ihom β†’ Iob) (hom : Ξ (j : Ihom), ob (dom j) β†’ ob (cod j)) open eq diagram -- structure col (D : diagram) := -- (incl : Ξ {i : Iob}, ob i) -- (eq_endpoint : Ξ {j : Ihom} (x : ob (dom j)), ob (cod j)) -- set_option pp.universes true -- check @diagram -- check @col constant colimit.{u v w} : diagram.{u v w} β†’ Type.{max u v w} namespace colimit constant inclusion : Ξ  [D : diagram] {i : Iob}, ob i β†’ colimit D abbreviation ΞΉ := @inclusion constant cglue : Ξ  [D : diagram] (j : Ihom) (x : ob (dom j)), ΞΉ (hom j x) = ΞΉ x /-protected-/ constant rec : Ξ  [D : diagram] {P : colimit D β†’ Type} (Pincl : Π⦃i : Iob⦄ (x : ob i), P (ΞΉ x)) (Pglue : Ξ (j : Ihom) (x : ob (dom j)), cglue j x β–Έ Pincl (hom j x) = Pincl x) (y : colimit D), P y -- {P : my_colim f β†’ Type} (Hinc : Π⦃n : ℕ⦄ (a : A n), P (inc f a)) -- (Heq : Ξ (n : β„•) (a : A n), inc_eq f a β–Έ Hinc (f a) = Hinc a) : Ξ aa, P aa -- init_hit definition comp_incl [D : diagram] {P : colimit D β†’ Type} (Pincl : Π⦃i : Iob⦄ (x : ob i), P (ΞΉ x)) (Pglue : Ξ (j : Ihom) (x : ob (dom j)), cglue j x β–Έ Pincl (hom j x) = Pincl x) {i : Iob} (x : ob i) : rec Pincl Pglue (ΞΉ x) = Pincl x := sorry --idp --set_option pp.notation false definition comp_cglue [D : diagram] {P : colimit D β†’ Type} (Pincl : Π⦃i : Iob⦄ (x : ob i), P (ΞΉ x)) (Pglue : Ξ (j : Ihom) (x : ob (dom j)), cglue j x β–Έ Pincl (hom j x) = Pincl x) {j : Ihom} (x : ob (dom j)) : apdt (rec Pincl Pglue) (cglue j x) = sorry ⬝ Pglue j x ⬝ sorry := --the sorry's in the statement can be removed when comp_incl is definitional sorry --idp protected definition rec_on [D : diagram] {P : colimit D β†’ Type} (y : colimit D) (Pincl : Π⦃i : Iob⦄ (x : ob i), P (ΞΉ x)) (Pglue : Ξ (j : Ihom) (x : ob (dom j)), cglue j x β–Έ Pincl (hom j x) = Pincl x) : P y := colimit.rec Pincl Pglue y end colimit open colimit bool namespace pushout section universe u parameters {TL BL TR : Type.{u}} (f : TL β†’ BL) (g : TL β†’ TR) inductive pushout_ob := | tl : pushout_ob | bl : pushout_ob | tr : pushout_ob open pushout_ob definition pushout_diag [reducible] : diagram := diagram.mk pushout_ob bool (Ξ»i, pushout_ob.rec_on i TL BL TR) (Ξ»j, bool.rec_on j tl tl) (Ξ»j, bool.rec_on j bl tr) (Ξ»j, bool.rec_on j f g) local notation `D` := pushout_diag -- open bool -- definition pushout_diag : diagram := -- diagram.mk pushout_ob -- bool -- (Ξ»i, match i with | tl := TL | tr := TR | bl := BL end) -- (Ξ»j, match j with | tt := tl | ff := tl end) -- (Ξ»j, match j with | tt := bl | ff := tr end) -- (Ξ»j, match j with | tt := f | ff := g end) definition pushout := colimit pushout_diag local attribute pushout_diag [instance] definition inl (x : BL) : pushout := @ΞΉ _ _ x definition inr (x : TR) : pushout := @ΞΉ _ _ x definition coherence (x : TL) : inl (f x) = @ΞΉ _ _ x := @cglue _ _ x definition glue (x : TL) : inl (f x) = inr (g x) := @cglue _ _ x ⬝ (@cglue _ _ x)⁻¹ set_option pp.notation false protected theorem rec {P : pushout β†’ Type} --make def (Pinl : Ξ (x : BL), P (inl x)) (Pinr : Ξ (x : TR), P (inr x)) (Pglue : Ξ (x : TL), glue x β–Έ Pinl (f x) = Pinr (g x)) (y : pushout) : P y := begin fapply (@colimit.rec_on _ _ y), { intros [i, x], cases i, exact (coherence x β–Έ Pinl (f x)), apply Pinl, apply Pinr}, { intros [j, x], cases j, exact idp, esimp [pushout_ob.cases_on], apply concat, rotate 1, apply (idpath (coherence x β–Έ Pinl (f x))), apply concat, apply (ap (transport _ _)), apply (idpath (Pinr (g x))), apply eq_tr_of_inv_tr_eq, rewrite -{(transport (Ξ» (x : pushout), P x) (inverse (coherence x)) (transport P (@cglue _ tt x) (Pinr (g x))))}con_tr, apply sorry } end exit
0a77118878fef99a8ff744c1a6d87231b1d70e02
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/category/Profinite/cofiltered_limit.lean
1847a7ebbd738c30737851eea3289cb45834e22d
[ "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
9,386
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import topology.category.Profinite import topology.locally_constant.basic import topology.discrete_quotient /-! # Cofiltered limits of profinite sets. This file contains some theorems about cofiltered limits of profinite sets. ## Main Results - `exists_clopen_of_cofiltered` shows that any clopen set in a cofiltered limit of profinite sets is the pullback of a clopen set from one of the factors in the limit. - `exists_locally_constant` shows that any locally constant function from a cofiltered limit of profinite sets factors through one of the components. -/ namespace Profinite open_locale classical open category_theory open category_theory.limits universe u variables {J : Type u} [small_category J] [is_cofiltered J] {F : J β₯€ Profinite.{u}} (C : cone F) (hC : is_limit C) include hC /-- If `X` is a cofiltered limit of profinite sets, then any clopen subset of `X` arises from a clopen set in one of the terms in the limit. -/ theorem exists_clopen_of_cofiltered {U : set C.X} (hU : is_clopen U) : βˆƒ (j : J) (V : set (F.obj j)) (hV : is_clopen V), U = C.Ο€.app j ⁻¹' V := begin -- First, we have the topological basis of the cofiltered limit obtained by pulling back -- clopen sets from the factors in the limit. By continuity, all such sets are again clopen. have hB := Top.is_topological_basis_cofiltered_limit.{u} (F β‹™ Profinite.to_Top) (Profinite.to_Top.map_cone C) (is_limit_of_preserves _ hC) (Ξ» j, {W | is_clopen W}) _ (Ξ» i, is_clopen_univ) (Ξ» i U1 U2 hU1 hU2, hU1.inter hU2) _, rotate, { intros i, change topological_space.is_topological_basis {W : set (F.obj i) | is_clopen W}, apply is_topological_basis_clopen }, { rintros i j f V (hV : is_clopen _), refine ⟨hV.1.preimage _, hV.2.preimage _⟩; continuity }, -- Using this, since `U` is open, we can write `U` as a union of clopen sets all of which -- are preimages of clopens from the factors in the limit. obtain ⟨S,hS,h⟩ := hB.open_eq_sUnion hU.1, clear hB, let j : S β†’ J := Ξ» s, (hS s.2).some, let V : Ξ  (s : S), set (F.obj (j s)) := Ξ» s, (hS s.2).some_spec.some, have hV : βˆ€ (s : S), is_clopen (V s) ∧ s.1 = C.Ο€.app (j s) ⁻¹' (V s) := Ξ» s, (hS s.2).some_spec.some_spec, -- Since `U` is also closed, hence compact, it is covered by finitely many of the -- clopens constructed in the previous step. have := hU.2.is_compact.elim_finite_subcover (Ξ» s : S, C.Ο€.app (j s) ⁻¹' (V s)) _ _, rotate, { intros s, refine (hV s).1.1.preimage _, continuity }, { dsimp only, rw h, rintro x ⟨T,hT,hx⟩, refine ⟨_,⟨⟨T,hT⟩,rfl⟩,_⟩, dsimp only, rwa ← (hV ⟨T,hT⟩).2 }, -- We thus obtain a finite set `G : finset J` and a clopen set of `F.obj j` for each -- `j ∈ G` such that `U` is the union of the preimages of these clopen sets. obtain ⟨G,hG⟩ := this, -- Since `J` is cofiltered, we can find a single `j0` dominating all the `j ∈ G`. -- Pulling back all of the sets from the previous step to `F.obj j0` and taking a union, -- we obtain a clopen set in `F.obj j0` which works. obtain ⟨j0,hj0⟩ := is_cofiltered.inf_objs_exists (G.image j), let f : Ξ  (s : S) (hs : s ∈ G), j0 ⟢ j s := Ξ» s hs, (hj0 (finset.mem_image.mpr ⟨s,hs,rfl⟩)).some, let W : S β†’ set (F.obj j0) := Ξ» s, if hs : s ∈ G then F.map (f s hs) ⁻¹' (V s) else set.univ, -- Conclude, using the `j0` and the clopen set of `F.obj j0` obtained above. refine ⟨j0, ⋃ (s : S) (hs : s ∈ G), W s, _, _⟩, { apply is_clopen_bUnion_finset, intros s hs, dsimp only [W], rw dif_pos hs, refine ⟨(hV s).1.1.preimage _, (hV s).1.2.preimage _⟩; continuity }, { ext x, split, { intro hx, simp_rw [set.preimage_Union, set.mem_Union], obtain ⟨_, ⟨s,rfl⟩, _, ⟨hs, rfl⟩, hh⟩ := hG hx, refine ⟨s, hs, _⟩, dsimp only [W] at hh ⊒, rwa [dif_pos hs, ← set.preimage_comp, ← Profinite.coe_comp, C.w] }, { intro hx, simp_rw [set.preimage_Union, set.mem_Union] at hx, obtain ⟨s,hs,hx⟩ := hx, rw h, refine ⟨s.1,s.2,_⟩, rw (hV s).2, dsimp only [W] at hx, rwa [dif_pos hs, ← set.preimage_comp, ← Profinite.coe_comp, C.w] at hx } } end lemma exists_locally_constant_fin_two (f : locally_constant C.X (fin 2)) : βˆƒ (j : J) (g : locally_constant (F.obj j) (fin 2)), f = g.comap (C.Ο€.app _) := begin let U := f ⁻¹' {0}, have hU : is_clopen U := f.is_locally_constant.is_clopen_fiber _, obtain ⟨j,V,hV,h⟩ := exists_clopen_of_cofiltered C hC hU, use [j, locally_constant.of_clopen hV], apply locally_constant.locally_constant_eq_of_fiber_zero_eq, rw locally_constant.coe_comap _ _ (C.Ο€.app j).continuous, conv_rhs { rw set.preimage_comp }, rw [locally_constant.of_clopen_fiber_zero hV, ← h], end theorem exists_locally_constant_finite_aux {Ξ± : Type*} [finite Ξ±] (f : locally_constant C.X Ξ±) : βˆƒ (j : J) (g : locally_constant (F.obj j) (Ξ± β†’ fin 2)), f.map (Ξ» a b, if a = b then (0 : fin 2) else 1) = g.comap (C.Ο€.app _) := begin casesI nonempty_fintype Ξ±, let ΞΉ : Ξ± β†’ Ξ± β†’ fin 2 := Ξ» x y, if x = y then 0 else 1, let ff := (f.map ΞΉ).flip, have hff := Ξ» (a : Ξ±), exists_locally_constant_fin_two _ hC (ff a), choose j g h using hff, let G : finset J := finset.univ.image j, obtain ⟨j0,hj0⟩ := is_cofiltered.inf_objs_exists G, have hj : βˆ€ a, j a ∈ G, { intros a, simp [G] }, let fs : Ξ  (a : Ξ±), j0 ⟢ j a := Ξ» a, (hj0 (hj a)).some, let gg : Ξ± β†’ locally_constant (F.obj j0) (fin 2) := Ξ» a, (g a).comap (F.map (fs _)), let ggg := locally_constant.unflip gg, refine ⟨j0, ggg, _⟩, have : f.map ΞΉ = locally_constant.unflip (f.map ΞΉ).flip, by simp, rw this, clear this, have : locally_constant.comap (C.Ο€.app j0) ggg = locally_constant.unflip (locally_constant.comap (C.Ο€.app j0) ggg).flip, by simp, rw this, clear this, congr' 1, ext1 a, change ff a = _, rw h, dsimp [ggg, gg], ext1, repeat { rw locally_constant.coe_comap, dsimp [locally_constant.flip, locally_constant.unflip] }, { congr' 1, change _ = ((C.Ο€.app j0) ≫ (F.map (fs a))) x, rw C.w }, all_goals { continuity }, end theorem exists_locally_constant_finite_nonempty {Ξ± : Type*} [finite Ξ±] [nonempty Ξ±] (f : locally_constant C.X Ξ±) : βˆƒ (j : J) (g : locally_constant (F.obj j) Ξ±), f = g.comap (C.Ο€.app _) := begin inhabit Ξ±, obtain ⟨j,gg,h⟩ := exists_locally_constant_finite_aux _ hC f, let ΞΉ : Ξ± β†’ Ξ± β†’ fin 2 := Ξ» a b, if a = b then 0 else 1, let Οƒ : (Ξ± β†’ fin 2) β†’ Ξ± := Ξ» f, if h : βˆƒ (a : Ξ±), ΞΉ a = f then h.some else arbitrary _, refine ⟨j, gg.map Οƒ, _⟩, ext, rw locally_constant.coe_comap _ _ (C.Ο€.app j).continuous, dsimp [Οƒ], have h1 : ΞΉ (f x) = gg (C.Ο€.app j x), { change f.map (Ξ» a b, if a = b then (0 : fin 2) else 1) x = _, rw [h, locally_constant.coe_comap _ _ (C.Ο€.app j).continuous] }, have h2 : βˆƒ a : Ξ±, ΞΉ a = gg (C.Ο€.app j x) := ⟨f x, h1⟩, rw dif_pos h2, apply_fun ΞΉ, { rw h2.some_spec, exact h1 }, { intros a b hh, apply_fun (Ξ» e, e a) at hh, dsimp [ΞΉ] at hh, rw if_pos rfl at hh, split_ifs at hh with hh1 hh1, { exact hh1.symm }, { exact false.elim (bot_ne_top hh) } } end /-- Any locally constant function from a cofiltered limit of profinite sets factors through one of the components. -/ theorem exists_locally_constant {Ξ± : Type*} (f : locally_constant C.X Ξ±) : βˆƒ (j : J) (g : locally_constant (F.obj j) Ξ±), f = g.comap (C.Ο€.app _) := begin let S := f.discrete_quotient, let ff : S β†’ Ξ± := f.lift, casesI is_empty_or_nonempty S, { suffices : βˆƒ j, is_empty (F.obj j), { refine this.imp (Ξ» j hj, _), refine ⟨⟨hj.elim, Ξ» A, _⟩, _⟩, { convert is_open_empty, exact @set.eq_empty_of_is_empty _ hj _ }, { ext x, exact hj.elim' (C.Ο€.app j x) } }, simp only [← not_nonempty_iff, ← not_forall], intros h, haveI : βˆ€ j : J, nonempty ((F β‹™ Profinite.to_Top).obj j) := h, haveI : βˆ€ j : J, t2_space ((F β‹™ Profinite.to_Top).obj j) := Ξ» j, (infer_instance : t2_space (F.obj j)), haveI : βˆ€ j : J, compact_space ((F β‹™ Profinite.to_Top).obj j) := Ξ» j, (infer_instance : compact_space (F.obj j)), have cond := Top.nonempty_limit_cone_of_compact_t2_cofiltered_system (F β‹™ Profinite.to_Top), suffices : nonempty C.X, from is_empty.false (S.proj this.some), let D := Profinite.to_Top.map_cone C, have hD : is_limit D := is_limit_of_preserves Profinite.to_Top hC, have CD := (hD.cone_point_unique_up_to_iso (Top.limit_cone_is_limit.{u} _)).inv, exact cond.map CD }, { let f' : locally_constant C.X S := ⟨S.proj, S.proj_is_locally_constant⟩, obtain ⟨j, g', hj⟩ := exists_locally_constant_finite_nonempty _ hC f', refine ⟨j, ⟨ff ∘ g', g'.is_locally_constant.comp _⟩,_⟩, ext1 t, apply_fun (Ξ» e, e t) at hj, rw locally_constant.coe_comap _ _ (C.Ο€.app j).continuous at hj ⊒, dsimp at hj ⊒, rw ← hj, refl }, end end Profinite
e939f7abc9f6bdedf358fde1edb0172bde09231b
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/products/associator.lean
7f28870feda5c9d14f3b598437e712e7b9cfde99
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,710
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.products.basic /-# The associator functor `((C Γ— D) Γ— E) β₯€ (C Γ— (D Γ— E))` and its inverse form an equivalence. -/ universes v₁ vβ‚‚ v₃ u₁ uβ‚‚ u₃ open category_theory namespace category_theory.prod variables (C : Type u₁) [category.{v₁} C] (D : Type uβ‚‚) [category.{vβ‚‚} D] (E : Type u₃) [category.{v₃} E] -- Here and below we specify explicitly the projections to generate `@[simp]` lemmas for, -- as the default behaviour of `@[simps]` will generate projections all the way down to components of pairs. @[simps obj map] def associator : ((C Γ— D) Γ— E) β₯€ (C Γ— (D Γ— E)) := { obj := Ξ» X, (X.1.1, (X.1.2, X.2)), map := Ξ» _ _ f, (f.1.1, (f.1.2, f.2)) } @[simps obj map] def inverse_associator : (C Γ— (D Γ— E)) β₯€ ((C Γ— D) Γ— E) := { obj := Ξ» X, ((X.1, X.2.1), X.2.2), map := Ξ» _ _ f, ((f.1, f.2.1), f.2.2) } def associativity : (C Γ— D) Γ— E β‰Œ C Γ— (D Γ— E) := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (Ξ» X, eq_to_iso (by simp)) (by tidy)) (nat_iso.of_components (Ξ» X, eq_to_iso (by simp)) (by tidy)) instance associator_is_equivalence : is_equivalence (associator C D E) := (by apply_instance : is_equivalence (associativity C D E).functor) instance inverse_associator_is_equivalence : is_equivalence (inverse_associator C D E) := (by apply_instance : is_equivalence (associativity C D E).inverse) -- TODO unitors? -- TODO pentagon natural transformation? ...satisfying? end category_theory.prod
315df9ade0c313457cfe1adfacf62071807cec8a
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/star/basic.lean
b7dbb0850fa2b85c752d7772454c9d405462410d
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,350
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison. -/ import tactic.apply_fun import algebra.ordered_ring import algebra.big_operators.basic import data.equiv.ring /-! # Star monoids and star rings We introduce the basic algebraic notions of star monoids, and star rings. Star algebras are introduced in `algebra.algebra.star`. These are implemented as "mixin" typeclasses, so to summon a star ring (for example) one needs to write `(R : Type) [ring R] [star_ring R]`. This avoids difficulties with diamond inheritance. For now we simply do not introduce notations, as different users are expected to feel strongly about the relative merits of `r^*`, `r†`, `rᘁ`, and so on. Our star rings are actually star semirings, but of course we can prove `star_neg : star (-r) = - star r` when the underlying semiring is a ring. -/ universes u v /-- Notation typeclass (with no default notation!) for an algebraic structure with a star operation. -/ class has_star (R : Type u) := (star : R β†’ R) variables {R : Type u} /-- A star operation (e.g. complex conjugate). -/ def star [has_star R] (r : R) : R := has_star.star r /-- Typeclass for a star operation with is involutive. -/ class has_involutive_star (R : Type u) extends has_star R := (star_involutive : function.involutive star) @[simp] lemma star_star [has_involutive_star R] (r : R) : star (star r) = r := has_involutive_star.star_involutive _ lemma star_injective [has_involutive_star R] : function.injective (star : R β†’ R) := has_involutive_star.star_involutive.injective /-- A `*`-monoid is a monoid `R` with an involutive operations `star` so `star (r * s) = star s * star r`. -/ class star_monoid (R : Type u) [monoid R] extends has_involutive_star R := (star_mul : βˆ€ r s : R, star (r * s) = star s * star r) @[simp] lemma star_mul [monoid R] [star_monoid R] (r s : R) : star (r * s) = star s * star r := star_monoid.star_mul r s /-- `star` as an `mul_equiv` from `R` to `Rα΅’α΅–` -/ @[simps apply] def star_mul_equiv [monoid R] [star_monoid R] : R ≃* Rα΅’α΅– := { to_fun := Ξ» x, opposite.op (star x), map_mul' := Ξ» x y, (star_mul x y).symm β–Έ (opposite.op_mul _ _), ..(has_involutive_star.star_involutive.to_equiv star).trans opposite.equiv_to_opposite} variables (R) @[simp] lemma star_one [monoid R] [star_monoid R] : star (1 : R) = 1 := begin have := congr_arg opposite.unop (star_mul_equiv : R ≃* Rα΅’α΅–).map_one, rwa [star_mul_equiv_apply, opposite.unop_op, opposite.unop_one] at this, end variables {R} /-- A `*`-ring `R` is a (semi)ring with an involutive `star` operation which is additive which makes `R` with its multiplicative structure into a `*`-monoid (i.e. `star (r * s) = star s * star r`). -/ class star_ring (R : Type u) [semiring R] extends star_monoid R := (star_add : βˆ€ r s : R, star (r + s) = star r + star s) @[simp] lemma star_add [semiring R] [star_ring R] (r s : R) : star (r + s) = star r + star s := star_ring.star_add r s /-- `star` as an `add_equiv` -/ @[simps apply] def star_add_equiv [semiring R] [star_ring R] : R ≃+ R := { to_fun := star, map_add' := star_add, ..(has_involutive_star.star_involutive.to_equiv star)} variables (R) @[simp] lemma star_zero [semiring R] [star_ring R] : star (0 : R) = 0 := (star_add_equiv : R ≃+ R).map_zero variables {R} /-- `star` as an `ring_equiv` from `R` to `Rα΅’α΅–` -/ @[simps apply] def star_ring_equiv [semiring R] [star_ring R] : R ≃+* Rα΅’α΅– := { to_fun := Ξ» x, opposite.op (star x), ..star_add_equiv.trans (opposite.op_add_equiv : R ≃+ Rα΅’α΅–), ..star_mul_equiv} section open_locale big_operators @[simp] lemma star_sum [semiring R] [star_ring R] {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β†’ R): star (βˆ‘ x in s, f x) = βˆ‘ x in s, star (f x) := (star_add_equiv : R ≃+ R).map_sum _ _ end @[simp] lemma star_neg [ring R] [star_ring R] (r : R) : star (-r) = - star r := (star_add_equiv : R ≃+ R).map_neg _ @[simp] lemma star_sub [ring R] [star_ring R] (r s : R) : star (r - s) = star r - star s := (star_add_equiv : R ≃+ R).map_sub _ _ @[simp] lemma star_bit0 [ring R] [star_ring R] (r : R) : star (bit0 r) = bit0 (star r) := by simp [bit0] @[simp] lemma star_bit1 [ring R] [star_ring R] (r : R) : star (bit1 r) = bit1 (star r) := by simp [bit1] /-- Any commutative semiring admits the trivial `*`-structure. -/ def star_ring_of_comm {R : Type*} [comm_semiring R] : star_ring R := { star := id, star_involutive := Ξ» x, by simp, star_mul := by simp [mul_comm], star_add := by simp, } section local attribute [instance] star_ring_of_comm @[simp] lemma star_id_of_comm {R : Type*} [comm_semiring R] {x : R} : star x = x := rfl end /-- An ordered `*`-ring is a ring which is both an ordered ring and a `*`-ring, and `0 ≀ star r * r` for every `r`. (In a Banach algebra, the natural ordering is given by the positive cone which is the closure of the sums of elements `star r * r`. This ordering makes the Banach algebra an ordered `*`-ring.) -/ class star_ordered_ring (R : Type u) [ordered_semiring R] extends star_ring R := (star_mul_self_nonneg : βˆ€ r : R, 0 ≀ star r * r) lemma star_mul_self_nonneg [ordered_semiring R] [star_ordered_ring R] {r : R} : 0 ≀ star r * r := star_ordered_ring.star_mul_self_nonneg r
e1a464e687280fb84ea17ecb66b2f0709ab58c10
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/fintype/card_embedding.lean
f5f3a810df06b0a1b1f6c7f6446c5536e4c1f11d
[ "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
1,904
lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import data.fintype.card import logic.equiv.fin import logic.equiv.embedding /-! # Number of embeddings This file establishes the cardinality of `Ξ± β†ͺ Ξ²` in full generality. -/ local notation `|` x `|` := finset.card x local notation `β€–` x `β€–` := fintype.card x open function open_locale nat big_operators namespace fintype lemma card_embedding_eq_of_unique {Ξ± Ξ² : Type*} [unique Ξ±] [fintype Ξ²] [fintype (Ξ± β†ͺ Ξ²)] : β€–Ξ± β†ͺ Ξ²β€– = β€–Ξ²β€– := card_congr equiv.unique_embedding_equiv_result /- Establishes the cardinality of the type of all injections between two finite types. -/ @[simp] theorem card_embedding_eq {Ξ± Ξ²} [fintype Ξ±] [fintype Ξ²] [fintype (Ξ± β†ͺ Ξ²)] : β€–Ξ± β†ͺ Ξ²β€– = (β€–Ξ²β€–.desc_factorial β€–Ξ±β€–) := begin classical, unfreezingI { induction β€Ήfintype Ξ±β€Ί using fintype.induction_empty_option with α₁ Ξ±β‚‚ hβ‚‚ e ih Ξ± h ih }, { letI := fintype.of_equiv _ e.symm, rw [← card_congr (equiv.embedding_congr e (equiv.refl Ξ²)), ih, card_congr e] }, { rw [card_pempty, nat.desc_factorial_zero, card_eq_one_iff], exact ⟨embedding.of_is_empty, Ξ» x, fun_like.ext _ _ is_empty_elim⟩ }, { rw [card_option, nat.desc_factorial_succ, card_congr (embedding.option_embedding_equiv Ξ± Ξ²), card_sigma, ← ih], simp only [fintype.card_compl_set, fintype.card_range, finset.sum_const, finset.card_univ, smul_eq_mul, mul_comm] }, end /- The cardinality of embeddings from an infinite type to a finite type is zero. This is a re-statement of the pigeonhole principle. -/ @[simp] lemma card_embedding_eq_of_infinite {Ξ± Ξ²} [infinite Ξ±] [fintype Ξ²] [fintype (Ξ± β†ͺ Ξ²)] : β€–Ξ± β†ͺ Ξ²β€– = 0 := card_eq_zero_iff.mpr function.embedding.is_empty end fintype
2b575f1ce918ce6e6581dde6204af409766c6992
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/complete_boolean_algebra.lean
a715c84bc3f9350af969903828405e946cd1ba71
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
7,018
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl -/ import order.complete_lattice /-! # Completely distributive lattices and Boolean algebras In this file there are definitions and an API for completely distributive lattices and completely distributive Boolean algebras. ## Typeclasses * `complete_distrib_lattice`: Completely distributive lattices: A complete lattice whose `βŠ“` and `βŠ”` distribute over `⨆` and `β¨…` respectively. * `complete_boolean_algebra`: Completely distributive Boolean algebra: A Boolean algebra whose `βŠ“` and `βŠ”` distribute over `⨆` and `β¨…` respectively. -/ set_option old_structure_cmd true universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {ΞΉ : Sort w} /-- A complete distributive lattice is a bit stronger than the name might suggest; perhaps completely distributive lattice is more descriptive, as this class includes a requirement that the lattice join distribute over *arbitrary* infima, and similarly for the dual. -/ class complete_distrib_lattice Ξ± extends complete_lattice Ξ± := (infi_sup_le_sup_Inf : βˆ€ a s, (β¨… b ∈ s, a βŠ” b) ≀ a βŠ” Inf s) (inf_Sup_le_supr_inf : βˆ€ a s, a βŠ“ Sup s ≀ (⨆ b ∈ s, a βŠ“ b)) section complete_distrib_lattice variables [complete_distrib_lattice Ξ±] {a b : Ξ±} {s t : set Ξ±} instance : complete_distrib_lattice (order_dual Ξ±) := { infi_sup_le_sup_Inf := complete_distrib_lattice.inf_Sup_le_supr_inf, inf_Sup_le_supr_inf := complete_distrib_lattice.infi_sup_le_sup_Inf, .. order_dual.complete_lattice Ξ± } theorem sup_Inf_eq : a βŠ” Inf s = (β¨… b ∈ s, a βŠ” b) := sup_Inf_le_infi_sup.antisymm (complete_distrib_lattice.infi_sup_le_sup_Inf _ _) theorem Inf_sup_eq : Inf s βŠ” b = (β¨… a ∈ s, a βŠ” b) := by simpa only [sup_comm] using @sup_Inf_eq Ξ± _ b s theorem inf_Sup_eq : a βŠ“ Sup s = (⨆ b ∈ s, a βŠ“ b) := (complete_distrib_lattice.inf_Sup_le_supr_inf _ _).antisymm supr_inf_le_inf_Sup theorem Sup_inf_eq : Sup s βŠ“ b = (⨆ a ∈ s, a βŠ“ b) := by simpa only [inf_comm] using @inf_Sup_eq Ξ± _ b s theorem supr_inf_eq (f : ΞΉ β†’ Ξ±) (a : Ξ±) : (⨆ i, f i) βŠ“ a = ⨆ i, f i βŠ“ a := by rw [supr, Sup_inf_eq, supr_range] theorem inf_supr_eq (a : Ξ±) (f : ΞΉ β†’ Ξ±) : a βŠ“ (⨆ i, f i) = ⨆ i, a βŠ“ f i := by simpa only [inf_comm] using supr_inf_eq f a theorem infi_sup_eq (f : ΞΉ β†’ Ξ±) (a : Ξ±) : (β¨… i, f i) βŠ” a = β¨… i, f i βŠ” a := @supr_inf_eq (order_dual Ξ±) _ _ _ _ theorem sup_infi_eq (a : Ξ±) (f : ΞΉ β†’ Ξ±) : a βŠ” (β¨… i, f i) = β¨… i, a βŠ” f i := @inf_supr_eq (order_dual Ξ±) _ _ _ _ theorem bsupr_inf_eq {p : Ξ± β†’ Prop} {f : Ξ  i (hi : p i), Ξ±} (a : Ξ±) : (⨆ i hi, f i hi) βŠ“ a = ⨆ i hi, f i hi βŠ“ a := by simp only [supr_inf_eq] theorem inf_bsupr_eq (a : Ξ±) {p : Ξ± β†’ Prop} {f : Ξ  i (hi : p i), Ξ±} : a βŠ“ (⨆ i hi, f i hi) = ⨆ i hi, a βŠ“ f i hi := by simp only [inf_supr_eq] theorem binfi_sup_eq {p : Ξ± β†’ Prop} {f : Ξ  i (hi : p i), Ξ±} (a : Ξ±) : (β¨… i hi, f i hi) βŠ” a = β¨… i hi, f i hi βŠ” a := @bsupr_inf_eq (order_dual Ξ±) _ _ _ _ theorem sup_binfi_eq (a : Ξ±) {p : Ξ± β†’ Prop} {f : Ξ  i (hi : p i), Ξ±} : a βŠ” (β¨… i hi, f i hi) = β¨… i hi, a βŠ” f i hi := @inf_bsupr_eq (order_dual Ξ±) _ _ _ _ instance pi.complete_distrib_lattice {ΞΉ : Type*} {Ο€ : ΞΉ β†’ Type*} [βˆ€ i, complete_distrib_lattice (Ο€ i)] : complete_distrib_lattice (Ξ  i, Ο€ i) := { infi_sup_le_sup_Inf := Ξ» a s i, by simp only [← sup_infi_eq, complete_lattice.Inf, Inf_apply, ←infi_subtype'', infi_apply, pi.sup_apply], inf_Sup_le_supr_inf := Ξ» a s i, by simp only [complete_lattice.Sup, Sup_apply, supr_apply, pi.inf_apply, inf_supr_eq, ← supr_subtype''], .. pi.complete_lattice } theorem Inf_sup_Inf : Inf s βŠ” Inf t = (β¨… p ∈ s Γ—Λ’ t, (p : Ξ± Γ— Ξ±).1 βŠ” p.2) := begin apply le_antisymm, { simp only [and_imp, prod.forall, le_infi_iff, set.mem_prod], intros a b ha hb, exact sup_le_sup (Inf_le ha) (Inf_le hb) }, { have : βˆ€ a ∈ s, (β¨… p ∈ s Γ—Λ’ t, (p : Ξ± Γ— Ξ±).1 βŠ” p.2) ≀ a βŠ” Inf t, { rintro a ha, have : (β¨… p ∈ s Γ—Λ’ t, ((p : Ξ± Γ— Ξ±).1 : Ξ±) βŠ” p.2) ≀ (β¨… p ∈ prod.mk a '' t, (p : Ξ± Γ— Ξ±).1 βŠ” p.2), { apply infi_le_infi_of_subset, rintro ⟨x, y⟩, simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, exists_imp_distrib], rintro x' x't ax x'y, rw [← x'y, ← ax], simp [ha, x't] }, rw [infi_image] at this, simp only at this, rwa ← sup_Inf_eq at this }, calc (β¨… p ∈ s Γ—Λ’ t, (p : Ξ± Γ— Ξ±).1 βŠ” p.2) ≀ (β¨… a ∈ s, a βŠ” Inf t) : by simp; exact this ... = Inf s βŠ” Inf t : Inf_sup_eq.symm } end theorem Sup_inf_Sup : Sup s βŠ“ Sup t = (⨆ p ∈ s Γ—Λ’ t, (p : Ξ± Γ— Ξ±).1 βŠ“ p.2) := @Inf_sup_Inf (order_dual Ξ±) _ _ _ lemma supr_disjoint_iff {f : ΞΉ β†’ Ξ±} : disjoint (⨆ i, f i) a ↔ βˆ€ i, disjoint (f i) a := by simp only [disjoint_iff, supr_inf_eq, supr_eq_bot] lemma disjoint_supr_iff {f : ΞΉ β†’ Ξ±} : disjoint a (⨆ i, f i) ↔ βˆ€ i, disjoint a (f i) := by simpa only [disjoint.comm] using @supr_disjoint_iff _ _ _ a f end complete_distrib_lattice @[priority 100] -- see Note [lower instance priority] instance complete_distrib_lattice.to_distrib_lattice [d : complete_distrib_lattice Ξ±] : distrib_lattice Ξ± := { le_sup_inf := Ξ» x y z, by rw [← Inf_pair, ← Inf_pair, sup_Inf_eq, ← Inf_image, set.image_pair], ..d } /-- A complete Boolean algebra is a completely distributive Boolean algebra. -/ class complete_boolean_algebra Ξ± extends boolean_algebra Ξ±, complete_distrib_lattice Ξ± instance pi.complete_boolean_algebra {ΞΉ : Type*} {Ο€ : ΞΉ β†’ Type*} [βˆ€ i, complete_boolean_algebra (Ο€ i)] : complete_boolean_algebra (Ξ  i, Ο€ i) := { .. pi.boolean_algebra, .. pi.complete_distrib_lattice } instance Prop.complete_boolean_algebra : complete_boolean_algebra Prop := { infi_sup_le_sup_Inf := Ξ» p s, iff.mp $ by simp only [forall_or_distrib_left, complete_lattice.Inf, infi_Prop_eq, sup_Prop_eq], inf_Sup_le_supr_inf := Ξ» p s, iff.mp $ by simp only [complete_lattice.Sup, exists_and_distrib_left, inf_Prop_eq, supr_Prop_eq], .. Prop.boolean_algebra, .. Prop.complete_lattice } section complete_boolean_algebra variables [complete_boolean_algebra Ξ±] {a b : Ξ±} {s : set Ξ±} {f : ΞΉ β†’ Ξ±} theorem compl_infi : (infi f)ᢜ = (⨆ i, (f i)ᢜ) := le_antisymm (compl_le_of_compl_le $ le_infi $ Ξ» i, compl_le_of_compl_le $ le_supr (compl ∘ f) i) (supr_le $ Ξ» i, compl_le_compl $ infi_le _ _) theorem compl_supr : (supr f)ᢜ = (β¨… i, (f i)ᢜ) := compl_injective (by simp [compl_infi]) theorem compl_Inf : (Inf s)ᢜ = (⨆ i ∈ s, iᢜ) := by simp only [Inf_eq_infi, compl_infi] theorem compl_Sup : (Sup s)ᢜ = (β¨… i ∈ s, iᢜ) := by simp only [Sup_eq_supr, compl_supr] end complete_boolean_algebra
a70b912e131c85e312f8d0fcad63d95fd8eee9a6
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/match1.lean
e1b8298ed5cbdf94bc4b103c98235a47a2037c06
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
738
lean
import data.nat.basic open nat definition two1 : nat := 2 definition two2 : nat := succ (succ (zero)) constant f : nat β†’ nat β†’ nat (* local tc = type_checker_with_hints(get_env()) local plugin = whnf_match_plugin(tc) function tst_match(p, t) local r1, r2 = match(p, t, plugin) assert(r1) print("--------------") for i = 1, #r1 do print(" expr:#" .. i .. " := " .. tostring(r1[i])) end for i = 1, #r2 do print(" lvl:#" .. i .. " := " .. tostring(r2[i])) end end local nat = Const("nat") local f = Const("f") local two1 = Const("two1") local two2 = Const("two2") local succ = Const({"nat", "succ"}) local V0 = mk_idx_metavar(0, nat) tst_match(f(succ(V0), two1), f(two2, two2)) *)
5d2316b52bf51fc07ac4306ce776ab4d28a5f6e0
94e33a31faa76775069b071adea97e86e218a8ee
/src/model_theory/skolem.lean
8557251d5c8c0f048737e46a7b7c765b2d18b36e
[ "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
6,049
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import model_theory.elementary_maps /-! # Skolem Functions and Downward LΓΆwenheim–Skolem ## Main Definitions * `first_order.language.skolem₁` is a language consisting of Skolem functions for another language. ## Main Results * `first_order.language.exists_elementary_substructure_card_eq` is the Downward LΓΆwenheim–Skolem theorem: If `s` is a set in an `L`-structure `M` and `ΞΊ` an infinite cardinal such that `max (# s, L.card) ≀ ΞΊ` and `ΞΊ ≀ # M`, then `M` has an elementary substructure containing `s` of cardinality `ΞΊ`. ## TODO * Use `skolem₁` recursively to construct an actual Skolemization of a language. -/ universes u v w w' namespace first_order namespace language open Structure cardinal open_locale cardinal variables (L : language.{u v}) {M : Type w} [nonempty M] [L.Structure M] /-- A language consisting of Skolem functions for another language. Called `skolem₁` because it is the first step in building a Skolemization of a language. -/ @[simps] def skolem₁ : language := ⟨λ n, L.bounded_formula empty (n + 1), Ξ» _, empty⟩ variables {L} theorem card_functions_sum_skolem₁ : # (Ξ£ n, (L.sum L.skolem₁).functions n) = # (Ξ£ n, L.bounded_formula empty (n + 1)) := begin simp only [card_functions_sum, skolem₁_functions, lift_id', mk_sigma, sum_add_distrib'], rw [add_comm, add_eq_max, max_eq_left], { refine sum_le_sum _ _ (Ξ» n, _), rw [← lift_le, lift_lift, lift_mk_le], refine ⟨⟨λ f, (func f default).bd_equal (func f default), Ξ» f g h, _⟩⟩, rcases h with ⟨rfl, ⟨rfl⟩⟩, refl }, { rw ← mk_sigma, exact infinite_iff.1 (infinite.of_injective (Ξ» n, ⟨n, βŠ₯⟩) (Ξ» x y xy, (sigma.mk.inj xy).1)) } end theorem card_functions_sum_skolem₁_le : # (Ξ£ n, (L.sum L.skolem₁).functions n) ≀ max β„΅β‚€ L.card := begin rw card_functions_sum_skolem₁, transitivity # (Ξ£ n, L.bounded_formula empty n), { exact ⟨⟨sigma.map nat.succ (Ξ» _, id), nat.succ_injective.sigma_map (Ξ» _, function.injective_id)⟩⟩ }, { refine trans bounded_formula.card_le (lift_le.1 _), simp only [mk_empty, lift_zero, lift_uzero, zero_add] } end /-- The structure assigning each function symbol of `L.skolem₁` to a skolem function generated with choice. -/ noncomputable instance skolem₁_Structure : L.skolem₁.Structure M := ⟨λ n Ο† x, classical.epsilon (Ξ» a, Ο†.realize default (fin.snoc x a : _ β†’ M)), Ξ» _ r, empty.elim r⟩ namespace substructure lemma skolem₁_reduct_is_elementary (S : (L.sum L.skolem₁).substructure M) : (Lhom.sum_inl.substructure_reduct S).is_elementary := begin apply (Lhom.sum_inl.substructure_reduct S).is_elementary_of_exists, intros n Ο† x a h, let Ο†' : (L.sum L.skolem₁).functions n := (Lhom.sum_inr.on_function Ο†), exact ⟨⟨fun_map Ο†' (coe ∘ x), S.fun_mem (Lhom.sum_inr.on_function Ο†) (coe ∘ x) (Ξ» i, (x i).2)⟩, classical.epsilon_spec ⟨a, h⟩⟩, end /-- Any `L.sum L.skolem₁`-substructure is an elementary `L`-substructure. -/ noncomputable def elementary_skolem₁_reduct (S : (L.sum L.skolem₁).substructure M) : L.elementary_substructure M := ⟨Lhom.sum_inl.substructure_reduct S, Ξ» _, S.skolem₁_reduct_is_elementary⟩ lemma coe_sort_elementary_skolem₁_reduct (S : (L.sum L.skolem₁).substructure M) : (S.elementary_skolem₁_reduct : Type w) = S := rfl end substructure open substructure variables (L) (M) instance : small (βŠ₯ : (L.sum L.skolem₁).substructure M).elementary_skolem₁_reduct := begin rw [coe_sort_elementary_skolem₁_reduct], apply_instance, end theorem exists_small_elementary_substructure : βˆƒ (S : L.elementary_substructure M), small.{max u v} S := ⟨substructure.elementary_skolem₁_reduct βŠ₯, infer_instance⟩ variables {M} /-- The Downward LΓΆwenheim–Skolem theorem : If `s` is a set in an `L`-structure `M` and `ΞΊ` an infinite cardinal such that `max (# s, L.card) ≀ ΞΊ` and `ΞΊ ≀ # M`, then `M` has an elementary substructure containing `s` of cardinality `ΞΊ`. -/ theorem exists_elementary_substructure_card_eq (s : set M) (ΞΊ : cardinal.{w'}) (h1 : β„΅β‚€ ≀ ΞΊ) (h2 : cardinal.lift.{w'} (# s) ≀ cardinal.lift.{w} ΞΊ) (h3 : cardinal.lift.{w'} L.card ≀ cardinal.lift.{max u v} ΞΊ) (h4 : cardinal.lift.{w} ΞΊ ≀ cardinal.lift.{w'} (# M)) : βˆƒ (S : L.elementary_substructure M), s βŠ† S ∧ cardinal.lift.{w'} (# S) = cardinal.lift.{w} ΞΊ := begin obtain ⟨s', hs'⟩ := cardinal.le_mk_iff_exists_set.1 h4, rw ← aleph_0_le_lift at h1, rw ← hs' at *, refine ⟨elementary_skolem₁_reduct (closure (L.sum L.skolem₁) (s βˆͺ (equiv.ulift '' s'))), (s.subset_union_left _).trans subset_closure, _⟩, have h := mk_image_eq_lift _ s' equiv.ulift.injective, rw [lift_umax, lift_id'] at h, rw [coe_sort_elementary_skolem₁_reduct, ← h, lift_inj], refine le_antisymm (lift_le.1 (lift_card_closure_le.trans _)) (mk_le_mk_of_subset ((set.subset_union_right _ _).trans subset_closure)), rw [max_le_iff, aleph_0_le_lift, ← aleph_0_le_lift, h, add_eq_max, max_le_iff, lift_le], refine ⟨h1, (mk_union_le _ _).trans _, (lift_le.2 card_functions_sum_skolem₁_le).trans _⟩, { rw [← lift_le, lift_add, h, add_comm, add_eq_max h1], exact max_le le_rfl h2 }, { rw [lift_max, lift_aleph_0, max_le_iff, aleph_0_le_lift, and_comm, ← lift_le.{_ w'}, lift_lift, lift_lift, ← aleph_0_le_lift, h], refine ⟨_, h1⟩, simp only [← lift_lift, lift_umax, lift_umax'], rw [lift_lift, ← lift_lift.{w' w} L.card], refine trans ((lift_le.{_ w}).2 h3) _, rw [lift_lift, ← lift_lift.{w (max u v)}, ← hs', ← h, lift_lift, lift_lift, lift_lift] }, { refine trans _ (lift_le.2 (mk_le_mk_of_subset (set.subset_union_right _ _))), rw [aleph_0_le_lift, ← aleph_0_le_lift, h], exact h1 } end end language end first_order
0ae9af814855aa7e2f321da4aa62655c828ba6bf
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/bug5.lean
a38fdde4261adf26681b1995b22c5842ab10d8c0
[ "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
95
lean
import logic theorem symm2 {A : Type} {a b : A} (H : a = b) : b = a := eq.subst H (eq.refl a)
a4c695454137171865cc51c7c18b159d50032b23
56af0912bd25910f5caae91d6dd0603b0c032989
/src/complex/Level_00_basic.lean
b62fbd3f8317b69b4617c71b7d8c413e658f8f2d
[ "Apache-2.0" ]
permissive
isabella232/complex-number-game
ae36e0b1df9761d9df07049ca29c91ae44dbdc2d
3d767f14041f9002e435bed3a3527fdd297c166d
refs/heads/master
1,679,305,953,116
1,606,397,567,000
1,606,397,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,041
lean
/- Copyright (c) 2020 The Xena project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard. Thanks: Imperial College London, leanprover-community -/ -- We will assume that the real numbers are a field. import data.real.basic /-! # The complex numbers We define the complex numbers, and prove that they are a ring. We also "extract some basic API" (e.g. we prove that two complex numbers are equal iff they have the same real and imaginary parts) This file has no `sorry`s in. All of the other levels: `Level_01_of_real.lean` `Level_02_I.lean` `Level_03_conj.lean` `Level_04_norm_sq.lean` `Level_05_field.lean` `Level_06_alg_closed.lean` have sorrys, indicating puzzles to be solved. # Main Definitions `zero` : the complex number 0 `one` : the complex number 1 `add` -- addition of two complex numbers `neg` -- negation of a complex number `mul` -- multiplication of two complex numbers # Main Theorem `comm_ring` : The complex numbers are a commutative ring. -/ /-- A complex number is defined to be a structure consisting of two real numbers, the real part and the imaginary part of the complex numberd. -/ structure complex : Type := (re : ℝ) (im : ℝ) -- Let's use the usual notation for the complex numbers notation `β„‚` := complex -- You make the complex number with real part 3 and imaginary part 4 like this: example : β„‚ := { re := 3, im := 4 } -- Or like this: example : β„‚ := complex.mk 3 4 -- or like this: example : β„‚ := ⟨3, 4⟩ -- They all give the same complex number. example : complex.mk 3 4 = ⟨3, 4⟩ := begin refl end -- "true by definition" -- All of our definitions, like `zero` and `one`, will all -- live in the `complex` namespace. namespace complex -- If you have a complex number, then you can get its real and -- imaginary parts with the `re` and `im` functions. example : ℝ := re(mk 3 4) -- this term is (3 : ℝ) example : re(mk 3 4) = 3 := begin refl end -- Computer scientists prefer the style `z.re` to `re(z)` for some reason. example : (mk 3 4).re = 3 := begin refl end example (z : β„‚) : re(z) = z.re := begin refl end -- Before we start making the basic -- We now prove the basic theorems and make the basic definitions for -- complex numbers. For example, we will define addition and multiplication on -- the complex numbers, and prove that it is a commutative ring. -- TODO fix /-! # Defining the ring structure on β„‚ -/ -- Our main goal is to prove that the complexes are a ring. Let's -- define the structure first; the zero, one, addition and multiplication -- on the complexes. /-! ## zero (0) -/ /-- The complex number with real part 0 and imaginary part 0 -/ def zero : β„‚ := ⟨0, 0⟩ -- Now we set up notation so that `0 : β„‚` will mean `zero`. /-- notation `0` for `zero` -/ instance : has_zero β„‚ := ⟨zero⟩ -- Let's prove the two basic properties, both of which are true by definition, -- and then tag them with the appropriate attributes. @[simp] lemma zero_re : re(0 : β„‚) = 0 := begin refl end @[simp] lemma zero_im : im(0 : β„‚) = 0 := begin refl end /-! ## one (1) -/ -- Now let's do the same thing for 1. /-- The complex number with real part 1 and imaginary part 0 -/ def one : β„‚ := ⟨1, 0⟩ /-- Notation `1` for `one` -/ instance : has_one β„‚ := ⟨one⟩ -- name the basic properties and tag them with `simp` @[simp] lemma one_re : re(1 : β„‚) = 1 := begin refl end @[simp] lemma one_im : im(1 : β„‚) = 0 := begin refl end /-! ## add (+) -/ -- Now let's define addition /-- addition `z+w` of complex numbers -/ def add (z w : β„‚) : β„‚ := ⟨z.re + w.re, z.im + w.im⟩ /-- Notation `+` for addition -/ instance : has_add β„‚ := ⟨add⟩ -- basic properties @[simp] lemma add_re (z w : β„‚) : re(z + w) = re(z) + re(w) := begin refl end @[simp] lemma add_im (z w : β„‚) : im(z + w) = im(z) + im(w) := begin refl end /-! ## neg (-) -/ -- negation /-- The negation `-z` of a complex number `z` -/ def neg (z : β„‚) : β„‚ := ⟨-re(z), -im(z)⟩ /-- Notation `-` for negation -/ instance : has_neg β„‚ := ⟨neg⟩ -- how neg interacts with re and im @[simp] lemma neg_re (z : β„‚) : re(-z) = -re(z) := begin refl end @[simp] lemma neg_im (z : β„‚) : im(-z) = -im(z) := begin refl end /-! ## mul (*) -/ -- multiplication /-- Multiplication `z*w` of two complex numbers -/ def mul (z w : β„‚) : β„‚ := ⟨re(z) * re(w) - im(z) * im(w), re(z) * im(w) + im(z) * re(w)⟩ /-- Notation `*` for multiplication -/ instance : has_mul β„‚ := ⟨mul⟩ -- how `mul` reacts with `re` and `im` @[simp] lemma mul_re (z w : β„‚) : re(z * w) = re(z) * re(w) - im(z) * im(w) := begin refl end @[simp] lemma mul_im (z w : β„‚) : im(z * w) = re(z) * im(w) + im(z) * re(w) := rfl /-! ## Example of what `simp` can now do example (a b c : β„‚) : re(a*(b+c)) = re(a) * (re(b) + re(c)) - im(a) * (im(b) + im(c)) := begin simp, end -/ /-! # `ext` : A mathematical triviality -/ /- Two complex numbers with the same and imaginary parts are equal. This is an "extensionality lemma", i.e. a lemma of the form "if two things are made from the same pieces, they are equal". This is not hard to prove, but we want to give the result a name so we can tag it with the `ext` attribute, meaning that the `ext` tactic will know it. To add to the confusion, let's call the theorem `ext` :-) -/ /-- If two complex numbers z and w have equal real and imaginary parts, they are equal -/ @[ext] theorem ext {z w : β„‚} (hre : re(z) = re(w)) (him : im(z) = im(w)) : z = w := begin cases z with zr zi, cases w with ww wi, simp * at *, end /-! # Theorem: The complex numbers are a commutative ring Proof: we've defined all the structure, and every axiom can be checked by reducing it to checking real and imaginary parts with `ext`, expanding everything out with `simp`, and then using the fact that the real numbers are a commutative ring (which we already know) -/ /-- The complex numbers are a commutative ring -/ instance : comm_ring β„‚ := begin -- first the data refine_struct { zero := (0 : β„‚), add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; -- now the axioms -- of which there seem to be 11 -- Note the semicolons, which mean "apply next tactic to all goals". -- First introduce the variables intros; -- we now have to prove an equality between two complex numbers. -- It suffices to check on real and imaginary parts ext; -- the simplifier can simplify stuff like re(a+0) simp; -- all the goals now are identities between *real* numbers, -- and the reals are already known to be a ring ring, end /- That is the end of the proof that the complexes form a ring. We built a basic API which was honed towards the general idea that to prove certain statements about the complex numbers, for example distributivity, we could just check on real and imaginary parts. We trained the simplifier to expand out things like re(z*w) in terms of re(z), im(z), re(w), im(w). -/ /-! # Optional (for mathematicians) : more basic infrastructure, and term mode -/ /-! ## `ext` revisited Recall extensionality: theorem ext {z w : β„‚} (hre : re(z) = re(w)) (him : im(z) = im(w)) : z = w := ... Here is another tactic mode proof of extensionality. Note that we have moved the hypotheses to the other side of the colon; this does not change the theorem. This proof shows the power of the `rintros` tactic. -/ theorem ext' : βˆ€ z w : β„‚, z.re = w.re β†’ z.im = w.im β†’ z = w := begin rintros ⟨zr, zi⟩ ⟨_, _⟩ ⟨rfl⟩ ⟨rfl⟩, refl, end /-! Explanation: `rintros` does `cases` as many times as you like using this cool `⟨ ⟩` syntax for the case splits. Note that if you say that a proof of `a = b` is `rfl` then Lean will define a to be b, or b to be a, and not even introduce new notation for it. -/ -- Here is the same proof in term mode. theorem ext'' : βˆ€ {z w : β„‚}, z.re = w.re β†’ z.im = w.im β†’ z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl /-! ## `eta` -/ /- We prove the mathematically obvious statement that the complex number whose real part is re(z) and whose imaginary part is im(z) is of course equal to z. -/ /-- ⟨z.re, z.im⟩ is equal to z -/ @[simp] theorem eta : βˆ€ z : β„‚, complex.mk z.re z.im = z := begin intro z, cases z with x y, /- goal now looks complicated, and contains terms which look like {re := a, im := b}.re which obviously simplify to a. The `dsimp` tactic will do some tidying up for us, although it is not logically necessary. `dsimp` does definitional simplification. -/ dsimp, -- Now we see the goal can be solved by reflexivity refl, end /- The proof was "unfold everything, and it's true by definition". This proof does not teach a mathematician anything, so we may as well write it in term mode. Many tactics have term mode equivalent. The equation compiler does the `intro` and `cases` steps, and `dsimp` was unnecessary -- the two sides of the equation were definitionally equal. -/ theorem eta' : βˆ€ z : β„‚, complex.mk z.re z.im = z | ⟨x, y⟩ := rfl /-! ## ext_iff -/ /- Note that `ext` is an implication -- if re(z)=re(w) and im(z)=im(w) then z=w. The below variant `ext_iff` is the two-way implication: two complex numbers are equal if and only if they have the same real and imaginary part. Let's first see a tactic mode proof. See how the `ext` tactic is used? After it is applied, we have two goals, both of which are hypotheses. The semicolon means "apply the next tactic to all the goals produced by this one" -/ theorem ext_iff {z w : β„‚} : z = w ↔ z.re = w.re ∧ z.im = w.im := begin split, { intro H, simp [H]}, { rintro ⟨hre, him⟩, ext; assumption, } end -- Again this is easy to write in term mode, and no mathematician -- wants to read the proof anyway. theorem ext_iff' {z w : β„‚} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ end complex /-! # some last comments on the `simp` tactic Some equalities, even if obvious, had to be given names, because we want `simp` to be able to use them. In short, the `simp` tactic tries to solve goals of the form A = B, when `refl` doesn't work (i.e. the goals are not definitionally equal) but when any mathematician would be able to simplify A and B via "obvious" steps such as `0 + x = x` or `⟨z.re, z.im⟩ = z`. These things are sometimes not true by definition, but they should be tagged as being well-known ways to simplify an equality. When building our API for the complex numbers, if we prove a theorem of the form `A = B` where `B` is a bit simpler than `A`, we should probably tag it with the `@[simp]` attribute, so `simp` can use it. Note: `simp` does *not* prove "all simple things". It proves *equalities*. It proves `A = B` when, and only when, it can do it by applying its "simplification rules", where a simplification rule is simply a proof of a theorem of the form `A = B` and `B` is simpler than `A`. -/
8e576d9a1bb25a950ca2b69ec44f4f1b0e168f14
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/factorial/double_factorial.lean
5964c0ef8dd6a8dda4b84d199692f00fd6dbde1a
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,164
lean
/- Copyright (c) 2023 Jake Levinson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jake Levinson -/ import data.nat.factorial.basic import algebra.big_operators.order import tactic.ring /-! # Double factorials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the double factorial, `nβ€Ό := n * (n - 2) * (n - 4) * ...`. ## Main declarations * `nat.double_factorial`: The double factorial. -/ open_locale nat namespace nat /-- `nat.double_factorial n` is the double factorial of `n`. -/ @[simp] def double_factorial : β„• β†’ β„• | 0 := 1 | 1 := 1 | (k + 2) := (k + 2) * double_factorial k -- This notation is `\!!` not two !'s localized "notation (name := nat.double_factorial) n `β€Ό`:10000 := nat.double_factorial n" in nat lemma double_factorial_add_two (n : β„•) : (n + 2)β€Ό = (n + 2) * nβ€Ό := rfl lemma double_factorial_add_one (n : β„•) : (n + 1)β€Ό = (n + 1) * (n - 1)β€Ό := by { cases n; refl } lemma factorial_eq_mul_double_factorial : βˆ€ (n : β„•), (n + 1)! = (n + 1)β€Ό * nβ€Ό | 0 := rfl | (k + 1) := begin rw [double_factorial_add_two, factorial, factorial_eq_mul_double_factorial, mul_comm _ (kβ€Ό), mul_assoc] end lemma double_factorial_two_mul : βˆ€ (n : β„•), (2 * n)β€Ό = 2^n * n! | 0 := rfl | (n + 1) := begin rw [mul_add, mul_one, double_factorial_add_two, factorial, pow_succ, double_factorial_two_mul, succ_eq_add_one], ring, end open_locale big_operators lemma double_factorial_eq_prod_even : βˆ€ (n : β„•), (2 * n)β€Ό = ∏ i in finset.range n, (2 * (i + 1)) | 0 := rfl | (n + 1) := begin rw [finset.prod_range_succ, ← double_factorial_eq_prod_even, mul_comm (2 * n)β€Ό, (by ring : 2 * (n + 1) = 2 * n + 2)], refl, end lemma double_factorial_eq_prod_odd : βˆ€ (n : β„•), (2 * n + 1)β€Ό = ∏ i in finset.range n, (2 * (i + 1) + 1) | 0 := rfl | (n + 1) := begin rw [finset.prod_range_succ, ← double_factorial_eq_prod_odd, mul_comm (2 * n + 1)β€Ό, (by ring : 2 * (n + 1) + 1 = (2 * n + 1) + 2)], refl, end end nat
d071452405abda3de683ddc80d038c58e9ba76ba
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/lie/cartan_subalgebra.lean
efa4ea5fb2af7cb5835f70d555f47408956743b1
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,240
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.nilpotent /-! # Cartan subalgebras Cartan subalgebras are one of the most important concepts in Lie theory. We define them here. The standard example is the set of diagonal matrices in the Lie algebra of matrices. ## Main definitions * `lie_subalgebra.normalizer` * `lie_subalgebra.le_normalizer_of_ideal` * `lie_subalgebra.is_cartan_subalgebra` ## Tags lie subalgebra, normalizer, idealizer, cartan subalgebra -/ universes u v w w₁ wβ‚‚ variables {R : Type u} {L : Type v} variables [comm_ring R] [lie_ring L] [lie_algebra R L] (H : lie_subalgebra R L) namespace lie_subalgebra /-- The normalizer of a Lie subalgebra `H` is the set of elements of the Lie algebra whose bracket with any element of `H` lies in `H`. It is the Lie algebra equivalent of the group-theoretic normalizer (see `subgroup.normalizer`) and is an idealizer in the sense of abstract algebra. -/ def normalizer : lie_subalgebra R L := { carrier := { x : L | βˆ€ (y : L), (y ∈ H) β†’ ⁅x, y⁆ ∈ H }, zero_mem' := Ξ» y hy, by { rw zero_lie y, exact H.zero_mem, }, add_mem' := Ξ» z₁ zβ‚‚ h₁ hβ‚‚ y hy, by { rw add_lie, exact H.add_mem (h₁ y hy) (hβ‚‚ y hy), }, smul_mem' := Ξ» t y hy z hz, by { rw smul_lie, exact H.smul_mem t (hy z hz), }, lie_mem' := Ξ» z₁ zβ‚‚ h₁ hβ‚‚ y hy, by { rw lie_lie, exact H.sub_mem (h₁ _ (hβ‚‚ y hy)) (hβ‚‚ _ (h₁ y hy)), }, } lemma mem_normalizer_iff (x : L) : x ∈ H.normalizer ↔ βˆ€ (y : L), (y ∈ H) β†’ ⁅x, y⁆ ∈ H := iff.rfl lemma mem_normalizer_iff' (x : L) : x ∈ H.normalizer ↔ βˆ€ (y : L), (y ∈ H) β†’ ⁅y, x⁆ ∈ H := forall_congr (Ξ» y, forall_congr (Ξ» hy, by rw [← lie_skew, H.neg_mem_iff])) lemma le_normalizer : H ≀ H.normalizer := Ξ» x hx, show βˆ€ (y : L), y ∈ H β†’ ⁅x,y⁆ ∈ H, from Ξ» y, H.lie_mem hx /-- A Lie subalgebra is an ideal of its normalizer. -/ lemma ideal_in_normalizer : βˆ€ (x y : L), x ∈ H.normalizer β†’ y ∈ H β†’ ⁅x,y⁆ ∈ H := Ξ» x y h, h y /-- The normalizer of a Lie subalgebra `H` is the maximal Lie subalgebra in which `H` is a Lie ideal. -/ lemma le_normalizer_of_ideal {N : lie_subalgebra R L} (h : βˆ€ (x y : L), x ∈ N β†’ y ∈ H β†’ ⁅x,y⁆ ∈ H) : N ≀ H.normalizer := Ξ» x hx y, h x y hx lemma normalizer_eq_self_iff : H.normalizer = H ↔ (lie_module.max_triv_submodule R H $ L β§Έ H.to_lie_submodule) = βŠ₯ := begin rw lie_submodule.eq_bot_iff, refine ⟨λ h, _, Ξ» h, le_antisymm (Ξ» x hx, _) H.le_normalizer⟩, { rintros ⟨x⟩ hx, suffices : x ∈ H, by simpa, rw [← h, H.mem_normalizer_iff'], intros y hy, replace hx : ⁅_, lie_submodule.quotient.mk' _ x⁆ = 0 := hx ⟨y, hy⟩, rwa [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero] at hx, }, { let y := lie_submodule.quotient.mk' H.to_lie_submodule x, have hy : y ∈ lie_module.max_triv_submodule R H (L β§Έ H.to_lie_submodule), { rintros ⟨z, hz⟩, rw [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero, coe_bracket_of_module, submodule.coe_mk, mem_to_lie_submodule], exact (H.mem_normalizer_iff' x).mp hx z hz, }, simpa using h y hy, }, end /-- A Cartan subalgebra is a nilpotent, self-normalizing subalgebra. -/ class is_cartan_subalgebra : Prop := (nilpotent : lie_algebra.is_nilpotent R H) (self_normalizing : H.normalizer = H) end lie_subalgebra @[simp] lemma lie_ideal.normalizer_eq_top {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) : (I : lie_subalgebra R L).normalizer = ⊀ := begin ext x, simpa only [lie_subalgebra.mem_normalizer_iff, lie_subalgebra.mem_top, iff_true] using Ξ» y hy, I.lie_mem hy end open lie_ideal /-- A nilpotent Lie algebra is its own Cartan subalgebra. -/ instance lie_algebra.top_is_cartan_subalgebra_of_nilpotent [lie_algebra.is_nilpotent R L] : lie_subalgebra.is_cartan_subalgebra (⊀ : lie_subalgebra R L) := { nilpotent := infer_instance, self_normalizing := by { rw [← top_coe_lie_subalgebra, normalizer_eq_top, top_coe_lie_subalgebra], }, }
275f997a721a4231f044d3c514f8eb6410f9937b
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/SyntheticMVars.lean
5f3fbb15907394eb45823cdf83b0305f30a9f99d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
25,512
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Meta.Tactic.Util import Lean.Util.ForEachExpr import Lean.Util.OccursCheck import Lean.Elab.Tactic.Basic namespace Lean.Elab.Term open Tactic (TacticM evalTactic getUnsolvedGoals withTacticInfoContext) open Meta /-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/ private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr := -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry` withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do elabTerm stx expectedType? false /-- Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`. It returns `true` if it succeeded, and `false` otherwise. It is used to implement `synthesizeSyntheticMVars`. -/ private def resumePostponed (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := withRef stx <| mvarId.withContext do let s ← saveState try withSavedContext savedContext do let mvarDecl ← getMVarDecl mvarId let expectedType ← instantiateMVars mvarDecl.type withInfoHole mvarId do let result ← resumeElabTerm stx expectedType (!postponeOnError) /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx. That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/ let result ← withRef stx <| ensureHasType expectedType result /- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/ if (← occursCheck mvarId result) then mvarId.assign result return true else return false catch | ex@(.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) return false else throw ex | ex@(.error ..) => if postponeOnError then s.restore (restoreInfo := true) return false else logException ex return true /-- Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances are used. It also logs any error message produced. -/ private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool := instMVar.withContext do try synthesizeInstMVarCore instMVar catch | ex@(.error ..) => logException ex; return true | _ => unreachable! /-- Similar to `synthesizePendingInstMVar`, but generates type mismatch error message. Remark: `eNew` is of the form `@coe ... mvar`, where `mvar` is the metavariable for the `CoeT ...` instance. If `mvar` can be synthesized, then assign `auxMVarId := (expandCoe eNew)`. -/ private def synthesizePendingCoeInstMVar (auxMVarId : MVarId) (errorMsgHeader? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool := do let instMVarId := eNew.appArg!.mvarId! instMVarId.withContext do let eType ← instantiateMVars eType if (← isSyntheticMVar eType) then return false if (← withDefault <| isDefEq expectedType eType) then /- This case may seem counterintuitive since we created the coercion because the `isDefEq expectedType eType` test failed before. However, it may succeed here because we have more information, for example, metavariables occurring at `expectedType` and `eType` may have been assigned. -/ if (← occursCheck auxMVarId e) then auxMVarId.assign e return true else return false try if (← synthesizeCoeInstMVarCore instMVarId) then let eNew ← expandCoe eNew if (← occursCheck auxMVarId eNew) then auxMVarId.assign eNew return true return false catch | .error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => unreachable! /-- Try to synthesize `mvarId` by starting using a default instance with the give privority. This method succeeds only if the metavariable of fully synthesized. Remark: In the past, we would return a list of pending TC problems, but this was problematic since a default instance may create subproblems that cannot be solved. Remark: The new approach also has limitations because other pending metavariables are not taken into account while backtraking. That is, we fail to synthesize `mvarId` because we reach subproblems that are stuck, but we could "unstuck" them if we tried to solve other pending metavariables. Considering all pending metavariables into a single backtracking search seems to be too expensive, and potentially generate incomprehensible error messages. This is particularly true if we consider pending metavariables for "postponed" elaboration steps. Here is an example that demonstrate this issue. The example considers we are using the old `binrel%` elaborator which was disconnected from `binop%`. ``` example (a : Int) (b c : Nat) : a = ↑b - ↑c := sorry ``` We have two pending coercions for the `↑` and `HSub ?m.220 ?m.221 ?m.222`. When we did not use a backtracking search here, then the homogenous default instance for `HSub`. ``` instance [Sub Ξ±] : HSub Ξ± Ξ± Ξ± where ``` would be applied first, and would propagate the expected type `Int` to the pending coercions which would now be unblocked. Instead of performing a backtracking search that considers all pending metavariables, we improved the `binrel%` elaborator. -/ private partial def synthesizeUsingDefaultPrio (mvarId : MVarId) (prio : Nat) : TermElabM Bool := mvarId.withContext do let mvarType ← mvarId.getType match (← isClass? mvarType) with | none => return false | some className => match (← getDefaultInstances className) with | [] => return false | defaultInstances => for (defaultInstance, instPrio) in defaultInstances do if instPrio == prio then if (← synthesizeUsingDefaultInstance mvarId defaultInstance) then return true return false where synthesizeUsingDefault (mvarId : MVarId) : TermElabM Bool := do for prio in (← getDefaultInstancesPriorities) do if (← synthesizeUsingDefaultPrio mvarId prio) then return true return false synthesizePendingInstMVar' (mvarId : MVarId) : TermElabM Bool := commitWhen <| mvarId.withContext do try synthesizeInstMVarCore mvarId catch _ => return false synthesizeUsingInstancesStep (mvarIds : List MVarId) : TermElabM (List MVarId) := mvarIds.filterM fun mvarId => do if (← synthesizePendingInstMVar' mvarId) then return false else return true synthesizeUsingInstances (mvarIds : List MVarId) : TermElabM (List MVarId) := do let mvarIds' ← synthesizeUsingInstancesStep mvarIds if mvarIds'.length < mvarIds.length then synthesizeUsingInstances mvarIds' else return mvarIds' synthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM Bool := commitWhen do let candidate ← mkConstWithFreshMVarLevels defaultInstance let (mvars, bis, _) ← forallMetaTelescopeReducing (← inferType candidate) let candidate := mkAppN candidate mvars trace[Elab.defaultInstance] "{toString (mkMVar mvarId)}, {mkMVar mvarId} : {← inferType (mkMVar mvarId)} =?= {candidate} : {← inferType candidate}" /- The `coeAtOutParam` feature may mark output parameters of local instances as `syntheticOpaque`. This kind of parameter is not assignable by default. We use `withAssignableSyntheticOpaque` to workaround this behavior when processing default instances. TODO: try to avoid `withAssignableSyntheticOpaque`. -/ if (← withAssignableSyntheticOpaque <| isDefEqGuarded (mkMVar mvarId) candidate) then -- Succeeded. Collect new TC problems trace[Elab.defaultInstance] "isDefEq worked {mkMVar mvarId} : {← inferType (mkMVar mvarId)} =?= {candidate} : {← inferType candidate}" let mut pending := [] for i in [:bis.size] do if bis[i]! == BinderInfo.instImplicit then pending := mvars[i]!.mvarId! :: pending synthesizePending pending else return false synthesizeSomeUsingDefault? (mvarIds : List MVarId) : TermElabM (Option (List MVarId)) := do match mvarIds with | [] => return none | mvarId :: mvarIds => if (← synthesizeUsingDefault mvarId) then return mvarIds else if let some mvarIds' ← synthesizeSomeUsingDefault? mvarIds then return mvarId :: mvarIds' else return none synthesizePending (mvarIds : List MVarId) : TermElabM Bool := do let mvarIds ← synthesizeUsingInstances mvarIds if mvarIds.isEmpty then return true let some mvarIds ← synthesizeSomeUsingDefault? mvarIds | return false synthesizePending mvarIds /-- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/ private def synthesizeSomeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do let rec visit (pendingMVars : List MVarId) (pendingMVarsNew : List MVarId) : TermElabM Bool := do match pendingMVars with | [] => return false | mvarId :: pendingMVars => let some mvarDecl ← getSyntheticMVarDecl? mvarId | visit pendingMVars (mvarId :: pendingMVarsNew) match mvarDecl.kind with | .typeClass => if (← withRef mvarDecl.stx <| synthesizeUsingDefaultPrio mvarId prio) then modify fun s => { s with pendingMVars := pendingMVars.reverse ++ pendingMVarsNew } return true else visit pendingMVars (mvarId :: pendingMVarsNew) | _ => visit pendingMVars (mvarId :: pendingMVarsNew) /- Recall that s.pendingMVars is essentially a stack. The first metavariable was the last one created. We want to apply the default instance in reverse creation order. Otherwise, `toString 0` will produce a `OfNat String _` cannot be synthesized error. -/ visit (← get).pendingMVars.reverse [] /-- Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault` Return true if something was synthesized. -/ private def synthesizeUsingDefault : TermElabM Bool := do let prioSet ← getDefaultInstancesPriorities /- Recall that `prioSet` is stored in descending order -/ for prio in prioSet do if (← synthesizeSomeUsingDefaultPrio prio) then return true return false /-- We use this method to report typeclass (and coercion) resolution problems that are "stuck". That is, there is nothing else to do, and we don't have enough information to synthesize them using TC resolution. -/ def reportStuckSyntheticMVar (mvarId : MVarId) (ignoreStuckTC := false) : TermElabM Unit := do let some mvarSyntheticDecl ← getSyntheticMVarDecl? mvarId | return () withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | .typeClass => unless ignoreStuckTC do mvarId.withContext do let mvarDecl ← getMVarDecl mvarId unless (← MonadLog.hasErrors) do throwError "typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}" | .coe header eNew expectedType eType e f? => let mvarId := eNew.appArg!.mvarId! mvarId.withContext do let mvarDecl ← getMVarDecl mvarId throwTypeMismatchError header expectedType eType e f? (some ("failed to create type class instance for " ++ indentExpr mvarDecl.type)) | _ => unreachable! -- TODO handle other cases. /-- Report an error for each synthetic metavariable that could not be resolved. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. -/ private def reportStuckSyntheticMVars (ignoreStuckTC := false) : TermElabM Unit := do let pendingMVars ← modifyGet fun s => (s.pendingMVars, { s with pendingMVars := [] }) for mvarId in pendingMVars do reportStuckSyntheticMVar mvarId ignoreStuckTC private def getSomeSynthethicMVarsRef : TermElabM Syntax := do for mvarId in (← get).pendingMVars do if let some decl ← getSyntheticMVarDecl? mvarId then if decl.stx.getPos?.isSome then return decl.stx return .missing /-- Generate an nicer error message for stuck universe constraints. -/ private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : HashSet (Level Γ— Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i]!.ref (← mkLevelStuckErrorMessage uniqueEntries[i]!) throwErrorAt uniqueEntries[0]!.ref (← mkLevelStuckErrorMessage uniqueEntries[0]!) /-- Try to solve postponed universe constraints, and throws an exception if there are stuck constraints. Remark: in previous versions, each `isDefEq u v` invocation would fail if there were pending universe level constraints. With this old approach, we were not able to process ``` Functor.map Prod.fst (x s) ``` because after elaborating `Prod.fst` and trying to ensure its type match the expected one, we would be stuck at the universe constraint: ``` u =?= max u ?v ``` Another benefit of using `withoutPostponingUniverseConstraints` is better error messages. Instead of getting a mysterious type mismatch constraint, we get a list of universe contraints the system is stuck at. -/ private def processPostponedUniverseContraints : TermElabM Unit := do unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr /-- Remove `mvarId` from the `syntheticMVars` table. We use this method after the metavariable has been synthesized. -/ private def markAsResolved (mvarId : MVarId) : TermElabM Unit := modify fun s => { s with syntheticMVars := s.syntheticMVars.erase mvarId } mutual /-- Try to synthesize a term `val` using the tactic code `tacticCode`, and then assign `mvarId := val`. -/ partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := withoutAutoBoundImplicit do /- Recall, `tacticCode` is the whole `by ...` expression. -/ let code := tacticCode[1] instantiateMVarDeclMVars mvarId /- TODO: consider using `runPendingTacticsAt` at `mvarId` local context and target type. Issue #1380 demonstrates that the goal may still contain pending metavariables. It happens in the following scenario we have a term `foo A (by tac)` where `A` has been postponed and contains nested `by ...` terms. The pending metavar list contains two metavariables: ?m1 (for `A`) and `?m2` (for `by tac`). When `A` is resumed, it creates a new metavariable `?m3` for the nested `by ...` term in `A`. `?m3` is after `?m2` in the to-do list. Then, we execute `by tac` for synthesizing `?m2`, but its type depends on `?m3`. We have considered putting `?m3` at `?m2` place in the to-do list, but this is not super robust. The ideal solution is to make sure a tactic "resolves" all pending metavariables nested in their local contex and target type before starting tactic execution. The procedure would be a generalization of `runPendingTacticsAt`. We can try to combine it with `instantiateMVarDeclMVars` to make sure we do not perform two traversals. Regarding issue #1380, we addressed the issue by avoiding the elaboration postponement step. However, the same issue can happen in more complicated scenarios. -/ try let remainingGoals ← withInfoHole mvarId <| Tactic.run mvarId do withTacticInfoContext tacticCode (evalTactic code) synthesizeSyntheticMVars (mayPostpone := false) unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals catch ex => if (← read).errToSorry then for mvarId in (← getMVars (mkMVar mvarId)) do mvarId.admit logException ex else throw ex /-- Try to synthesize the given pending synthetic metavariable. -/ private partial def synthesizeSyntheticMVar (mvarId : MVarId) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let some mvarSyntheticDecl ← getSyntheticMVarDecl? mvarId | return true -- The metavariable has already been synthesized withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | .typeClass => synthesizePendingInstMVar mvarId | .coe header? eNew expectedType eType e f? => synthesizePendingCoeInstMVar mvarId header? eNew expectedType eType e f? -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | .postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarId postponeOnError | .tactic tacticCode savedContext => withSavedContext savedContext do if runTactics then runTactic mvarId tacticCode return true else return false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let ctx ← read traceAtCmdPos `Elab.resuming fun _ => m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}" let pendingMVars := (← get).pendingMVars let numSyntheticMVars := pendingMVars.length -- We reset `pendingMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`. modify fun s => { s with pendingMVars := [] } -- Recall that `pendingMVars` is a list where head is the most recent pending synthetic metavariable. -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created. -- It would not be incorrect to use `filterM`. let remainingPendingMVars ← pendingMVars.filterRevM fun mvarId => do -- We use `traceM` because we want to make sure the metavar local context is used to trace the message traceM `Elab.postpone (mvarId.withContext do addMessageContext m!"resuming {mkMVar mvarId}") let succeeded ← synthesizeSyntheticMVar mvarId postponeOnError runTactics if succeeded then markAsResolved mvarId trace[Elab.postpone] if succeeded then format "succeeded" else format "not ready yet" pure !succeeded -- Merge new synthetic metavariables with `remainingPendingMVars`, i.e., metavariables that still couldn't be synthesized modify fun s => { s with pendingMVars := s.pendingMVars ++ remainingPendingMVars } return numSyntheticMVars != remainingPendingMVars.length /-- Try to process pending synthetic metavariables. If `mayPostpone == false`, then `pendingMVars` is `[]` after executing this method. It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made. If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available) metavariables that are still unresolved, and then tries to resolve metavariables with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to a "best option". If, after that, we still haven't made progress, we report "stuck" errors. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. Then, pending TC problems become implicit parameters for the simp theorem. -/ partial def synthesizeSyntheticMVars (mayPostpone := true) (ignoreStuckTC := false) : TermElabM Unit := do let rec loop (_ : Unit) : TermElabM Unit := do withRef (← getSomeSynthethicMVarsRef) <| withIncRecDepth do unless (← get).pendingMVars.isEmpty do if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if !mayPostpone then /- Resume pending metavariables with "elaboration postponement" disabled. We postpone elaboration errors in this step by setting `postponeOnError := true`. Example: ``` #check let x := ⟨1, 2⟩; Prod.fst x ``` The term `⟨1, 2⟩` can't be elaborated because the expected type is not know. The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known. When we execute the following step with "elaboration postponement" disabled, the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns that its type must be of the form `Prod ?Ξ± ?Ξ²`. Recall that we postponed `x` at `Prod.fst x` because its type it is not known. We the type of `x` may learn later its type and it may contain implicit and/or auto arguments. By disabling postponement, we are essentially giving up the opportunity of learning `x`s type and assume it does not have implict and/or auto arguments. -/ if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := true) (runTactics := false) then loop () else if ← synthesizeUsingDefault then loop () else if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then loop () else reportStuckSyntheticMVars ignoreStuckTC loop () unless mayPostpone do processPostponedUniverseContraints end def synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := false) : TermElabM Unit := synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := ignoreStuckTC) /-- Keep invoking `synthesizeUsingDefault` until it returns false. -/ private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do if (← synthesizeUsingDefault) then synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop private partial def withSynthesizeImp {Ξ±} (k : TermElabM Ξ±) (mayPostpone : Bool) (synthesizeDefault : Bool) : TermElabM Ξ± := do let pendingMVarsSaved := (← get).pendingMVars modify fun s => { s with pendingMVars := [] } try let a ← k synthesizeSyntheticMVars mayPostpone if mayPostpone && synthesizeDefault then synthesizeUsingDefaultLoop return a finally modify fun s => { s with pendingMVars := s.pendingMVars ++ pendingMVarsSaved } /-- Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved. If `mayPostpone == false`, then all of them must be synthesized. Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/ @[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m Ξ±) (mayPostpone := false) : m Ξ± := monadMap (m := TermElabM) (withSynthesizeImp Β· mayPostpone (synthesizeDefault := true)) k /-- Similar to `withSynthesize`, but sets `mayPostpone` to `true`, and do not use `synthesizeUsingDefault` -/ @[inline] def withSynthesizeLight [MonadFunctorT TermElabM m] [Monad m] (k : m Ξ±) : m Ξ± := monadMap (m := TermElabM) (withSynthesizeImp Β· (mayPostpone := true) (synthesizeDefault := false)) k /-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/ def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := withRef stx do instantiateMVars (← withSynthesize <| elabTerm stx expectedType?) /-- Collect unassigned metavariables at `e` that have associated tactic blocks, and then execute them using `runTactic`. We use this method at the `match .. with` elaborator when it cannot be postponed anymore, but it is still waiting the result of a tactic block. -/ def runPendingTacticsAt (e : Expr) : TermElabM Unit := do for mvarId in (← getMVars e) do let mvarId ← getDelayedMVarRoot mvarId if let some { kind := .tactic tacticCode savedContext, .. } ← getSyntheticMVarDecl? mvarId then withSavedContext savedContext do runTactic mvarId tacticCode markAsResolved mvarId builtin_initialize registerTraceClass `Elab.resume end Lean.Elab.Term
cf654d1d4090eb29c7b0600f6aeae07c7e77bb05
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/typeclasses/has_mul/has_mul.lean
af3fed42ed4045dbff8a70bd427e2896756dce17
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
615
lean
namespace hidden universe u structure has_mul_ident (Ξ± : Type u): Type (u+1) := (mul : Ξ± β†’ Ξ± β†’ Ξ±) def has_mul_ident_type: has_mul_ident bool := has_mul_ident.mk band #check has_mul_ident_type /- Syntactic alternative: class has_mul (Ξ± : Type u) := (mul : Ξ± β†’ Ξ± β†’ Ξ±) -/ @[class] structure has_mul (Ξ± : Type u): Type (u+1) := (mul : Ξ± β†’ Ξ± β†’ Ξ±) instance has_mul_bool : has_mul bool := has_mul.mk band instance has_mul_nat : has_mul nat := has_mul.mk nat.mul def fancy_mul {Ξ± : Type} [tc: has_mul Ξ±] : Ξ± β†’ Ξ± β†’ Ξ±:= tc.mul #eval fancy_mul tt ff #eval fancy_mul 3 4 end hidden
b10dc8a9c1a8043723f1486709bdd292bc875c13
3af272061d36e7f3f0521cceaa3a847ed4e03af9
/src/action.lean
4495bfe1541177a740d3c88a2ee5b13a4e5ae4e2
[]
no_license
semorrison/kbb
fdab0929d21dca880d835081814225a95f946187
229bd06e840bc7a7438b8fee6802a4f8024419e3
refs/heads/master
1,585,351,834,355
1,539,848,241,000
1,539,848,241,000
147,323,315
2
1
null
null
null
null
UTF-8
Lean
false
false
839
lean
import group_theory.group_action variables {X : Type*} {G : Type*} [group G] (ρ : G β†’ X β†’ X) [is_group_action ρ] lemma is_group_action.inverse_left (g : G) : (ρ g⁻¹) ∘ ρ g = id := begin ext x, change ρ g⁻¹ (ρ g x) = x, rw ← is_monoid_action.mul ρ g⁻¹ g x, simp [is_monoid_action.one ρ] end lemma is_group_action.inverse_right (g : G) : (ρ g) ∘ ρ g⁻¹ = id := by simpa using is_group_action.inverse_left ρ g⁻¹ def action_rel : setoid X := ⟨λ x y, βˆƒ g, ρ g x = y, ⟨λ x, ⟨(1 : G), is_monoid_action.one ρ x⟩, begin { split, { rintros x y ⟨g, h⟩, existsi g⁻¹, rw ←h, exact congr_fun (is_group_action.inverse_left ρ g) x }, { rintros x y z ⟨g, h⟩ ⟨g', h'⟩, existsi g'*g, rw [is_monoid_action.mul ρ, h, h'] } } end⟩⟩
4458b8d38b535489d240ea2e950fff66ee420505
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/852.hlean
7fc17ae67ef1197199b5368845b0917a15da807e
[ "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
122
hlean
import algebra.category.functor.equivalence -- print prefix category.equivalence -- check @category.equivalence.to._Fun