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
dc1fd0cc0cf0b255bbc48611905b801607268333
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/group_power/order.lean
aa2ab3534f216861cc1ea9cc528524c027f28529
[ "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
15,237
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.order.ring import algebra.group_power.basic /-! # Lemmas about the interaction of power operations with order Note that some lemmas are in `algebra/group_power/lemmas.lean` as they import files which depend on this file. -/ variables {A G M R : Type*} section preorder variables [monoid M] [preorder M] [covariant_class M M (*) (≤)] @[to_additive nsmul_le_nsmul_of_le_right, mono] lemma pow_le_pow_of_le_left' [covariant_class M M (function.swap (*)) (≤)] {a b : M} (hab : a ≤ b) : ∀ i : ℕ, a ^ i ≤ b ^ i | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ], exact mul_le_mul' hab (pow_le_pow_of_le_left' k) } attribute [mono] nsmul_le_nsmul_of_le_right @[to_additive nsmul_nonneg] theorem one_le_pow_of_one_le' {a : M} (H : 1 ≤ a) : ∀ n : ℕ, 1 ≤ a ^ n | 0 := by simp | (k + 1) := by { rw pow_succ, exact one_le_mul H (one_le_pow_of_one_le' k) } @[to_additive nsmul_nonpos] lemma pow_le_one' {a : M} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1 := @one_le_pow_of_one_le' Mᵒᵈ _ _ _ _ H n @[to_additive nsmul_le_nsmul] theorem pow_le_pow' {a : M} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n ≤ a ^ n * a ^ k : le_mul_of_one_le_right' (one_le_pow_of_one_le' ha _) ... = a ^ m : by rw [← hk, pow_add] @[to_additive nsmul_le_nsmul_of_nonpos] theorem pow_le_pow_of_le_one' {a : M} {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n := @pow_le_pow' Mᵒᵈ _ _ _ _ _ _ ha h @[to_additive nsmul_pos] theorem one_lt_pow' {a : M} (ha : 1 < a) {k : ℕ} (hk : k ≠ 0) : 1 < a ^ k := begin rcases nat.exists_eq_succ_of_ne_zero hk with ⟨l, rfl⟩, clear hk, induction l with l IH, { simpa using ha }, { rw pow_succ, exact one_lt_mul' ha IH } end @[to_additive nsmul_neg] lemma pow_lt_one' {a : M} (ha : a < 1) {k : ℕ} (hk : k ≠ 0) : a ^ k < 1 := @one_lt_pow' Mᵒᵈ _ _ _ _ ha k hk @[to_additive nsmul_lt_nsmul] theorem pow_lt_pow' [covariant_class M M (*) (<)] {a : M} {n m : ℕ} (ha : 1 < a) (h : n < m) : a ^ n < a ^ m := begin rcases nat.le.dest h with ⟨k, rfl⟩, clear h, rw [pow_add, pow_succ', mul_assoc, ← pow_succ], exact lt_mul_of_one_lt_right' _ (one_lt_pow' ha k.succ_ne_zero) end @[to_additive nsmul_strict_mono_right] lemma pow_strict_mono_left [covariant_class M M (*) (<)] {a : M} (ha : 1 < a) : strict_mono ((^) a : ℕ → M) := λ m n, pow_lt_pow' ha end preorder section linear_order variables [monoid M] [linear_order M] [covariant_class M M (*) (≤)] @[to_additive nsmul_nonneg_iff] lemma one_le_pow_iff {x : M} {n : ℕ} (hn : n ≠ 0) : 1 ≤ x ^ n ↔ 1 ≤ x := ⟨le_imp_le_of_lt_imp_lt $ λ h, pow_lt_one' h hn, λ h, one_le_pow_of_one_le' h n⟩ @[to_additive] lemma pow_le_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n ≤ 1 ↔ x ≤ 1 := @one_le_pow_iff Mᵒᵈ _ _ _ _ _ hn @[to_additive nsmul_pos_iff] lemma one_lt_pow_iff {x : M} {n : ℕ} (hn : n ≠ 0) : 1 < x ^ n ↔ 1 < x := lt_iff_lt_of_le_iff_le (pow_le_one_iff hn) @[to_additive] lemma pow_lt_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n < 1 ↔ x < 1 := lt_iff_lt_of_le_iff_le (one_le_pow_iff hn) @[to_additive] lemma pow_eq_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := by simp only [le_antisymm_iff, pow_le_one_iff hn, one_le_pow_iff hn] variables [covariant_class M M (*) (<)] {a : M} {m n : ℕ} @[to_additive nsmul_le_nsmul_iff] lemma pow_le_pow_iff' (ha : 1 < a) : a ^ m ≤ a ^ n ↔ m ≤ n := (pow_strict_mono_left ha).le_iff_le @[to_additive nsmul_lt_nsmul_iff] lemma pow_lt_pow_iff' (ha : 1 < a) : a ^ m < a ^ n ↔ m < n := (pow_strict_mono_left ha).lt_iff_lt end linear_order section div_inv_monoid variables [div_inv_monoid G] [preorder G] [covariant_class G G (*) (≤)] @[to_additive zsmul_nonneg] theorem one_le_zpow {x : G} (H : 1 ≤ x) {n : ℤ} (hn : 0 ≤ n) : 1 ≤ x ^ n := begin lift n to ℕ using hn, rw zpow_coe_nat, apply one_le_pow_of_one_le' H, end end div_inv_monoid namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) (n : ℕ) : 0 < a ^ n := pos_iff_ne_zero.2 $ pow_ne_zero _ H.ne' end canonically_ordered_comm_semiring section ordered_semiring variables [ordered_semiring R] {a x y : R} {n m : ℕ} theorem pow_add_pow_le (hx : 0 ≤ x) (hy : 0 ≤ y) (hn : n ≠ 0) : x ^ n + y ^ n ≤ (x + y) ^ n := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨k, rfl⟩, induction k with k ih, { simp only [pow_one] }, let n := k.succ, have h1 := add_nonneg (mul_nonneg hx (pow_nonneg hy n)) (mul_nonneg hy (pow_nonneg hx n)), have h2 := add_nonneg hx hy, calc x^n.succ + y^n.succ ≤ x*x^n + y*y^n + (x*y^n + y*x^n) : by { rw [pow_succ _ n, pow_succ _ n], exact le_add_of_nonneg_right h1 } ... = (x+y) * (x^n + y^n) : by rw [add_mul, mul_add, mul_add, add_comm (y*x^n), ← add_assoc, ← add_assoc, add_assoc (x*x^n) (x*y^n), add_comm (x*y^n) (y*y^n), ← add_assoc] ... ≤ (x+y)^n.succ : by { rw [pow_succ _ n], exact mul_le_mul_of_nonneg_left (ih (nat.succ_ne_zero k)) h2 } end theorem pow_lt_pow_of_lt_left (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ← tsub_add_cancel_of_le (nat.succ_le_of_lt Hnpos), induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end lemma pow_lt_one (h₀ : 0 ≤ a) (h₁ : a < 1) {n : ℕ} (hn : n ≠ 0) : a ^ n < 1 := (one_pow n).subst (pow_lt_pow_of_lt_left h₁ h₀ (nat.pos_of_ne_zero hn)) theorem strict_mono_on_pow (hn : 0 < n) : strict_mono_on (λ x : R, x ^ n) (set.Ici 0) := λ x hx y hy h, pow_lt_pow_of_lt_left h hx hn theorem one_le_pow_of_one_le (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := by rw [pow_zero] | (n+1) := by { rw pow_succ, simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) } lemma pow_mono (h : 1 ≤ a) : monotone (λ n : ℕ, a ^ n) := monotone_nat_of_le_succ $ λ n, by { rw pow_succ, exact le_mul_of_one_le_left (pow_nonneg (zero_le_one.trans h) _) h } theorem pow_le_pow (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := pow_mono ha h theorem le_self_pow (ha : 1 ≤ a) (h : 1 ≤ m) : a ≤ a ^ m := eq.trans_le (pow_one a).symm (pow_le_pow ha h) lemma strict_mono_pow (h : 1 < a) : strict_mono (λ n : ℕ, a ^ n) := have 0 < a := zero_le_one.trans_lt h, strict_mono_nat_of_lt_succ $ λ n, by simpa only [one_mul, pow_succ] using mul_lt_mul h (le_refl (a ^ n)) (pow_pos this _) this.le lemma pow_lt_pow (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := strict_mono_pow h h2 lemma pow_lt_pow_iff (h : 1 < a) : a ^ n < a ^ m ↔ n < m := (strict_mono_pow h).lt_iff_lt lemma pow_le_pow_iff (h : 1 < a) : a ^ n ≤ a ^ m ↔ n ≤ m := (strict_mono_pow h).le_iff_le lemma strict_anti_pow (h₀ : 0 < a) (h₁ : a < 1) : strict_anti (λ n : ℕ, a ^ n) := strict_anti_nat_of_succ_lt $ λ n, by simpa only [pow_succ, one_mul] using mul_lt_mul h₁ le_rfl (pow_pos h₀ n) zero_le_one lemma pow_lt_pow_iff_of_lt_one (h₀ : 0 < a) (h₁ : a < 1) : a ^ m < a ^ n ↔ n < m := (strict_anti_pow h₀ h₁).lt_iff_lt lemma pow_lt_pow_of_lt_one (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := (pow_lt_pow_iff_of_lt_one h ha).2 hij @[mono] lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ], exact mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) } lemma one_lt_pow (ha : 1 < a) {n : ℕ} (hn : n ≠ 0) : 1 < a ^ n := pow_zero a ▸ pow_lt_pow ha (pos_iff_ne_zero.2 hn) lemma pow_le_one : ∀ (n : ℕ) (h₀ : 0 ≤ a) (h₁ : a ≤ 1), a ^ n ≤ 1 | 0 h₀ h₁ := (pow_zero a).le | (n + 1) h₀ h₁ := (pow_succ' a n).le.trans (mul_le_one (pow_le_one n h₀ h₁) h₀ h₁) lemma sq_pos_of_pos (ha : 0 < a) : 0 < a ^ 2 := by { rw sq, exact mul_pos ha ha } end ordered_semiring section ordered_ring variables [ordered_ring R] {a : R} lemma sq_pos_of_neg (ha : a < 0) : 0 < a ^ 2 := by { rw sq, exact mul_pos_of_neg_of_neg ha ha } lemma pow_bit0_pos_of_neg (ha : a < 0) (n : ℕ) : 0 < a ^ bit0 n := begin rw pow_bit0', exact pow_pos (mul_pos_of_neg_of_neg ha ha) _, end lemma pow_bit1_neg (ha : a < 0) (n : ℕ) : a ^ bit1 n < 0 := begin rw [bit1, pow_succ], exact mul_neg_of_neg_of_pos ha (pow_bit0_pos_of_neg ha n), end end ordered_ring section linear_ordered_semiring variable [linear_ordered_semiring R] lemma pow_le_one_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : a ^ n ≤ 1 ↔ a ≤ 1 := begin refine ⟨_, pow_le_one n ha⟩, rw [←not_lt, ←not_lt], exact mt (λ h, one_lt_pow h hn), end lemma one_le_pow_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : 1 ≤ a ^ n ↔ 1 ≤ a := begin refine ⟨_, λ h, one_le_pow_of_one_le h n⟩, rw [←not_lt, ←not_lt], exact mt (λ h, pow_lt_one ha h hn), end lemma one_lt_pow_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : 1 < a ^ n ↔ 1 < a := lt_iff_lt_of_le_iff_le (pow_le_one_iff_of_nonneg ha hn) lemma pow_lt_one_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : a ^ n < 1 ↔ a < 1 := lt_iff_lt_of_le_iff_le (one_le_pow_iff_of_nonneg ha hn) lemma sq_le_one_iff {a : R} (ha : 0 ≤ a) : a^2 ≤ 1 ↔ a ≤ 1 := pow_le_one_iff_of_nonneg ha (nat.succ_ne_zero _) lemma sq_lt_one_iff {a : R} (ha : 0 ≤ a) : a^2 < 1 ↔ a < 1 := pow_lt_one_iff_of_nonneg ha (nat.succ_ne_zero _) lemma one_le_sq_iff {a : R} (ha : 0 ≤ a) : 1 ≤ a^2 ↔ 1 ≤ a := one_le_pow_iff_of_nonneg ha (nat.succ_ne_zero _) lemma one_lt_sq_iff {a : R} (ha : 0 ≤ a) : 1 < a^2 ↔ 1 < a := one_lt_pow_iff_of_nonneg ha (nat.succ_ne_zero _) @[simp] theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) : x ^ n = y ^ n ↔ x = y := (@strict_mono_on_pow R _ _ Hnpos).inj_on.eq_iff Hxpos Hypos lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h lemma le_of_pow_le_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b := le_of_not_lt $ λ h1, not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h @[simp] lemma sq_eq_sq {a b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ 2 = b ^ 2 ↔ a = b := pow_left_inj ha hb dec_trivial end linear_ordered_semiring section linear_ordered_ring variable [linear_ordered_ring R] lemma pow_abs (a : R) (n : ℕ) : |a| ^ n = |a ^ n| := ((abs_hom.to_monoid_hom : R →* R).map_pow a n).symm lemma abs_neg_one_pow (n : ℕ) : |(-1 : R) ^ n| = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] theorem pow_bit0_nonneg (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n := by { rw pow_bit0, exact mul_self_nonneg _ } theorem sq_nonneg (a : R) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 alias sq_nonneg ← pow_two_nonneg theorem pow_bit0_pos {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n := (pow_bit0_nonneg a n).lt_of_ne (pow_ne_zero _ h).symm theorem sq_pos_of_ne_zero (a : R) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 alias sq_pos_of_ne_zero ← pow_two_pos_of_ne_zero theorem pow_bit0_pos_iff (a : R) {n : ℕ} (hn : n ≠ 0) : 0 < a ^ bit0 n ↔ a ≠ 0 := begin refine ⟨λ h, _, λ h, pow_bit0_pos h n⟩, rintro rfl, rw zero_pow (nat.zero_lt_bit0 hn) at h, exact lt_irrefl _ h, end theorem sq_pos_iff (a : R) : 0 < a ^ 2 ↔ a ≠ 0 := pow_bit0_pos_iff a one_ne_zero variables {x y : R} theorem sq_abs (x : R) : |x| ^ 2 = x ^ 2 := by simpa only [sq] using abs_mul_abs_self x theorem abs_sq (x : R) : |x ^ 2| = x ^ 2 := by simpa only [sq] using abs_mul_self x theorem sq_lt_sq (h : |x| < |y|) : x ^ 2 < y ^ 2 := by simpa only [sq_abs] using pow_lt_pow_of_lt_left h (abs_nonneg x) (1:ℕ).succ_pos theorem sq_lt_sq' (h1 : -y < x) (h2 : x < y) : x ^ 2 < y ^ 2 := sq_lt_sq (lt_of_lt_of_le (abs_lt.2 ⟨h1, h2⟩) (le_abs_self _)) theorem sq_le_sq (h : |x| ≤ |y|) : x ^ 2 ≤ y ^ 2 := by simpa only [sq_abs] using pow_le_pow_of_le_left (abs_nonneg x) h 2 theorem sq_le_sq' (h1 : -y ≤ x) (h2 : x ≤ y) : x ^ 2 ≤ y ^ 2 := sq_le_sq (le_trans (abs_le.mpr ⟨h1, h2⟩) (le_abs_self _)) theorem abs_lt_abs_of_sq_lt_sq (h : x^2 < y^2) : |x| < |y| := lt_of_pow_lt_pow 2 (abs_nonneg y) $ by rwa [← sq_abs x, ← sq_abs y] at h theorem abs_lt_of_sq_lt_sq (h : x^2 < y^2) (hy : 0 ≤ y) : |x| < y := begin rw [← abs_of_nonneg hy], exact abs_lt_abs_of_sq_lt_sq h, end theorem abs_lt_of_sq_lt_sq' (h : x^2 < y^2) (hy : 0 ≤ y) : -y < x ∧ x < y := abs_lt.mp $ abs_lt_of_sq_lt_sq h hy theorem abs_le_abs_of_sq_le_sq (h : x^2 ≤ y^2) : |x| ≤ |y| := le_of_pow_le_pow 2 (abs_nonneg y) (1:ℕ).succ_pos $ by rwa [← sq_abs x, ← sq_abs y] at h theorem abs_le_of_sq_le_sq (h : x^2 ≤ y^2) (hy : 0 ≤ y) : |x| ≤ y := begin rw [← abs_of_nonneg hy], exact abs_le_abs_of_sq_le_sq h, end theorem abs_le_of_sq_le_sq' (h : x^2 ≤ y^2) (hy : 0 ≤ y) : -y ≤ x ∧ x ≤ y := abs_le.mp $ abs_le_of_sq_le_sq h hy lemma sq_eq_sq_iff_abs_eq_abs (x y : R) : x^2 = y^2 ↔ |x| = |y| := ⟨λ h, (abs_le_abs_of_sq_le_sq h.le).antisymm (abs_le_abs_of_sq_le_sq h.ge), λ h, by rw [←sq_abs, h, sq_abs]⟩ @[simp] lemma sq_eq_one_iff (x : R) : x^2 = 1 ↔ x = 1 ∨ x = -1 := by rw [←abs_eq_abs, ←sq_eq_sq_iff_abs_eq_abs, one_pow] lemma sq_ne_one_iff (x : R) : x^2 ≠ 1 ↔ x ≠ 1 ∧ x ≠ -1 := (not_iff_not.2 (sq_eq_one_iff _)).trans not_or_distrib @[simp] lemma sq_le_one_iff_abs_le_one (x : R) : x^2 ≤ 1 ↔ |x| ≤ 1 := have t : x^2 ≤ 1^2 ↔ |x| ≤ |1| := ⟨abs_le_abs_of_sq_le_sq, sq_le_sq⟩, by simpa using t @[simp] lemma sq_lt_one_iff_abs_lt_one (x : R) : x^2 < 1 ↔ |x| < 1 := have t : x^2 < 1^2 ↔ |x| < |1| := ⟨abs_lt_abs_of_sq_lt_sq, sq_lt_sq⟩, by simpa using t @[simp] lemma one_le_sq_iff_one_le_abs (x : R) : 1 ≤ x^2 ↔ 1 ≤ |x| := have t : 1^2 ≤ x^2 ↔ |1| ≤ |x| := ⟨abs_le_abs_of_sq_le_sq, sq_le_sq⟩, by simpa using t @[simp] lemma one_lt_sq_iff_one_lt_abs (x : R) : 1 < x^2 ↔ 1 < |x| := have t : 1^2 < x^2 ↔ |1| < |x| := ⟨abs_lt_abs_of_sq_lt_sq, sq_lt_sq⟩, by simpa using t lemma pow_four_le_pow_two_of_pow_two_le {x y : R} (h : x^2 ≤ y) : x^4 ≤ y^2 := (pow_mul x 2 2).symm ▸ pow_le_pow_of_le_left (sq_nonneg x) h 2 end linear_ordered_ring section linear_ordered_comm_ring variables [linear_ordered_comm_ring R] /-- Arithmetic mean-geometric mean (AM-GM) inequality for linearly ordered commutative rings. -/ lemma two_mul_le_add_sq (a b : R) : 2 * a * b ≤ a ^ 2 + b ^ 2 := sub_nonneg.mp ((sub_add_eq_add_sub _ _ _).subst ((sub_sq a b).subst (sq_nonneg _))) alias two_mul_le_add_sq ← two_mul_le_add_pow_two end linear_ordered_comm_ring
f2d48e020717ec9e0764cd3054d7980168d55fd4
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/polynomial/ring_division.lean
dc316738a09c8e618aa30c0e8ac21723dafdd643
[ "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
34,132
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div import ring_theory.localization.fraction_ring import algebra.polynomial.big_operators /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : R[X]} section variables [semiring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma mod_by_monic_eq_of_dvd_sub (hq : q.monic) {p₁ p₂ : R[X]} (h : q ∣ (p₁ - p₂)) : p₁ %ₘ q = p₂ %ₘ q := begin nontriviality R, obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (p₂ /ₘ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic (p₁ p₂ : R[X]) : (p₁ + p₂) %ₘ q = p₁ %ₘ q + p₂ %ₘ q := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (p₁ /ₘ q + p₂ /ₘ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end lemma smul_mod_by_monic (c : R) (p : R[X]) : (c • p) %ₘ q = c • (p %ₘ q) := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end /-- `_ %ₘ q` as an `R`-linear map. -/ @[simps] def mod_by_monic_hom (q : R[X]) : R[X] →ₗ[R] R[X] := { to_fun := λ p, p %ₘ q, map_add' := add_mod_by_monic, map_smul' := smul_mod_by_monic } end section variables [ring S] lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : R[X]} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := -- `eval₂_mod_by_monic_eq_self_of_root` doesn't work here as it needs commutativity by rw [mod_by_monic_eq_sub_mul_div p hq, _root_.map_sub, _root_.map_mul, hx, zero_mul, sub_zero] end end comm_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} instance : no_zero_divisors R[X] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] lemma trailing_degree_mul : (p * q).trailing_degree = p.trailing_degree + q.trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, trailing_degree_zero, top_add] }, by_cases hq : q = 0, { rw [hq, mul_zero, trailing_degree_zero, add_top] }, rw [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, trailing_degree_eq_nat_trailing_degree (mul_ne_zero hp hq), nat_trailing_degree_mul hp hq, with_top.coe_add], end @[simp] lemma nat_degree_pow (p : R[X]) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma degree_le_mul_left (p : R[X]) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end /-- This lemma is useful for working with the `int_degree` of a rational function. -/ lemma nat_degree_sub_eq_of_prod_eq {p₁ p₂ q₁ q₂ : polynomial R} (hp₁ : p₁ ≠ 0) (hq₁ : q₁ ≠ 0) (hp₂ : p₂ ≠ 0) (hq₂ : q₂ ≠ 0) (h_eq : p₁ * q₂ = p₂ * q₁) : (p₁.nat_degree : ℤ) - q₁.nat_degree = (p₂.nat_degree : ℤ) - q₂.nat_degree := begin rw sub_eq_sub_iff_add_eq_add, norm_cast, rw [← nat_degree_mul hp₁ hq₂, ← nat_degree_mul hp₂ hq₁, h_eq] end end no_zero_divisors section no_zero_divisors variables [comm_semiring R] [no_zero_divisors R] {p q : R[X]} lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h end no_zero_divisors section ring variables [ring R] [is_domain R] {p q : R[X]} instance : is_domain R[X] := { ..polynomial.no_zero_divisors, ..polynomial.nontrivial, } end ring section comm_ring variables [comm_ring R] [is_domain R] {p q : R[X]} section roots open multiset lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : R[X]) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : R[X]ˣ) : degree (u : R[X]) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C r, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : R[X]) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : R[X]) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, apply_instance, end lemma root_multiplicity_mul {p q : R[X]} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := pow_ne_zero n.succ (X_sub_C_ne_zero a), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : R[X]} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : R[X]} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : ∀ {p : R[X]} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : R[X]) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : R[X]).roots = 0 := dif_pos rfl lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' (p : R[X]) : p.roots.card ≤ nat_degree p := begin by_cases hp0 : p = 0, { simp [hp0], }, exact with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) end lemma card_roots_sub_C {p : R[X]} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : R[X]} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (p : R[X]) : p.roots.count a = root_multiplicity a p := begin by_cases hp : p = 0, { simp [hp], }, rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots p, root_multiplicity_pos hp] theorem card_le_degree_of_subset_roots {p : R[X]} {Z : finset R} (h : Z.val ⊆ p.roots) : Z.card ≤ p.nat_degree := (multiset.card_le_of_le (finset.val_le_iff_val_subset.2 h)).trans (polynomial.card_roots' p) lemma finite_set_of_is_root {p : R[X]} (hp : p ≠ 0) : set.finite {x | is_root p x} := by simpa only [← finset.set_of_mem, mem_to_finset, mem_roots hp] using p.roots.to_finset.finite_to_set lemma eq_zero_of_infinite_is_root (p : R[X]) (h : set.infinite {x | is_root p x}) : p = 0 := not_imp_comm.mp finite_set_of_is_root h lemma exists_max_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ finite_set_of_is_root hp lemma exists_min_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ finite_set_of_is_root hp lemma eq_of_infinite_eval_eq (p q : R[X]) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : R[X]} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots, count_roots, count_roots, root_multiplicity_mul hpq] lemma roots.le_of_dvd (h : q ≠ 0) : p ∣ q → roots p ≤ roots q := begin rintro ⟨k, rfl⟩, exact multiset.le_iff_exists_add.mpr ⟨k.roots, roots_mul h⟩ end @[simp] lemma mem_roots_sub_C {p : R[X]} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots, root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton_self] }, { rw [singleton_eq_cons, count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, by rw [count_roots, count_zero, root_multiplicity_eq_zero (not_is_root_C _ _ H)] @[simp] lemma roots_one : (1 : R[X]).roots = ∅ := roots_C 1 lemma roots_smul_nonzero (p : R[X]) {r : R} (hr : r ≠ 0) : (r • p).roots = p.roots := begin by_cases hp : p = 0; simp [smul_eq_C_mul, roots_mul, hr, hp] end lemma roots_list_prod (L : list R[X]) : ((0 : R[X]) ∉ L) → L.prod.roots = (L : multiset R[X]).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset R[X]) : (0 : R[X]) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [multiset.coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → R[X]) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) @[simp] lemma roots_multiset_prod_X_sub_C (s : multiset R) : (s.map (λ a, X - C a)).prod.roots = s := begin rw [roots_multiset_prod, multiset.bind_map], { simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id'] }, { rw [multiset.mem_map], rintro ⟨a, -, h⟩, exact X_sub_C_ne_zero a h }, end @[simp] lemma nat_degree_multiset_prod_X_sub_C_eq_card (s : multiset R): (s.map (λ a, X - C a)).prod.nat_degree = s.card := begin rw [nat_degree_multiset_prod_of_monic, multiset.map_map], { convert multiset.sum_repeat 1 _, { convert multiset.map_const _ 1, ext, apply nat_degree_X_sub_C }, { simp } }, { intros f hf, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.1 hf, exact monic_X_sub_C a }, end lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : R[X]) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : R[X]) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : R[X]) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section variables {A B : Type*} [comm_ring A] [comm_ring B] lemma le_root_multiplicity_map {p : A[X]} {f : A →+* B} (hmap : map f p ≠ 0) (a : A) : root_multiplicity a p ≤ root_multiplicity (f a) (map f p) := begin have hp0 : p ≠ 0 := λ h, hmap (h.symm ▸ polynomial.map_zero f), rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, have := (map_ring_hom f).map_dvd (hm m le_rfl), simpa only [coe_map_ring_hom, map_pow, map_sub, map_X, map_C], end lemma eq_root_multiplicity_map {p : A[X]} {f : A →+* B} (hf : function.injective f) (a : A) : root_multiplicity a p = root_multiplicity (f a) (map f p) := begin by_cases hp0 : p = 0, { simp only [hp0, root_multiplicity_zero, polynomial.map_zero], }, have hmap : map f p ≠ 0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply le_antisymm (le_root_multiplicity_map hmap a), rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, rw ← map_dvd_map f hf ((monic_X_sub_C a).pow _), convert hm m le_rfl, simp only [polynomial.map_pow, polynomial.map_sub, map_pow, map_sub, map_X, map_C], end lemma count_map_roots [is_domain A] (p : A[X]) {f : A →+* B} (hf : function.injective f) (a : B) : count a (p.roots.map f) ≤ root_multiplicity a (map f p) := begin by_cases h : ∃ t, f t = a, { rcases h with ⟨h_w, rfl⟩, rw [multiset.count_map_eq_count' f _ hf, count_roots], exact (eq_root_multiplicity_map hf h_w).le }, { suffices : (multiset.map f p.roots).count a = 0, { rw this, exact zero_le _, }, rw [multiset.count_map, multiset.card_eq_zero, multiset.filter_eq_nil], rintro k hk rfl, exact h ⟨k, rfl⟩, }, end lemma roots_map_of_injective_card_eq_total_degree [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (hf : function.injective f) (hroots : p.roots.card = p.nat_degree) : p.roots.map f = (map f p).roots := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, polynomial.map_zero], }, have hmap : map f p ≠ 0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply multiset.eq_of_le_of_card_le, { simpa only [multiset.le_iff_count, count_roots] using count_map_roots p hf }, { simpa only [multiset.card_map, hroots] using (card_roots' _).trans (nat_degree_map_le f p) }, end end section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : R[X]) ^ n - C a) @[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : R[X]) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], exact degree_C_le })) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] @[simp] lemma nth_roots_finset_zero : nth_roots_finset 0 R = ∅ := by simp [nth_roots_finset] end nth_roots lemma monic.comp (hp : p.monic) (hq : q.monic) (h : q.nat_degree ≠ 0) : (p.comp q).monic := by rw [monic.def, leading_coeff_comp h, monic.def.1 hp, monic.def.1 hq, one_pow, one_mul] lemma monic.comp_X_add_C (hp : p.monic) (r : R) : (p.comp (X + C r)).monic := begin refine hp.comp (monic_X_add_C _) (λ ha, _), rw [nat_degree_X_add_C] at ha, exact one_ne_zero ha end lemma monic.comp_X_sub_C (hp : p.monic) (r : R) : (p.comp (X - C r)).monic := by simpa using hp.comp_X_add_C (-r) lemma units_coeff_zero_smul (c : R[X]ˣ) (p : R[X]) : (c : R[X]).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : R[X]ˣ) : nat_degree (u : R[X]) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : R[X]) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : R[X]} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : set S := (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := rfl @[simp] lemma root_set_zero (S) [comm_ring S] [is_domain S] [algebra T S] : (0 : T[X]).root_set S = ∅ := by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty] @[simp] lemma root_set_C [comm_ring S] [is_domain S] [algebra T S] (a : T) : (C a).root_set S = ∅ := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] instance root_set_fintype (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : (p.root_set S).finite := set.to_finite _ theorem mem_root_set_iff' {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] (hp : p.map (algebra_map T S) ≠ 0) (a : S) : a ∈ p.root_set S ↔ (p.map (algebra_map T S)).eval a = 0 := by { change a ∈ multiset.to_finset _ ↔ _, rw [mem_to_finset, mem_roots hp], refl } theorem mem_root_set_iff {p : T[X]} (hp : p ≠ 0) {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] (a : S) : a ∈ p.root_set S ↔ aeval a p = 0 := begin rw [mem_root_set_iff', ←eval₂_eq_eval_map], { refl }, intro h, rw ←polynomial.map_zero (algebra_map T S) at h, exact hp (map_injective _ (no_zero_smul_divisors.algebra_map_injective T S) h) end end roots theorem is_unit_iff {f : R[X]} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : R[X]ˣ) : coeff (u : R[X]) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] {p q : R[X]} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin nontriviality, have h : q.leading_coeff * (p /ₘ q).leading_coeff ≠ 0, { simpa [div_by_monic_eq_zero_iff hmonic, hmonic.leading_coeff, nat.with_bot.one_le_iff_zero_lt] using hdegree }, nth_rewrite_rhs 0 ←mod_by_monic_add_div p hmonic, rw [leading_coeff_add_of_degree_lt, leading_coeff_monic_mul hmonic], rw [degree_mul' h, degree_add_div_by_monic hmonic hdegree], exact (degree_mod_by_monic_lt p hmonic).trans_le hdegree end lemma leading_coeff_div_by_monic_X_sub_C (p : R[X]) (hp : degree p ≠ 0) (a : R) : leading_coeff (p /ₘ (X - C a)) = leading_coeff p := begin nontriviality, cases hp.lt_or_lt with hd hd, { rw [degree_eq_bot.mp $ (nat.with_bot.lt_zero_iff _).mp hd, zero_div_by_monic] }, refine leading_coeff_div_by_monic_of_monic (monic_X_sub_C a) _, rwa [degree_X_sub_C, nat.with_bot.one_le_iff_zero_lt] end lemma eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = C q.leading_coeff * p := begin obtain ⟨r, hr⟩ := hdiv, obtain (rfl|hq) := eq_or_ne q 0, {simp}, have rzero : r ≠ 0 := λ h, by simpa [h, hq] using hr, rw [hr, nat_degree_mul'] at hdeg, swap, { rw [hp.leading_coeff, one_mul, leading_coeff_ne_zero], exact rzero }, rw [mul_comm, @eq_C_of_nat_degree_eq_zero _ _ r] at hr, { convert hr, convert leading_coeff_C _ using 1, rw [hr, leading_coeff_mul_monic hp] }, { exact (add_right_inj _).1 (le_antisymm hdeg $ nat.le.intro rfl) }, end lemma eq_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin convert eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le hp hdiv hdeg, rw [hq.leading_coeff, C_1, one_mul], end lemma is_coprime_X_sub_C_of_is_unit_sub {R} [comm_ring R] {a b : R} (h : is_unit (a - b)) : is_coprime (X - C a) (X - C b) := ⟨-C h.unit⁻¹.val, C h.unit⁻¹.val, by { rw [neg_mul_comm, ← left_distrib, neg_add_eq_sub, sub_sub_sub_cancel_left, ← C_sub, ← C_mul], convert C_1, exact h.coe_inv_mul }⟩ theorem pairwise_coprime_X_sub_C {K} [field K] {I : Type v} {s : I → K} (H : function.injective s) : pairwise (is_coprime on (λ i : I, X - C (s i))) := λ i j hij, is_coprime_X_sub_C_of_is_unit_sub (sub_ne_zero_of_ne $ H.ne hij).is_unit lemma monic_prod_multiset_X_sub_C : monic (p.roots.map (λ a, X - C a)).prod := monic_multiset_prod_of_monic _ _ (λ a _, monic_X_sub_C a) lemma prod_multiset_root_eq_finset_root : (p.roots.map (λ a, X - C a)).prod = p.roots.to_finset.prod (λ a, (X - C a) ^ root_multiplicity a p) := by simp only [count_roots, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : R[X]) : (p.roots.map (λ a, X - C a)).prod ∣ p := begin rw ← map_dvd_map _ (is_fraction_ring.injective R $ fraction_ring R) monic_prod_multiset_X_sub_C, rw [prod_multiset_root_eq_finset_root, polynomial.map_prod], refine finset.prod_dvd_of_coprime (λ a _ b _ h, _) (λ a _, _), { simp_rw [polynomial.map_pow, polynomial.map_sub, map_C, map_X], exact (pairwise_coprime_X_sub_C (is_fraction_ring.injective R $ fraction_ring R) _ _ h).pow }, { exact polynomial.map_dvd _ (pow_root_multiplicity_dvd p a) }, end lemma exists_prod_multiset_X_sub_C_mul (p : R[X]) : ∃ q, (p.roots.map (λ a, X - C a)).prod * q = p ∧ p.roots.card + q.nat_degree = p.nat_degree ∧ q.roots = 0 := begin obtain ⟨q, he⟩ := prod_multiset_X_sub_C_dvd p, use [q, he.symm], obtain (rfl|hq) := eq_or_ne q 0, { rw mul_zero at he, subst he, simp }, split, { conv_rhs { rw he }, rw [monic_prod_multiset_X_sub_C.nat_degree_mul' hq, nat_degree_multiset_prod_X_sub_C_eq_card] }, { replace he := congr_arg roots he.symm, rw [roots_mul, roots_multiset_prod_X_sub_C] at he, exacts [add_right_eq_self.1 he, mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq] }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (p.roots.map (λ a, X - C a)).prod = p := (eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le monic_prod_multiset_X_sub_C (prod_multiset_X_sub_C_dvd p) $ ((nat_degree_multiset_prod_X_sub_C_eq_card _).trans hroots).ge).symm /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq (hp : p.monic) (hroots : p.roots.card = p.nat_degree) : (p.roots.map (λ a, X - C a)).prod = p := by { convert C_leading_coeff_mul_prod_multiset_X_sub_C hroots, rw [hp.leading_coeff, C_1, one_mul] } end comm_ring section variables [semiring R] [comm_ring S] [is_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map {f : R[X]} (hf : is_unit f.leading_coeff) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map C _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin refine ⟨h_irr.not_unit ∘ is_unit.map (map_ring_hom φ), λ a b h, _⟩, dsimp [monic] at h_mon, have q := (leading_coeff_mul a b).symm, rw [←h, h_mon] at q, refine (h_irr.is_unit_or_is_unit $ (congr_arg (map φ) h).trans (polynomial.map_mul φ)).imp _ _; apply is_unit_of_is_unit_leading_coeff_of_is_unit_map; apply is_unit_of_mul_eq_one, { exact q }, { rw mul_comm, exact q }, end end end polynomial
21c65eb296cca30699f61e997462a2239bb7bb8e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/multiset/sum.lean
40c4c9f4d18c1dab33ea79503c140dffebc3588f
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
3,137
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.multiset.nodup /-! # Disjoint sum of multisets This file defines the disjoint sum of two multisets as `multiset (α ⊕ β)`. Beware not to confuse with the `multiset.sum` operation which computes the additive sum. ## Main declarations * `multiset.disj_sum`: `s.disj_sum t` is the disjoint sum of `s` and `t`. -/ open sum namespace multiset variables {α β : Type*} (s : multiset α) (t : multiset β) /-- Disjoint sum of multisets. -/ def disj_sum : multiset (α ⊕ β) := s.map inl + t.map inr @[simp] lemma zero_disj_sum : (0 : multiset α).disj_sum t = t.map inr := zero_add _ @[simp] lemma disj_sum_zero : s.disj_sum (0 : multiset β) = s.map inl := add_zero _ @[simp] lemma card_disj_sum : (s.disj_sum t).card = s.card + t.card := by rw [disj_sum, card_add, card_map, card_map] variables {s t} {s₁ s₂ : multiset α} {t₁ t₂ : multiset β} {a : α} {b : β} {x : α ⊕ β} lemma mem_disj_sum : x ∈ s.disj_sum t ↔ (∃ a, a ∈ s ∧ inl a = x) ∨ ∃ b, b ∈ t ∧ inr b = x := by simp_rw [disj_sum, mem_add, mem_map] @[simp] lemma inl_mem_disj_sum : inl a ∈ s.disj_sum t ↔ a ∈ s := begin rw [mem_disj_sum, or_iff_left], simp only [exists_eq_right], rintro ⟨b, _, hb⟩, exact inr_ne_inl hb, end @[simp] lemma inr_mem_disj_sum : inr b ∈ s.disj_sum t ↔ b ∈ t := begin rw [mem_disj_sum, or_iff_right], simp only [exists_eq_right], rintro ⟨a, _, ha⟩, exact inl_ne_inr ha, end lemma disj_sum_mono (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.disj_sum t₁ ≤ s₂.disj_sum t₂ := add_le_add (map_le_map hs) (map_le_map ht) lemma disj_sum_mono_left (t : multiset β) : monotone (λ s : multiset α, s.disj_sum t) := λ s₁ s₂ hs, add_le_add_right (map_le_map hs) _ lemma disj_sum_mono_right (s : multiset α) : monotone (s.disj_sum : multiset β → multiset (α ⊕ β)) := λ t₁ t₂ ht, add_le_add_left (map_le_map ht) _ lemma disj_sum_lt_disj_sum_of_lt_of_le (hs : s₁ < s₂) (ht : t₁ ≤ t₂) : s₁.disj_sum t₁ < s₂.disj_sum t₂ := add_lt_add_of_lt_of_le (map_lt_map hs) (map_le_map ht) lemma disj_sum_lt_disj_sum_of_le_of_lt (hs : s₁ ≤ s₂) (ht : t₁ < t₂) : s₁.disj_sum t₁ < s₂.disj_sum t₂ := add_lt_add_of_le_of_lt (map_le_map hs) (map_lt_map ht) lemma disj_sum_strict_mono_left (t : multiset β) : strict_mono (λ s : multiset α, s.disj_sum t) := λ s₁ s₂ hs, disj_sum_lt_disj_sum_of_lt_of_le hs le_rfl lemma disj_sum_strict_mono_right (s : multiset α) : strict_mono (s.disj_sum : multiset β → multiset (α ⊕ β)) := λ s₁ s₂, disj_sum_lt_disj_sum_of_le_of_lt le_rfl protected lemma nodup.disj_sum (hs : s.nodup) (ht : t.nodup) : (s.disj_sum t).nodup := begin refine (multiset.nodup_add_of_nodup (multiset.nodup_map inl_injective hs) $ multiset.nodup_map inr_injective ht).2 (λ x hs ht, _), rw multiset.mem_map at hs ht, obtain ⟨a, _, rfl⟩ := hs, obtain ⟨b, _, h⟩ := ht, exact inr_ne_inl h, end end multiset
1aa35c3262bfce068d280461eb0dc30278544b2c
c777c32c8e484e195053731103c5e52af26a25d1
/src/category_theory/cofiltered_system.lean
73df182bb6ee8a39d5d0e37f7a429ec827bf64bc
[ "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
15,911
lean
/- Copyright (c) 2022 Kyle Miller, Adam Topaz, Rémi Bottinelli, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Adam Topaz, Rémi Bottinelli, Junyan Xu -/ import category_theory.filtered import data.set.finite import topology.category.Top.limits.konig /-! # Cofiltered systems This file deals with properties of cofiltered (and inverse) systems. ## Main definitions Given a functor `F : J ⥤ Type v`: * For `j : J`, `F.eventual_range j` is the intersections of all ranges of morphisms `F.map f` where `f` has codomain `j`. * `F.is_mittag_leffler` states that the functor `F` satisfies the Mittag-Leffler condition: the ranges of morphisms `F.map f` (with `f` having codomain `j`) stabilize. * If `J` is cofiltered `F.to_eventual_ranges` is the subfunctor of `F` obtained by restriction to `F.eventual_range`. * `F.to_preimages` restricts a functor to preimages of a given set in some `F.obj i`. If `J` is cofiltered, then it is Mittag-Leffler if `F` is, see `is_mittag_leffler.to_preimages`. ## Main statements * `nonempty_sections_of_finite_cofiltered_system` shows that if `J` is cofiltered and each `F.obj j` is nonempty and finite, `F.sections` is nonempty. * `nonempty_sections_of_finite_inverse_system` is a specialization of the above to `J` being a directed set (and `F : Jᵒᵖ ⥤ Type v`). * `is_mittag_leffler_of_exists_finite_range` shows that if `J` is cofiltered and for all `j`, there exists some `i` and `f : i ⟶ j` such that the range of `F.map f` is finite, then `F` is Mittag-Leffler. * `to_eventual_ranges_surjective` shows that if `F` is Mittag-Leffler, then `F.to_eventual_ranges` has all morphisms `F.map f` surjective. ## Todo * Prove [Stacks: Lemma 0597](https://stacks.math.columbia.edu/tag/0597) ## References * [Stacks: Mittag-Leffler systems](https://stacks.math.columbia.edu/tag/0594) ## Tags Mittag-Leffler, surjective, eventual range, inverse system, -/ universes u v w open category_theory category_theory.is_cofiltered set category_theory.functor_to_types section finite_konig /-- This bootstraps `nonempty_sections_of_finite_inverse_system`. In this version, the `F` functor is between categories of the same universe, and it is an easy corollary to `Top.nonempty_limit_cone_of_compact_t2_inverse_system`. -/ lemma nonempty_sections_of_finite_cofiltered_system.init {J : Type u} [small_category J] [is_cofiltered_or_empty J] (F : J ⥤ Type u) [hf : ∀ j, finite (F.obj j)] [hne : ∀ j, nonempty (F.obj j)] : F.sections.nonempty := begin let F' : J ⥤ Top := F ⋙ Top.discrete, haveI : ∀ j, discrete_topology (F'.obj j) := λ _, ⟨rfl⟩, haveI : ∀ j, finite (F'.obj j) := hf, haveI : ∀ j, nonempty (F'.obj j) := hne, obtain ⟨⟨u, hu⟩⟩ := Top.nonempty_limit_cone_of_compact_t2_cofiltered_system F', exact ⟨u, λ _ _, hu⟩, end /-- The cofiltered limit of nonempty finite types is nonempty. See `nonempty_sections_of_finite_inverse_system` for a specialization to inverse limits. -/ theorem nonempty_sections_of_finite_cofiltered_system {J : Type u} [category.{w} J] [is_cofiltered_or_empty J] (F : J ⥤ Type v) [∀ (j : J), finite (F.obj j)] [∀ (j : J), nonempty (F.obj j)] : F.sections.nonempty := begin -- Step 1: lift everything to the `max u v w` universe. let J' : Type (max w v u) := as_small.{max w v} J, let down : J' ⥤ J := as_small.down, let F' : J' ⥤ Type (max u v w) := down ⋙ F ⋙ ulift_functor.{(max u w) v}, haveI : ∀ i, nonempty (F'.obj i) := λ i, ⟨⟨classical.arbitrary (F.obj (down.obj i))⟩⟩, haveI : ∀ i, finite (F'.obj i) := λ i, finite.of_equiv (F.obj (down.obj i)) equiv.ulift.symm, -- Step 2: apply the bootstrap theorem casesI is_empty_or_nonempty J, { fsplit; exact is_empty_elim }, haveI : is_cofiltered J := ⟨⟩, obtain ⟨u, hu⟩ := nonempty_sections_of_finite_cofiltered_system.init F', -- Step 3: interpret the results use λ j, (u ⟨j⟩).down, intros j j' f, have h := @hu (⟨j⟩ : J') (⟨j'⟩ : J') (ulift.up f), simp only [as_small.down, functor.comp_map, ulift_functor_map, functor.op_map] at h, simp_rw [←h], refl, end /-- The inverse limit of nonempty finite types is nonempty. See `nonempty_sections_of_finite_cofiltered_system` for a generalization to cofiltered limits. That version applies in almost all cases, and the only difference is that this version allows `J` to be empty. This may be regarded as a generalization of Kőnig's lemma. To specialize: given a locally finite connected graph, take `Jᵒᵖ` to be `ℕ` and `F j` to be length-`j` paths that start from an arbitrary fixed vertex. Elements of `F.sections` can be read off as infinite rays in the graph. -/ theorem nonempty_sections_of_finite_inverse_system {J : Type u} [preorder J] [is_directed J (≤)] (F : Jᵒᵖ ⥤ Type v) [∀ (j : Jᵒᵖ), finite (F.obj j)] [∀ (j : Jᵒᵖ), nonempty (F.obj j)] : F.sections.nonempty := begin casesI is_empty_or_nonempty J, { haveI : is_empty Jᵒᵖ := ⟨λ j, is_empty_elim j.unop⟩, -- TODO: this should be a global instance exact ⟨is_empty_elim, is_empty_elim⟩, }, { exact nonempty_sections_of_finite_cofiltered_system _, }, end end finite_konig namespace category_theory namespace functor variables {J : Type u} [category J] (F : J ⥤ Type v) {i j k : J} (s : set (F.obj i)) /-- The eventual range of the functor `F : J ⥤ Type v` at index `j : J` is the intersection of the ranges of all maps `F.map f` with `i : J` and `f : i ⟶ j`. -/ def eventual_range (j : J) := ⋂ i (f : i ⟶ j), range (F.map f) lemma mem_eventual_range_iff {x : F.obj j} : x ∈ F.eventual_range j ↔ ∀ ⦃i⦄ (f : i ⟶ j), x ∈ range (F.map f) := mem_Inter₂ /-- The functor `F : J ⥤ Type v` satisfies the Mittag-Leffler condition if for all `j : J`, there exists some `i : J` and `f : i ⟶ j` such that for all `k : J` and `g : k ⟶ j`, the range of `F.map f` is contained in that of `F.map g`; in other words (see `is_mittag_leffler_iff_eventual_range`), the eventual range at `j` is attained by some `f : i ⟶ j`. -/ def is_mittag_leffler : Prop := ∀ j : J, ∃ i (f : i ⟶ j), ∀ ⦃k⦄ (g : k ⟶ j), range (F.map f) ⊆ range (F.map g) lemma is_mittag_leffler_iff_eventual_range : F.is_mittag_leffler ↔ ∀ j : J, ∃ i (f : i ⟶ j), F.eventual_range j = range (F.map f) := forall_congr $ λ j, exists₂_congr $ λ i f, ⟨λ h, (Inter₂_subset _ _).antisymm $ subset_Inter₂ h, λ h, h ▸ Inter₂_subset⟩ lemma is_mittag_leffler.subset_image_eventual_range (h : F.is_mittag_leffler) (f : j ⟶ i) : F.eventual_range i ⊆ F.map f '' (F.eventual_range j) := begin obtain ⟨k, g, hg⟩ := F.is_mittag_leffler_iff_eventual_range.1 h j, rw hg, intros x hx, obtain ⟨x, rfl⟩ := F.mem_eventual_range_iff.1 hx (g ≫ f), refine ⟨_, ⟨x, rfl⟩, by simpa only [F.map_comp]⟩, end lemma eventual_range_eq_range_precomp (f : i ⟶ j) (g : j ⟶ k) (h : F.eventual_range k = range (F.map g)) : F.eventual_range k = range (F.map $ f ≫ g) := begin apply subset_antisymm, { apply Inter₂_subset, }, { rw [h, F.map_comp], apply range_comp_subset_range, } end lemma is_mittag_leffler_of_surjective (h : ∀ ⦃i j : J⦄ (f :i ⟶ j), (F.map f).surjective) : F.is_mittag_leffler := λ j, ⟨j, 𝟙 j, λ k g, by rw [map_id, types_id, range_id, (h g).range_eq]⟩ /-- The subfunctor of `F` obtained by restricting to the preimages of a set `s ∈ F.obj i`. -/ @[simps] def to_preimages : J ⥤ Type v := { obj := λ j, ⋂ f : j ⟶ i, F.map f ⁻¹' s, map := λ j k g, maps_to.restrict (F.map g) _ _ $ λ x h, begin rw [mem_Inter] at h ⊢, intro f, rw [← mem_preimage, preimage_preimage], convert h (g ≫ f), rw F.map_comp, refl, end, map_id' := λ j, by { simp_rw F.map_id, ext, refl }, map_comp' := λ j k l f g, by { simp_rw F.map_comp, refl } } instance to_preimages_finite [∀ j, finite (F.obj j)] : ∀ j, finite ((F.to_preimages s).obj j) := λ j, subtype.finite variable [is_cofiltered_or_empty J] lemma eventual_range_maps_to (f : j ⟶ i) : (F.eventual_range j).maps_to (F.map f) (F.eventual_range i) := λ x hx, begin rw mem_eventual_range_iff at hx ⊢, intros k f', obtain ⟨l, g, g', he⟩ := cospan f f', obtain ⟨x, rfl⟩ := hx g, rw [← map_comp_apply, he, F.map_comp], exact ⟨_, rfl⟩, end lemma is_mittag_leffler.eq_image_eventual_range (h : F.is_mittag_leffler) (f : j ⟶ i) : F.eventual_range i = F.map f '' (F.eventual_range j) := (h.subset_image_eventual_range F f).antisymm $ maps_to'.1 (F.eventual_range_maps_to f) lemma eventual_range_eq_iff {f : i ⟶ j} : F.eventual_range j = range (F.map f) ↔ ∀ ⦃k⦄ (g : k ⟶ i), range (F.map f) ⊆ range (F.map $ g ≫ f) := begin rw [subset_antisymm_iff, eventual_range, and_iff_right (Inter₂_subset _ _), subset_Inter₂_iff], refine ⟨λ h k g, h _ _, λ h j' f', _⟩, obtain ⟨k, g, g', he⟩ := cospan f f', refine (h g).trans _, rw [he, F.map_comp], apply range_comp_subset_range, end lemma is_mittag_leffler_iff_subset_range_comp : F.is_mittag_leffler ↔ ∀ j : J, ∃ i (f : i ⟶ j), ∀ ⦃k⦄ (g : k ⟶ i), range (F.map f) ⊆ range (F.map $ g ≫ f) := by simp_rw [is_mittag_leffler_iff_eventual_range, eventual_range_eq_iff] lemma is_mittag_leffler.to_preimages (h : F.is_mittag_leffler) : (F.to_preimages s).is_mittag_leffler := (is_mittag_leffler_iff_subset_range_comp _).2 $ λ j, begin obtain ⟨j₁, g₁, f₁, -⟩ := cone_objs i j, obtain ⟨j₂, f₂, h₂⟩ := F.is_mittag_leffler_iff_eventual_range.1 h j₁, refine ⟨j₂, f₂ ≫ f₁, λ j₃ f₃, _⟩, rintro _ ⟨⟨x, hx⟩, rfl⟩, have : F.map f₂ x ∈ F.eventual_range j₁, { rw h₂, exact ⟨_, rfl⟩ }, obtain ⟨y, hy, h₃⟩ := h.subset_image_eventual_range F (f₃ ≫ f₂) this, refine ⟨⟨y, mem_Inter.2 $ λ g₂, _⟩, subtype.ext _⟩, { obtain ⟨j₄, f₄, h₄⟩ := cone_maps g₂ ((f₃ ≫ f₂) ≫ g₁), obtain ⟨y, rfl⟩ := F.mem_eventual_range_iff.1 hy f₄, rw ← map_comp_apply at h₃, rw [mem_preimage, ← map_comp_apply, h₄, ← category.assoc, map_comp_apply, h₃, ← map_comp_apply], apply mem_Inter.1 hx }, { simp_rw [to_preimages_map, maps_to.coe_restrict_apply, subtype.coe_mk], rw [← category.assoc, map_comp_apply, h₃, map_comp_apply] }, end lemma is_mittag_leffler_of_exists_finite_range (h : ∀ (j : J), ∃ i (f : i ⟶ j), (range $ F.map f).finite) : F.is_mittag_leffler := λ j, begin obtain ⟨i, hi, hf⟩ := h j, obtain ⟨m, ⟨i, f, hm⟩, hmin⟩ := finset.is_well_founded_lt.wf.has_min {s : finset (F.obj j) | ∃ i (f : i ⟶ j), ↑s = range (F.map f)} ⟨_, i, hi, hf.coe_to_finset⟩, refine ⟨i, f, λ k g, (directed_on_range.mp $ F.ranges_directed j).is_bot_of_is_min ⟨⟨i, f⟩, rfl⟩ _ _ ⟨⟨k, g⟩, rfl⟩⟩, rintro _ ⟨⟨k', g'⟩, rfl⟩ hl, refine (eq_of_le_of_not_lt hl _).ge, have := hmin _ ⟨k', g', (m.finite_to_set.subset $ hm.substr hl).coe_to_finset⟩, rwa [finset.lt_iff_ssubset, ← finset.coe_ssubset, set.finite.coe_to_finset, hm] at this, end /-- The subfunctor of `F` obtained by restricting to the eventual range at each index. -/ @[simps] def to_eventual_ranges : J ⥤ Type v := { obj := λ j, F.eventual_range j, map := λ i j f, (F.eventual_range_maps_to f).restrict _ _ _, map_id' := λ i, by { simp_rw F.map_id, ext, refl }, map_comp' := λ _ _ _ _ _, by { simp_rw F.map_comp, refl } } instance to_eventual_ranges_finite [∀ j, finite (F.obj j)] : ∀ j, finite (F.to_eventual_ranges.obj j) := λ j, subtype.finite /-- The sections of the functor `F : J ⥤ Type v` are in bijection with the sections of `F.eventual_ranges`. -/ def to_eventual_ranges_sections_equiv : F.to_eventual_ranges.sections ≃ F.sections := { to_fun := λ s, ⟨_, λ i j f, subtype.coe_inj.2 $ s.prop f⟩, inv_fun := λ s, ⟨λ j, ⟨_, mem_Inter₂.2 $ λ i f, ⟨_, s.prop f⟩⟩, λ i j f, subtype.ext $ s.prop f⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl } } /-- If `F` satisfies the Mittag-Leffler condition, its restriction to eventual ranges is a surjective functor. -/ lemma surjective_to_eventual_ranges (h : F.is_mittag_leffler) ⦃i j⦄ (f : i ⟶ j) : (F.to_eventual_ranges.map f).surjective := λ ⟨x, hx⟩, by { obtain ⟨y, hy, rfl⟩ := h.subset_image_eventual_range F f hx, exact ⟨⟨y, hy⟩, rfl⟩ } /-- If `F` is nonempty at each index and Mittag-Leffler, then so is `F.to_eventual_ranges`. -/ lemma to_eventual_ranges_nonempty (h : F.is_mittag_leffler) [∀ (j : J), nonempty (F.obj j)] (j : J) : nonempty (F.to_eventual_ranges.obj j) := let ⟨i, f, h⟩ := F.is_mittag_leffler_iff_eventual_range.1 h j in by { rw [to_eventual_ranges_obj, h], apply_instance } /-- If `F` has all arrows surjective, then it "factors through a poset". -/ lemma thin_diagram_of_surjective (Fsur : ∀ ⦃i j : J⦄ (f : i ⟶ j), (F.map f).surjective) {i j} (f g : i ⟶ j) : F.map f = F.map g := let ⟨k, φ, hφ⟩ := cone_maps f g in (Fsur φ).injective_comp_right $ by simp_rw [← types_comp, ← F.map_comp, hφ] lemma to_preimages_nonempty_of_surjective [hFn : ∀ (j : J), nonempty (F.obj j)] (Fsur : ∀ ⦃i j : J⦄ (f : i ⟶ j), (F.map f).surjective) (hs : s.nonempty) (j) : nonempty ((F.to_preimages s).obj j) := begin simp only [to_preimages_obj, nonempty_coe_sort, nonempty_Inter, mem_preimage], obtain (h|⟨⟨ji⟩⟩) := is_empty_or_nonempty (j ⟶ i), { exact ⟨(hFn j).some, λ ji, h.elim ji⟩, }, { obtain ⟨y, ys⟩ := hs, obtain ⟨x, rfl⟩ := Fsur ji y, exact ⟨x, λ ji', (F.thin_diagram_of_surjective Fsur ji' ji).symm ▸ ys⟩, }, end lemma eval_section_injective_of_eventually_injective {j} (Finj : ∀ i (f : i ⟶ j), (F.map f).injective) (i) (f : i ⟶ j) : (λ s : F.sections, s.val j).injective := begin refine λ s₀ s₁ h, subtype.ext $ funext $ λ k, _, obtain ⟨m, mi, mk, _⟩ := cone_objs i k, dsimp at h, rw [←s₀.prop (mi ≫ f), ←s₁.prop (mi ≫ f)] at h, rw [←s₀.prop mk, ←s₁.prop mk], refine congr_arg _ (Finj m (mi ≫ f) h), end section finite_cofiltered_system variables [∀ (j : J), nonempty (F.obj j)] [∀ (j : J), finite (F.obj j)] (Fsur : ∀ ⦃i j : J⦄ (f :i ⟶ j), (F.map f).surjective) include Fsur lemma eval_section_surjective_of_surjective (i : J) : (λ s : F.sections, s.val i).surjective := λ x, begin let s : set (F.obj i) := {x}, haveI := F.to_preimages_nonempty_of_surjective s Fsur (singleton_nonempty x), obtain ⟨sec, h⟩ := nonempty_sections_of_finite_cofiltered_system (F.to_preimages s), refine ⟨⟨λ j, (sec j).val, λ j k jk, by simpa [subtype.ext_iff] using h jk⟩, _⟩, { have := (sec i).prop, simp only [mem_Inter, mem_preimage, mem_singleton_iff] at this, replace this := this (𝟙 i), rwa [map_id_apply] at this, }, end lemma eventually_injective [nonempty J] [finite F.sections] : ∃ j, ∀ i (f : i ⟶ j), (F.map f).injective := begin haveI : ∀ j, fintype (F.obj j) := λ j, fintype.of_finite (F.obj j), haveI : fintype F.sections := fintype.of_finite F.sections, have card_le : ∀ j, fintype.card (F.obj j) ≤ fintype.card F.sections := λ j, fintype.card_le_of_surjective _ (F.eval_section_surjective_of_surjective Fsur j), let fn := λ j, fintype.card F.sections - fintype.card (F.obj j), refine ⟨fn.argmin nat.well_founded_lt.wf, λ i f, ((fintype.bijective_iff_surjective_and_card _).2 ⟨Fsur f, le_antisymm _ (fintype.card_le_of_surjective _ $ Fsur f)⟩).1⟩, rw [← nat.sub_sub_self (card_le i), tsub_le_iff_tsub_le], apply fn.argmin_le, end end finite_cofiltered_system end functor end category_theory
cad060213f1a5c81cd6f04e4550131d5cfdec66a
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/hofer.lean
3b890a10cb59828eb04e8ac90b898ad25de376cb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,605
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import analysis.specific_limits.basic /-! # Hofer's lemma This is an elementary lemma about complete metric spaces. It is motivated by an application to the bubbling-off analysis for holomorphic curves in symplectic topology. We are *very* far away from having these applications, but the proof here is a nice example of a proof needing to construct a sequence by induction in the middle of the proof. ## References: * H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres* -/ open_locale classical topological_space big_operators open filter finset local notation `d` := dist lemma hofer {X: Type*} [metric_space X] [complete_space X] (x : X) (ε : ℝ) (ε_pos : 0 < ε) {ϕ : X → ℝ} (cont : continuous ϕ) (nonneg : ∀ y, 0 ≤ ϕ y) : ∃ (ε' > 0) (x' : X), ε' ≤ ε ∧ d x' x ≤ 2*ε ∧ ε * ϕ(x) ≤ ε' * ϕ x' ∧ ∀ y, d x' y ≤ ε' → ϕ y ≤ 2*ϕ x' := begin by_contradiction H, have reformulation : ∀ x' (k : ℕ), ε * ϕ x ≤ ε / 2 ^ k * ϕ x' ↔ 2^k * ϕ x ≤ ϕ x', { intros x' k, rw [div_mul_eq_mul_div, le_div_iff, mul_assoc, mul_le_mul_left ε_pos, mul_comm], exact pow_pos (by norm_num) k, }, -- Now let's specialize to `ε/2^k` replace H : ∀ k : ℕ, ∀ x', d x' x ≤ 2 * ε ∧ 2^k * ϕ x ≤ ϕ x' → ∃ y, d x' y ≤ ε/2^k ∧ 2 * ϕ x' < ϕ y, { intros k x', push_neg at H, simpa [reformulation] using H (ε/2^k) (by simp [ε_pos, zero_lt_two]) x' (by simp [ε_pos, zero_lt_two, one_le_two]) }, clear reformulation, haveI : nonempty X := ⟨x⟩, choose! F hF using H, -- Use the axiom of choice -- Now define u by induction starting at x, with u_{n+1} = F(n, u_n) let u : ℕ → X := λ n, nat.rec_on n x F, have hu0 : u 0 = x := rfl, -- The properties of F translate to properties of u have hu : ∀ n, d (u n) x ≤ 2 * ε ∧ 2^n * ϕ x ≤ ϕ (u n) → d (u n) (u $ n + 1) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u $ n + 1), { intro n, exact hF n (u n) }, clear hF, -- Key properties of u, to be proven by induction have key : ∀ n, d (u n) (u (n + 1)) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u (n + 1)), { intro n, induction n using nat.case_strong_induction_on with n IH, { specialize hu 0, simpa [hu0, mul_nonneg_iff, zero_le_one, ε_pos.le, le_refl] using hu }, have A : d (u (n+1)) x ≤ 2 * ε, { rw [dist_comm], let r := range (n+1), -- range (n+1) = {0, ..., n} calc d (u 0) (u (n + 1)) ≤ ∑ i in r, d (u i) (u $ i+1) : dist_le_range_sum_dist u (n + 1) ... ≤ ∑ i in r, ε/2^i : sum_le_sum (λ i i_in, (IH i $ nat.lt_succ_iff.mp $ finset.mem_range.mp i_in).1) ... = ∑ i in r, (1/2)^i*ε : by { congr' with i, field_simp } ... = (∑ i in r, (1/2)^i)*ε : finset.sum_mul.symm ... ≤ 2*ε : mul_le_mul_of_nonneg_right (sum_geometric_two_le _) (le_of_lt ε_pos), }, have B : 2^(n+1) * ϕ x ≤ ϕ (u (n + 1)), { refine @geom_le (ϕ ∘ u) _ zero_le_two (n + 1) (λ m hm, _), exact (IH _ $ nat.lt_add_one_iff.1 hm).2.le }, exact hu (n+1) ⟨A, B⟩, }, cases forall_and_distrib.mp key with key₁ key₂, clear hu key, -- Hence u is Cauchy have cauchy_u : cauchy_seq u, { refine cauchy_seq_of_le_geometric _ ε one_half_lt_one (λ n, _), simpa only [one_div, inv_pow₀] using key₁ n }, -- So u converges to some y obtain ⟨y, limy⟩ : ∃ y, tendsto u at_top (𝓝 y), from complete_space.complete cauchy_u, -- And ϕ ∘ u goes to +∞ have lim_top : tendsto (ϕ ∘ u) at_top at_top, { let v := λ n, (ϕ ∘ u) (n+1), suffices : tendsto v at_top at_top, by rwa tendsto_add_at_top_iff_nat at this, have hv₀ : 0 < v 0, { have : 0 ≤ ϕ (u 0) := nonneg x, calc 0 ≤ 2 * ϕ (u 0) : by linarith ... < ϕ (u (0 + 1)) : key₂ 0 }, apply tendsto_at_top_of_geom_le hv₀ one_lt_two, exact λ n, (key₂ (n+1)).le }, -- But ϕ ∘ u also needs to go to ϕ(y) have lim : tendsto (ϕ ∘ u) at_top (𝓝 (ϕ y)), from tendsto.comp cont.continuous_at limy, -- So we have our contradiction! exact not_tendsto_at_top_of_tendsto_nhds lim lim_top, end
7c37de24c20fc6612084649a6d1a1afb00c2bd3b
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/ResolveName.lean
49ccfa400205a313a025114253ebeb825c2b8211
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,962
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.OpenDecl import Lean.Hygiene import Lean.Modifiers import Lean.Exception namespace Lean /-! We use aliases to implement the `export <id> (<id>+)` command. An `export A (x)` in the namespace `B` produces an alias `B.x ~> A.x`. -/ abbrev AliasState := SMap Name (List Name) abbrev AliasEntry := Name × Name def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState := match s.find? e.1 with | none => s.insert e.1 [e.2] | some es => if es.elem e.2 then s else s.insert e.1 (e.2 :: es) builtin_initialize aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState ← registerSimplePersistentEnvExtension { name := `aliasesExt, addEntryFn := addAliasEntry, addImportedFn := fun es => mkStateFromImportedEntries addAliasEntry {} es |>.switch } /- Add alias `a` for `e` -/ @[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) def getAliases (env : Environment) (a : Name) : List Name := match aliasExtension.getState env |>.find? a with | none => [] | some es => es -- slower, but only used in the pretty printer def getRevAliases (env : Environment) (e : Name) : List Name := (aliasExtension.getState env).fold (fun as a es => if List.contains es e then a :: as else as) [] /- Global name resolution -/ namespace ResolveName /- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id let resolvedIds := getAliases env resolvedId if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else -- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`. let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds else resolvedIds /- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(Name.str p _ _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace env id p | resolvedIds => resolvedIds | _ => [] /- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous if env.contains resolvedId then some resolvedId else -- We also allow `_root` when accessing private declarations. -- If we change our minds, we should just replace `resolvedId` with `id` let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then some resolvedIdPrv else none /- Check open namespaces -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.elem id then resolveOpenDecls env id openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id resolveOpenDecls env id openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if id == openedId then resolvedId :: resolvedIds else resolvedIds resolveOpenDecls env id openDecls resolvedIds def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else [] let idPrv := mkPrivateName env id let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds let resolvedIds := resolveOpenDecls env id openDecls resolvedIds let resolvedIds := getAliases env id ++ resolvedIds match resolvedIds with | _ :: _ => resolvedIds.eraseDups.map fun id => (id, projs) | [] => loop p (s::projs) | _, _ => [] loop extractionResult.name [] /- Namespace resolution -/ def resolveNamespaceUsingScope (env : Environment) (n : Name) : Name → Option Name | Name.anonymous => if env.isNamespace n then some n else none | ns@(Name.str p _ _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope env n p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → Option Name | [] => none | OpenDecl.simple ns [] :: ds => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingOpenDecls env n ds | _ :: ds => resolveNamespaceUsingOpenDecls env n ds /- Given a name `id` try to find namespace it refers to. The resolution procedure works as follows 1- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then return `s_1 . ... . s_i ++ n` if it is the name of an existing namespace. We search "backwards". 2- If `id` is the extact name of an existing namespace, then return `id` 3- Finally, for each command `open N`, return `N ++ n` if it is the name of an existing namespace. We search "backwards" again. That is, we try the most recent `open` command first. We only consider simple `open` commands. -/ def resolveNamespace? (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : Option Name := match resolveNamespaceUsingScope env id ns with | some n => some n | none => match resolveNamespaceUsingOpenDecls env id openDecls with | some n => some n | none => none end ResolveName class MonadResolveName (m : Type → Type) := (getCurrNamespace : m Name) (getOpenDecls : m (List OpenDecl)) export MonadResolveName (getCurrNamespace getOpenDecls) instance (m n) [MonadResolveName m] [MonadLift m n] : MonadResolveName n := { getCurrNamespace := liftM (getCurrNamespace : m _), getOpenDecls := liftM (getOpenDecls : m _) } section Methods variables {m : Type → Type} [Monad m] [MonadResolveName m] [MonadEnv m] /- Given a name `n`, return a list of possible interpretations. Each interpretation is a pair `(declName, fieldList)`, where `declName` is the name of a declaration in the current environment, and `fieldList` are (potential) field names. The pair is needed because in Lean `.` may be part of a qualified name or a field (aka dot-notation). As an example, consider the following definitions ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalName x` => `[(Foo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w])]` After `open Foo open Boo`, we have - `resolveGlobalName x` => `[(Foo.x, []), (Boo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w]), (Boo.x, [z, w])]` -/ def resolveGlobalName (id : Name) : m (List (Name × List String)) := do return ResolveName.resolveGlobalName (← getEnv) (← getCurrNamespace) (← getOpenDecls) id variables [MonadExceptOf Exception m] [MonadRef m] [AddErrorMessageContext m] def resolveNamespace (id : Name) : m Name := do match ResolveName.resolveNamespace? (← getEnv) (← getCurrNamespace) (← getOpenDecls) id with | some ns => return ns | none => throwError s!"unknown namespace '{id}'" /- Similar to `resolveGlobalName`, but discard any candidate whose `fieldList` is not empty. -/ def resolveGlobalConst (n : Name) : m (List Name) := do let cs ← resolveGlobalName n let cs := cs.filter fun (_, fieldList) => fieldList.isEmpty if cs.isEmpty then throwUnknownConstant n return cs.map (·.1) def resolveGlobalConstNoOverload (n : Name) : m Name := do let cs ← resolveGlobalConst n match cs with | [c] => pure c | _ => throwError s!"ambiguous identifier '{mkConst n}', possible interpretations: {cs.map mkConst}" end Methods end Lean
5ec6c9c671ac0b9a82bfcb4d17cc201799bb0e74
94e33a31faa76775069b071adea97e86e218a8ee
/archive/imo/imo1998_q2.lean
51a73ca85113b4b63f89a8ed698bb4afddd1c507
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
9,547
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.fintype.basic import data.int.parity import algebra.big_operators.order import tactic.ring import tactic.noncomm_ring /-! # IMO 1998 Q2 In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`. ## Solution The problem asks us to think about triples consisting of a contestant and two judges whose ratings agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J - {(j, j)}`. We have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`, and a lower bound from the count for `left`. These two bounds combine to the required result. First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2-b)`. Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size `(b-1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain the lower bound: `a(b-1)^2/2 ≤ |A|`. Rearranging gives the result. -/ open_locale classical noncomputable theory /-- An ordered pair of judges. -/ abbreviation judge_pair (J : Type*) := J × J /-- A triple consisting of contestant together with an ordered pair of judges. -/ abbreviation agreed_triple (C J : Type*) := C × (judge_pair J) variables {C J : Type*} (r : C → J → Prop) /-- The first judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst /-- The second judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd /-- The proposition that the judges in an ordered pair are distinct. -/ abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂ /-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/ abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂ /-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst /-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd @[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) : p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl /-- The set of contestants on which two judges agree. -/ def agreed_contestants [fintype C] (p : judge_pair J) : finset C := finset.univ.filter (λ c, p.agree r c) section variables [fintype J] [fintype C] /-- All incidences of agreement. -/ def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J), a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct) lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) : a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) := by simp [A, finset.mem_off_diag] lemma A_fibre_over_contestant (c : C) : finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd := begin ext p, simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop], split, { rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, }, { intros h, finish, }, end lemma A_fibre_over_contestant_card (c : C) : (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card := by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, } lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) : agreed_contestants r p = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant := begin dunfold A agreed_contestants, ext c, split; intros h, { rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, }, { finish, }, end lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) : (agreed_contestants r p).card = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card := by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, } lemma A_card_upper_bound {k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) := begin change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )), rw ← finset.off_diag_card, apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r), intros p hp, have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, }, rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp', end end lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) : (x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y := by noncomm_ring lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) : 2*z*z + 2*z + 1 ≤ x*x + y*y := begin suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y, { rw ← mul_le_mul_left (@zero_lt_two _ _ int.nontrivial), convert this; ring, }, have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, }, rw [← add_sq_add_sq_sub, h', add_le_add_iff_left], suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, }, rw [mul_self_pos, sub_ne_zero], apply int.ne_of_odd_add ⟨z, h⟩, end section variables [fintype J] lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card := begin let x := (finset.univ.filter (λ j, r c j)).card, let y := (finset.univ.filter (λ j, ¬ r c j)).card, have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y, { simp [← finset.filter_product_card], }, rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul], apply norm_bound_of_odd_sum, suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], }, rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl, end lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card := begin let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c), let t := finset.univ.filter (λ (p : judge_pair J), p.distinct), have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, }, have hst : s \ t = finset.univ.diag, { ext p, split; intros, { finish, }, { suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, }, have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, }, rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff], { rw hst', rw add_assoc at hs, apply le_tsub_of_add_le_right hs, }, { apply finset.sdiff_subset, }, end lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) : 2*z*z * (fintype.card C) ≤ (A r).card := begin have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, }, apply finset.mul_card_image_le_card_of_maps_to h, intros c hc, rw ← A_fibre_over_contestant_card, apply distinct_judge_pairs_card_lower_bound r hJ, end end local notation x `/` y := (x : ℚ) / y lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) : (b - 1) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) := by rw div_le_div_iff; norm_cast; simp [ha, hb] theorem imo1998_q2 [fintype J] [fintype C] (a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b) (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (b - 1) / (2 * b) ≤ k / a := begin rw clear_denominators ha hb.pos, obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz, have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk), rw [hC, hJ] at h, -- We are now essentially done; we just need to bash `h` into exactly the right shape. have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z, { simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, }, have hr : 2 * z * z * a = 2 * z * a * z, { ring, }, rw [hl, hr] at h, cases z, { simp, }, { exact le_of_mul_le_mul_right h z.succ_pos, }, end
23a919eee2abacdb7ed4122958c425e61c30d75d
618003631150032a5676f229d13a079ac875ff77
/src/topology/category/Top/opens.lean
96630bf1f97f397b682d4afb98f73ae30ae4f048
[ "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
3,866
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.category.Top.basic import category_theory.eq_to_hom open category_theory open topological_space open opposite universe u namespace topological_space.opens variables {X Y Z : Top.{u}} instance opens_category : category.{u} (opens X) := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans f.down.down g.down.down ⟩ ⟩ } def to_Top (X : Top.{u}) : opens X ⥤ Top := { obj := λ U, ⟨U.val, infer_instance⟩, map := λ U V i, ⟨λ x, ⟨x.1, i.down.down x.2⟩, (embedding.continuous_iff embedding_subtype_val).2 continuous_induced_dom⟩ } /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f.val ⁻¹' U.val, f.property _ U.property ⟩, map := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }. @[simp] lemma map_obj (f : X ⟶ Y) (U) (p) : (map f).obj ⟨U, p⟩ = ⟨ f.val ⁻¹' U, f.property _ p ⟩ := rfl @[simp] lemma map_id_obj (U : opens X) : (map (𝟙 X)).obj U = U := by { ext, refl } -- not quite `rfl`, since we don't have eta for records @[simp] lemma map_id_obj' (U) (p) : (map (𝟙 X)).obj ⟨U, p⟩ = ⟨U, p⟩ := rfl @[simp] lemma map_id_obj_unop (U : (opens X)ᵒᵖ) : (map (𝟙 X)).obj (unop U) = unop U := by simp @[simp] lemma op_map_id_obj (U : (opens X)ᵒᵖ) : (map (𝟙 X)).op.obj U = U := by simp section variable (X) def map_id : map (𝟙 X) ≅ 𝟭 (opens X) := { hom := { app := λ U, eq_to_hom (map_id_obj U) }, inv := { app := λ U, eq_to_hom (map_id_obj U).symm } } @[simp] lemma map_id_hom_app (U) : (map_id X).hom.app U = eq_to_hom (map_id_obj U) := rfl @[simp] lemma map_id_inv_app (U) : (map_id X).inv.app U = eq_to_hom (map_id_obj U).symm := rfl end @[simp] lemma map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj U = (map f).obj ((map g).obj U) := by { ext, refl } -- not quite `rfl`, since we don't have eta for records @[simp] lemma map_comp_obj' (f : X ⟶ Y) (g : Y ⟶ Z) (U) (p) : (map (f ≫ g)).obj ⟨U, p⟩ = (map f).obj ((map g).obj ⟨U, p⟩) := rfl @[simp] lemma map_comp_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) := by simp @[simp] lemma op_map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).op.obj U = (map f).op.obj ((map g).op.obj U) := by simp def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := { hom := { app := λ U, eq_to_hom (map_comp_obj f g U) }, inv := { app := λ U, eq_to_hom (map_comp_obj f g U).symm } } @[simp] lemma map_comp_hom_app (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map_comp f g).hom.app U = eq_to_hom (map_comp_obj f g U) := rfl @[simp] lemma map_comp_inv_app (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map_comp f g).inv.app U = eq_to_hom (map_comp_obj f g U).symm := rfl -- We could make f g implicit here, but it's nice to be able to see when -- they are the identity (often!) def map_iso (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg functor.obj (congr_arg map h)) U) ) (by obviously) @[simp] lemma map_iso_refl (f : X ⟶ Y) (h) : map_iso f f h = iso.refl (map _) := rfl @[simp] lemma map_iso_hom_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).hom.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h)) U) := rfl @[simp] lemma map_iso_inv_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).inv.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h.symm)) U) := rfl end topological_space.opens
60d9081260903514087a4cda02f70c7543078ace
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/algebra/category/yoneda.lean
7d1983b082e48bdb6d3f2549914a8d5e5a2c887a
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
336
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.category.yoneda Author: Floris van Doorn -/ import .constructions open eq eq.ops category functor category.ops prod namespace yoneda --representable functor section end end yoneda
925e672fe658ed5b0d6c5fcdb6a9b1a2422a585a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Basic.lean
ea963f66b328a0c388a1efbfb395bc32544304eb
[ "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
448
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.List.Basic import Init.Data.Char.Basic import Init.Data.String.Basic import Init.Data.Option.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Data.String.Extra
471638588e3f98848c2c6f21cb857ae5cf608825
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/uniform_space/cauchy.lean
35b7e46332053c6a6361b535086364e1ecbb42c2
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,007
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.uniform_space.basic import topology.bases import data.set.intervals /-! # Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ universes u v open filter topological_space set classical uniform_space open_locale classical uniformity topological_space filter variables {α : Type u} {β : Type v} [uniform_space α] /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := ne_bot f ∧ f ×ᶠ f ≤ (𝓤 α) /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def is_complete (s : set α) := ∀f, cauchy f → f ≤ 𝓟 s → ∃x∈s, f ≤ 𝓝 x lemma filter.has_basis.cauchy_iff {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {f : filter α} : cauchy f ↔ (ne_bot f ∧ (∀ i, p i → ∃ t ∈ f, ∀ x y ∈ t, (x, y) ∈ s i)) := and_congr iff.rfl $ (f.basis_sets.prod_self.le_basis_iff h).trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id] lemma cauchy_iff' {f : filter α} : cauchy f ↔ (ne_bot f ∧ (∀ s ∈ 𝓤 α, ∃t∈f, ∀ x y ∈ t, (x, y) ∈ s)) := (𝓤 α).basis_sets.cauchy_iff lemma cauchy_iff {f : filter α} : cauchy f ↔ (ne_bot f ∧ (∀ s ∈ 𝓤 α, ∃t∈f, (set.prod t t) ⊆ s)) := (𝓤 α).basis_sets.cauchy_iff.trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id] lemma cauchy_map_iff {l : filter β} {f : β → α} : cauchy (l.map f) ↔ (ne_bot l ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l ×ᶠ l) (𝓤 α)) := by rw [cauchy, map_ne_bot_iff, prod_map_map_eq, tendsto] lemma cauchy_map_iff' {l : filter β} [hl : ne_bot l] {f : β → α} : cauchy (l.map f) ↔ tendsto (λp:β×β, (f p.1, f p.2)) (l ×ᶠ l) (𝓤 α) := cauchy_map_iff.trans $ and_iff_right hl lemma cauchy.mono {f g : filter α} [hg : ne_bot g] (h_c : cauchy f) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy.mono' {f g : filter α} (h_c : cauchy f) (hg : ne_bot g) (h_le : g ≤ f) : cauchy g := h_c.mono h_le lemma cauchy_nhds {a : α} : cauchy (𝓝 a) := ⟨nhds_ne_bot, calc 𝓝 a ×ᶠ 𝓝 a = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ (𝓤 α).lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ 𝓤 α : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_nhds.mono (pure_le_nhds a) lemma filter.tendsto.cauchy_map {l : filter β} [ne_bot l] {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : cauchy (map f l) := cauchy_nhds.mono h /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ lemma le_nhds_of_cauchy_adhp_aux {f : filter α} {x : α} (adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, (set.prod t t ⊆ s) ∧ ∃ y, (x, y) ∈ s ∧ y ∈ t) : f ≤ 𝓝 x := begin -- Consider a neighborhood `s` of `x` assume s hs, -- Take an entourage twice smaller than `s` rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff_right.1 hs) with ⟨U, U_mem, hU⟩, -- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U` rcases adhs U U_mem with ⟨t, t_mem, ht, y, hxy, hy⟩, apply mem_sets_of_superset t_mem, -- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s` exact (λ z hz, hU (prod_mk_mem_comp_rel hxy (ht $ mk_mem_prod hy hz)) rfl) end /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : cluster_pt x f) : f ≤ 𝓝 x := le_nhds_of_cauchy_adhp_aux begin assume s hs, obtain ⟨t, t_mem, ht⟩ : ∃ t ∈ f, set.prod t t ⊆ s, from (cauchy_iff.1 hf).2 s hs, use [t, t_mem, ht], exact (forall_sets_nonempty_iff_ne_bot.2 adhs _ (inter_mem_inf_sets (mem_nhds_left x hs) t_mem )) end lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ 𝓝 x ↔ cluster_pt x f := ⟨assume h, cluster_pt.of_le_nhds' h hf.1, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy.map [uniform_space β] {f : filter α} {m : α → β} (hf : cauchy f) (hm : uniform_continuous m) : cauchy (map m f) := ⟨hf.1.map _, calc map m f ×ᶠ map m f = map (λp:α×α, (m p.1, m p.2)) (f ×ᶠ f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right ... ≤ 𝓤 β : hm⟩ lemma cauchy.comap [uniform_space β] {f : filter β} {m : α → β} (hf : cauchy f) (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) [ne_bot (comap m f)] : cauchy (comap m f) := ⟨‹_›, calc comap m f ×ᶠ comap m f = comap (λp:α×α, (m p.1, m p.2)) (f ×ᶠ f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right ... ≤ 𝓤 α : hm⟩ lemma cauchy.comap' [uniform_space β] {f : filter β} {m : α → β} (hf : cauchy f) (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (hb : ne_bot (comap m f)) : cauchy (comap m f) := hf.comap hm /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def cauchy_seq [semilattice_sup β] (u : β → α) := cauchy (at_top.map u) lemma cauchy_seq.mem_entourage {ι : Type*} [nonempty ι] [decidable_linear_order ι] {u : ι → α} (h : cauchy_seq u) {V : set (α × α)} (hV : V ∈ 𝓤 α) : ∃ k₀, ∀ i j, k₀ ≤ i → k₀ ≤ j → (u i, u j) ∈ V := begin have := h.right hV, obtain ⟨⟨i₀, j₀⟩, H⟩ : ∃ a, ∀ b : ι × ι, b ≥ a → prod.map u u b ∈ V, by rwa [prod_map_at_top_eq, mem_map, mem_at_top_sets] at this, refine ⟨max i₀ j₀, _⟩, intros i j hi hj, exact H (i, j) ⟨le_of_max_le_left hi, le_of_max_le_right hj⟩, end lemma filter.tendsto.cauchy_seq [semilattice_sup β] [nonempty β] {f : β → α} {x} (hx : tendsto f at_top (𝓝 x)) : cauchy_seq f := hx.cauchy_map lemma cauchy_seq_iff_tendsto [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (prod.map u u) at_top (𝓤 α) := cauchy_map_iff'.trans $ by simp only [prod_at_top_at_top_eq, prod.map_def] /-- If a Cauchy sequence has a convergent subsequence, then it converges. -/ lemma tendsto_nhds_of_cauchy_seq_of_subseq [semilattice_sup β] {u : β → α} (hu : cauchy_seq u) {ι : Type*} {f : ι → β} {p : filter ι} [ne_bot p] (hf : tendsto f p at_top) {a : α} (ha : tendsto (u ∘ f) p (𝓝 a)) : tendsto u at_top (𝓝 a) := le_nhds_of_cauchy_adhp hu (map_cluster_pt_of_comp hf ha) @[nolint ge_or_gt] -- see Note [nolint_ge] lemma filter.has_basis.cauchy_seq_iff {γ} [nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (h : (𝓤 α).has_basis p s) : cauchy_seq u ↔ ∀ i, p i → ∃N, ∀m n≥N, (u m, u n) ∈ s i := begin rw [cauchy_seq_iff_tendsto, ← prod_at_top_at_top_eq], refine (at_top_basis.prod_self.tendsto_iff h).trans _, simp only [exists_prop, true_and, maps_to, preimage, subset_def, prod.forall, mem_prod_eq, mem_set_of_eq, mem_Ici, and_imp, prod.map] end lemma filter.has_basis.cauchy_seq_iff' {γ} [nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (H : (𝓤 α).has_basis p s) : cauchy_seq u ↔ ∀ i, p i → ∃N, ∀n≥N, (u n, u N) ∈ s i := begin refine H.cauchy_seq_iff.trans ⟨λ h i hi, _, λ h i hi, _⟩, { exact (h i hi).imp (λ N hN n hn, hN n N hn (le_refl N)) }, { rcases comp_symm_of_uniformity (H.mem_of_mem hi) with ⟨t, ht, ht', hts⟩, rcases H.mem_iff.1 ht with ⟨j, hj, hjt⟩, refine (h j hj).imp (λ N hN m n hm hn, hts ⟨u N, hjt _, ht' $ hjt _⟩), { exact hN m hm }, { exact hN n hn } } end lemma cauchy_seq_of_controlled [semilattice_sup β] [nonempty β] (U : β → set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) {f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) : cauchy_seq f := cauchy_seq_iff_tendsto.2 begin assume s hs, rw [mem_map, mem_at_top_sets], cases hU s hs with N hN, refine ⟨(N, N), λ mn hmn, _⟩, cases mn with m n, exact hN (hf hmn.1 hmn.2) end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ 𝓝 x) lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] : is_complete (univ : set α) := begin assume f hf _, rcases complete_space.complete hf with ⟨x, hx⟩, exact ⟨x, mem_univ x, hx⟩ end lemma cauchy_prod [uniform_space β] {f : filter α} {g : filter β} : cauchy f → cauchy g → cauchy (f ×ᶠ g) | ⟨f_proper, hf⟩ ⟨g_proper, hg⟩ := ⟨filter.prod_ne_bot.2 ⟨f_proper, g_proper⟩, let p_α := λp:(α×β)×(α×β), (p.1.1, p.2.1), p_β := λp:(α×β)×(α×β), (p.1.2, p.2.2) in suffices (f.prod f).comap p_α ⊓ (g.prod g).comap p_β ≤ (𝓤 α).comap p_α ⊓ (𝓤 β).comap p_β, by simpa [uniformity_prod, filter.prod, filter.comap_inf, filter.comap_comap, (∘), inf_assoc, inf_comm, inf_left_comm], inf_le_inf (filter.comap_mono hf) (filter.comap_mono hg)⟩ instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ hf.map uniform_continuous_fst in let ⟨x2, hx2⟩ := complete_space.complete $ hf.map uniform_continuous_snd in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } /--If `univ` is complete, the space is a complete space -/ lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α := ⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩ lemma complete_space_iff_is_complete_univ : complete_space α ↔ is_complete (univ : set α) := ⟨@complete_univ α _, complete_space_of_is_complete_univ⟩ lemma cauchy_iff_exists_le_nhds [complete_space α] {l : filter α} [ne_bot l] : cauchy l ↔ (∃x, l ≤ 𝓝 x) := ⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_nhds.mono hx⟩ lemma cauchy_map_iff_exists_tendsto [complete_space α] {l : filter β} {f : β → α} [ne_bot l] : cauchy (l.map f) ↔ (∃x, tendsto f l (𝓝 x)) := cauchy_iff_exists_le_nhds /-- A Cauchy sequence in a complete space converges -/ theorem cauchy_seq_tendsto_of_complete [semilattice_sup β] [complete_space α] {u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (𝓝 x) := complete_space.complete H /-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/ lemma cauchy_seq_tendsto_of_is_complete [semilattice_sup β] {K : set α} (h₁ : is_complete K) {u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : cauchy_seq u) : ∃ v ∈ K, tendsto u at_top (𝓝 v) := h₁ _ h₃ $ le_principal_iff.2 $ mem_map_sets_iff.2 ⟨univ, univ_mem_sets, by { simp only [image_univ], rintros _ ⟨n, rfl⟩, exact h₂ n }⟩ theorem cauchy.le_nhds_Lim [complete_space α] [nonempty α] {f : filter α} (hf : cauchy f) : f ≤ 𝓝 (Lim f) := le_nhds_Lim (complete_space.complete hf) theorem cauchy_seq.tendsto_lim [semilattice_sup β] [complete_space α] [nonempty α] {u : β → α} (h : cauchy_seq u) : tendsto u at_top (𝓝 $ lim at_top u) := h.le_nhds_Lim lemma is_closed.is_complete [complete_space α] {s : set α} (h : is_closed s) : is_complete s := λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in ⟨x, is_closed_iff_cluster_pt.mp h x (ne_bot_of_le_ne_bot cf.left (le_inf hx fs)), hx⟩ /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ 𝓤 α, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ 𝓤 α, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := fk.subset (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, exact mem_bUnion_iff.2 ⟨_, ⟨z, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_of_forall_symm {s : set α} (h : ∀ V ∈ 𝓤 α, symmetric_rel V → ∃ t : set α, finite t ∧ s ⊆ ⋃ y ∈ t, ball y V) : totally_bounded s := begin intros V V_in, rcases h _ (symmetrize_mem_uniformity V_in) (symmetric_symmetrize_rel V) with ⟨t, tfin, h⟩, refine ⟨t, tfin, subset.trans h _⟩, mono, intros x x_in z z_in, exact z_in.right end lemma totally_bounded_subset {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_empty : totally_bounded (∅ : set α) := λ d hd, ⟨∅, finite_empty, empty_subset _⟩ /-- The closure of a totally bounded set is totally bounded. -/ lemma totally_bounded.closure {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : is_closed.closure_eq $ is_closed_bUnion hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ /-- The image of a totally bounded set under a unifromly continuous map is totally bounded. -/ lemma totally_bounded.image [uniform_space β] {f : α → β} {s : set α} (hs : totally_bounded s) (hf : uniform_continuous f) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, hfc.image f, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp, exact hct x hx end⟩ lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : is_ultrafilter f) (h : f ≤ 𝓟 s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (f ×ᶠ f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, ne_bot f → f ≤ 𝓟 s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of' hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, ne_bot f → f ≤ 𝓟 s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, 𝓟 (s \ (⋃y∈t.val, {x | (x,y) ∈ d})) in have ne_bot f, from infi_ne_bot_of_directed' (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, ht₁.union ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [ne_bot, diff_eq_empty]; exact hd_cover ht), have f ≤ 𝓟 s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ 𝓟 s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := hc₂.left.nonempty_of_mem this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ 𝓟 (s \ ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s \ ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, is_ultrafilter f → f ≤ 𝓟 s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of' hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_iff_totally_bounded_complete {s : set α} : is_compact s ↔ totally_bounded s ∧ is_complete s := ⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf1 hf2, let ⟨x, xs, fx⟩ := compact_iff_ultrafilter_le_nhds.1 hs f hf1 hf2 in cauchy_nhds.mono' hf1.1 fx), λ f fc fs, let ⟨a, as, fa⟩ := @hs f fc.1 fs in ⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩, λ ⟨ht, hc⟩, compact_iff_ultrafilter_le_nhds.2 (λf hf hfs, hc _ (totally_bounded_iff_ultrafilter.1 ht _ hf hfs) hfs)⟩ @[priority 100] -- see Note [lower instance priority] instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := ⟨λf hf, by simpa [principal_univ] using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : is_compact s := (@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, hc.is_complete⟩ /-! ### Sequentially complete space In this section we prove that a uniform space is complete provided that it is sequentially complete (i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set. In particular, this applies to (e)metric spaces, see the files `topology/metric_space/emetric_space` and `topology/metric_space/basic`. More precisely, we assume that there is a sequence of entourages `U_n` such that any other entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/ namespace sequentially_complete variables {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) open set finset noncomputable theory /-- An auxiliary sequence of sets approximating a Cauchy filter. -/ def set_seq_aux (n : ℕ) : {s : set α // ∃ (_ : s ∈ f), s.prod s ⊆ U n } := indefinite_description _ $ (cauchy_iff.1 hf).2 (U n) (U_mem n) /-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides a sequence of monotonically decreasing sets `s n ∈ f` such that `(s n).prod (s n) ⊆ U`. -/ def set_seq (n : ℕ) : set α := ⋂ m ∈ Iic n, (set_seq_aux hf U_mem m).val lemma set_seq_mem (n : ℕ) : set_seq hf U_mem n ∈ f := Inter_mem_sets (finite_le_nat n) (λ m _, (set_seq_aux hf U_mem m).2.fst) lemma set_seq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m := bInter_subset_bInter_left (λ k hk, le_trans hk h) lemma set_seq_sub_aux (n : ℕ) : set_seq hf U_mem n ⊆ set_seq_aux hf U_mem n := bInter_subset_of_mem right_mem_Iic lemma set_seq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) : (set_seq hf U_mem m).prod (set_seq hf U_mem n) ⊆ U N := begin assume p hp, refine (set_seq_aux hf U_mem N).2.snd ⟨_, _⟩; apply set_seq_sub_aux, exact set_seq_mono hf U_mem hm hp.1, exact set_seq_mono hf U_mem hn hp.2 end /-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is a monotonically decreasing sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence of entourages. -/ def seq (n : ℕ) : α := some $ hf.1.nonempty_of_mem (set_seq_mem hf U_mem n) lemma seq_mem (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n := some_spec $ hf.1.nonempty_of_mem (set_seq_mem hf U_mem n) lemma seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) : (seq hf U_mem m, seq hf U_mem n) ∈ U N := set_seq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩ include U_le theorem seq_is_cauchy_seq : cauchy_seq $ seq hf U_mem := cauchy_seq_of_controlled U U_le $ seq_pair_mem hf U_mem /-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/ theorem le_nhds_of_seq_tendsto_nhds ⦃a : α⦄ (ha : tendsto (seq hf U_mem) at_top (𝓝 a)) : f ≤ 𝓝 a := le_nhds_of_cauchy_adhp_aux begin assume s hs, rcases U_le s hs with ⟨m, hm⟩, rcases (tendsto_at_top' _ _).1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩, refine ⟨set_seq hf U_mem (max m n), set_seq_mem hf U_mem _, _, seq hf U_mem (max m n), _, seq_mem hf U_mem _⟩, { have := le_max_left m n, exact set.subset.trans (set_seq_prod_subset hf U_mem this this) hm }, { exact hm (hn _ $ le_max_right m n) } end end sequentially_complete namespace uniform_space open sequentially_complete variables (H : is_countably_generated (𝓤 α)) include H /-- A uniform space is complete provided that (a) its uniformity filter has a countable basis; (b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/ theorem complete_of_convergent_controlled_sequences (U : ℕ → set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α) (HU : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ a, tendsto u at_top (𝓝 a)) : complete_space α := begin rcases H.exists_antimono_seq' with ⟨U', U'_mono, hU'⟩, have Hmem : ∀ n, U n ∩ U' n ∈ 𝓤 α, from λ n, inter_mem_sets (U_mem n) (hU'.2 ⟨n, subset.refl _⟩), refine ⟨λ f hf, (HU (seq hf Hmem) (λ N m n hm hn, _)).imp $ le_nhds_of_seq_tendsto_nhds _ _ (λ s hs, _)⟩, { rcases (hU'.1 hs) with ⟨N, hN⟩, exact ⟨N, subset.trans (inter_subset_right _ _) hN⟩ }, { exact inter_subset_left _ _ (seq_pair_mem hf Hmem hm hn) } end /-- A sequentially complete uniform space with a countable basis of the uniformity filter is complete. -/ theorem complete_of_cauchy_seq_tendsto (H' : ∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) : complete_space α := let ⟨U', U'_mono, hU'⟩ := H.exists_antimono_seq' in complete_of_convergent_controlled_sequences H U' (λ n, hU'.2 ⟨n, subset.refl _⟩) (λ u hu, H' u $ cauchy_seq_of_controlled U' (λ s hs, hU'.1 hs) hu) protected lemma first_countable_topology : first_countable_topology α := ⟨λ a, by { rw nhds_eq_comap_uniformity, exact H.comap (prod.mk a) }⟩ /-- A separable uniform space with countably generated uniformity filter is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational "radii" from a countable open symmetric antimono basis of `𝓤 α`. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable [separable_space α] : second_countable_topology α := begin rcases exists_countable_dense α with ⟨s, hsc, hsd⟩, obtain ⟨t : ℕ → set (α × α), hto : ∀ (i : ℕ), t i ∈ (𝓤 α).sets ∧ is_open (t i) ∧ symmetric_rel (t i), h_basis : (𝓤 α).has_antimono_basis (λ _, true) t⟩ := H.exists_antimono_subbasis uniformity_has_basis_open_symmetric, refine ⟨⟨⋃ (x ∈ s), range (λ k, ball x (t k)), hsc.bUnion (λ x hx, countable_range _), _⟩⟩, refine (is_topological_basis_of_open_of_nhds _ _).2.2, { simp only [mem_bUnion_iff, mem_range], rintros _ ⟨x, hxs, k, rfl⟩, exact is_open_ball x (hto k).2.1 }, { intros x V hxV hVo, simp only [mem_bUnion_iff, mem_range, exists_prop], rcases uniform_space.mem_nhds_iff.1 (mem_nhds_sets hVo hxV) with ⟨U, hU, hUV⟩, rcases comp_symm_of_uniformity hU with ⟨U', hU', hsymm, hUU'⟩, rcases h_basis.to_has_basis.mem_iff.1 hU' with ⟨k, -, hk⟩, rcases hsd.inter_open_nonempty (ball x $ t k) (uniform_space.is_open_ball x (hto k).2.1) ⟨x, uniform_space.mem_ball_self _ (hto k).1⟩ with ⟨y, hxy, hys⟩, refine ⟨_, ⟨y, hys, k, rfl⟩, (hto k).2.2.subset hxy, λ z hz, _⟩, exact hUV (ball_subset_of_comp_subset (hk hxy) hUU' (hk hz)) } end end uniform_space
ae9256a94e8e349f6ad1c69eda3812ac0e6e91b5
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/removeSemiJoinRightWithFilter.lean
31d50bf172a073aee33a305e65c338a698cff17c
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,745
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int constant str_foo_: const int. theorem rule: forall ( Γ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (right⋅left⋅emp_ename) (FROM1 (product (table rel_emp) (product (table rel_dept) (table rel_emp))) WHERE (and (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno)))) (equal (uvariable (right⋅right⋅left⋅dept_name)) (constantExpr str_foo_))))) : SQL Γ _ ) = denoteSQL ((SELECT1 (right⋅left⋅emp_ename) (FROM1 (product (table rel_emp) (product ((SELECT * FROM1 (table rel_dept) WHERE (equal (uvariable (right⋅dept_name)) (constantExpr str_foo_)))) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno)))))) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, TDP' ucongr, end
ce685520bbdb377874df1a19f249cba3ad8d7117
4727251e0cd73359b15b664c3170e5d754078599
/src/combinatorics/simple_graph/hasse.lean
937d1e815c11836c8805d619f8bb6f3e06999784
[ "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
2,462
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 combinatorics.simple_graph.connectivity import data.fin.succ_pred import order.succ_pred.relation /-! # The Hasse diagram as a graph This file defines the Hasse diagram of an order (graph of `covby`, the covering relation) and the path graph on `n` vertices. ## Main declarations * `simple_graph.hasse`: Hasse diagram of an order. * `simple_graph.path_graph`: Path graph on `n` vertices. -/ open order order_dual relation namespace simple_graph variables (α β : Type*) section preorder variables [preorder α] [preorder β] /-- The Hasse diagram of an order as a simple graph. The graph of the covering relation. -/ def hasse : simple_graph α := { adj := λ a b, a ⋖ b ∨ b ⋖ a, symm := λ a b, or.symm, loopless := λ a h, h.elim (irrefl _) (irrefl _) } variables {α β} {a b : α} @[simp] lemma hasse_adj : (hasse α).adj a b ↔ a ⋖ b ∨ b ⋖ a := iff.rfl /-- `αᵒᵈ` and `α` have the same Hasse diagram. -/ def hasse_dual_iso : hasse αᵒᵈ ≃g hasse α := { map_rel_iff' := λ a b, by simp [or_comm], ..of_dual } @[simp] lemma hasse_dual_iso_apply (a : αᵒᵈ) : hasse_dual_iso a = of_dual a := rfl @[simp] lemma hasse_dual_iso_symm_apply (a : α) : hasse_dual_iso.symm a = to_dual a := rfl end preorder section linear_order variables [linear_order α] lemma hasse_preconnected_of_succ [succ_order α] [is_succ_archimedean α] : (hasse α).preconnected := λ a b, begin rw reachable_iff_refl_trans_gen, exact refl_trans_gen_of_succ _ (λ c hc, or.inl $ covby_succ_of_not_is_max hc.2.not_is_max) (λ c hc, or.inr $ covby_succ_of_not_is_max hc.2.not_is_max), end lemma hasse_preconnected_of_pred [pred_order α] [is_pred_archimedean α] : (hasse α).preconnected := λ a b, begin rw [reachable_iff_refl_trans_gen, ←refl_trans_gen_swap], exact refl_trans_gen_of_pred _ (λ c hc, or.inl $ pred_covby_of_not_is_min hc.1.not_is_min) (λ c hc, or.inr $ pred_covby_of_not_is_min hc.1.not_is_min), end end linear_order /-- The path graph on `n` vertices. -/ def path_graph (n : ℕ) : simple_graph (fin n) := hasse _ lemma path_graph_preconnected (n : ℕ) : (path_graph n).preconnected := hasse_preconnected_of_succ _ lemma path_graph_connected (n : ℕ) : (path_graph (n + 1)).connected := ⟨path_graph_preconnected _⟩ end simple_graph
d926abd5d1ad0c12fad30c5d06691e400d7fdb60
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/topology/algebra/monoid.lean
7c152b1988b2009ca4b10abcd86d0ae49f5a1119
[ "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
10,770
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.continuous_on import group_theory.submonoid.basic import algebra.group.prod import algebra.pointwise /-! # Theory of topological monoids In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ open classical set filter topological_space open_locale classical topological_space big_operators variables {α β M N : Type*} /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `α`, for example, is obtained by requiring both the instances `add_monoid α` and `has_continuous_add α`. -/ class has_continuous_add (M : Type*) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `α`, for example, is obtained by requiring both the instances `monoid α` and `has_continuous_mul α`. -/ @[to_additive] class has_continuous_mul (M : Type*) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[continuity, to_additive] lemma continuous.mul [topological_space α] {f : α → M} {g : α → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg : _) -- should `to_additive` be doing this? attribute [continuity] continuous.add @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul [topological_space α] {f : α → M} {g : α → M} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f : α → M} {g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds @[to_additive] lemma continuous_at.mul [topological_space α] {f : α → M} {g : α → M} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul [topological_space α] {f : α → M} {g : α → M} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk ((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩ @[priority 100, to_additive] instance has_continuous_mul_of_discrete_topology [topological_space N] [has_mul N] [discrete_topology N] : has_continuous_mul N := ⟨continuous_of_discrete_topology⟩ open_locale filter open function @[to_additive] lemma has_continuous_mul.of_nhds_one {M : Type*} [monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : has_continuous_mul M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ p : M × M, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : M × M), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, hleft x₀, hright y₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by { rw [key, ← filter.map_map], } ... ≤ map ((λ (x : M), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← hright, hleft y₀, filter.map_map, key₂, ← hleft] end⟩ @[to_additive] lemma has_continuous_mul_of_comm_of_nhds_one (M : Type*) [comm_monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : has_continuous_mul M := begin apply has_continuous_mul.of_nhds_one hmul hleft, intros x₀, simp_rw [mul_comm, hleft x₀] end end has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, mem_nhds_sets Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma tendsto_list_prod {f : β → α → M} {x : filter α} {a : β → M} : ∀l:list β, (∀c∈l, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod [topological_space α] {f : β → α → M} (l : list β) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x -- @[to_additive continuous_smul] @[continuity] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : M), a * a ^ k), from continuous_id.mul (continuous_pow _) @[continuity] lemma continuous.pow {f : α → M} [topological_space α] (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := continuous.comp (continuous_pow n) h end has_continuous_mul section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := mem_nhds_sets oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : multiset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : finset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[to_additive, continuity] lemma continuous_multiset_prod [topological_space α] {f : β → α → M} (s : multiset β) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } attribute [continuity] continuous_multiset_sum @[continuity, to_additive] lemma continuous_finset_prod [topological_space α] {f : β → α → M} (s : finset β) : (∀c∈s, continuous (f c)) → continuous (λa, ∏ c in s, f c a) := continuous_multiset_prod _ -- should `to_additive` be doing this? attribute [continuity] continuous_finset_sum end instance additive.has_continuous_add {M} [h : topological_space M] [has_mul M] [has_continuous_mul M] : @has_continuous_add (additive M) h _ := { continuous_add := @continuous_mul M _ _ _ } instance multiplicative.has_continuous_mul {M} [h : topological_space M] [has_add M] [has_continuous_add M] : @has_continuous_mul (multiplicative M) h _ := { continuous_mul := @continuous_add M _ _ _ }
ebd414c7f3e42a9e3dbc2f02c4995c7b271c2dbe
367134ba5a65885e863bdc4507601606690974c1
/src/testing/slim_check/functions.lean
25191f0761d5c45322dbce91226f84e335d23749
[ "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
16,958
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 data.list.sigma import testing.slim_check.sampleable import testing.slim_check.testable import tactic.pretty_cases /-! ## `slim_check`: generators for functions This file defines `sampleable` instances for `α → β` functions and `ℤ → ℤ` injective functions. Functions are generated by creating a list of pairs and one more value using the list as a lookup table and resorting to the additional value when a value is not found in the table. Injective functions are generated by creating a list of numbers and a permutation of that list. The permutation insures that every input is mapped to a unique output. When an input is not found in the list the input itself is used as an output. Injective functions `f : α → α` could be generated easily instead of `ℤ → ℤ` by generating a `list α`, removing duplicates and creating a permutations. One has to be careful when generating the domain to make if vast enough that, when generating arguments to apply `f` to, they argument should be likely to lie in the domain of `f`. This is the reason that injective functions `f : ℤ → ℤ` are generated by fixing the domain to the range `[-2*size .. -2*size]`, with `size` the size parameter of the `gen` monad. Much of the machinery provided in this file is applicable to generate injective functions of type `α → α` and new instances should be easy to define. Other classes of functions such as monotone functions can generated using similar techniques. For monotone functions, generating two lists, sorting them and matching them should suffice, with appropriate default values. Some care must be taken for shrinking such functions to make sure their defining property is invariant through shrinking. Injective functions are an example of how complicated it can get. -/ universes u v w namespace slim_check /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `with_default f y` encodes `x ↦ f x` when `x ∈ f` and `x ↦ y` otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `data.list.sigma`. -/ inductive total_function (α : Type u) (β : Type v) : Type (max u v) | with_default : list (Σ _ : α, β) → β → total_function instance total_function.inhabited {α β} [inhabited β] : inhabited (total_function α β) := ⟨ total_function.with_default ∅ (default _) ⟩ namespace total_function /-- Apply a total function to an argument. -/ def apply {α β : Type*} [decidable_eq α] : total_function α β → α → β | (total_function.with_default m y) x := (m.lookup x).get_or_else y /-- Implementation of `has_repr (total_function α β)`. Creates a string for a given `finmap` and output, `x₀ ↦ y₀, .. xₙ ↦ yₙ` for each of the entries. The brackets are provided by the calling function. -/ def repr_aux {α : Type u} [has_repr α] {β : Type v} [has_repr β] (m : list (Σ _ : α, β)) : string := string.join $ list.qsort (λ x y, x < y) (m.map $ λ x, sformat!"{repr $ sigma.fst x} ↦ {repr $ sigma.snd x}, ") /-- Produce a string for a given `total_function`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, _ ↦ y]`. -/ protected def repr {α : Type u} [has_repr α] {β : Type v} [has_repr β] : total_function α β → string | (total_function.with_default m y) := sformat!"[{repr_aux m}_ ↦ {has_repr.repr y}]" instance (α : Type u) (β : Type v) [has_repr α] [has_repr β] : has_repr (total_function α β) := ⟨ total_function.repr ⟩ /-- Create a `finmap` from a list of pairs. -/ def list.to_finmap' {α β} (xs : list (α × β)) : list (Σ _ : α, β) := xs.map prod.to_sigma section variables {α : Type u} {β : Type v} [sampleable α] [sampleable β] /-- Redefine `sizeof` to follow the structure of `sampleable` instances. -/ def total.sizeof : total_function α β → ℕ | ⟨m, x⟩ := 1 + @sizeof _ sampleable.wf m + sizeof x @[priority 2000] instance : has_sizeof (total_function α β) := ⟨ total.sizeof ⟩ variables [decidable_eq α] /-- Shrink a total function by shrinking the lists that represent it. -/ protected def shrink : shrink_fn (total_function α β) | ⟨m, x⟩ := (sampleable.shrink (m, x)).map $ λ ⟨⟨m', x'⟩, h⟩, ⟨⟨list.erase_dupkeys m', x'⟩, lt_of_le_of_lt (by unfold_wf; refine @list.sizeof_erase_dupkeys _ _ _ (@sampleable.wf _ _) _) h ⟩ variables [has_repr α] [has_repr β] instance pi.sampleable_ext : sampleable_ext (α → β) := { proxy_repr := total_function α β, interp := total_function.apply, sample := do { xs ← (sampleable.sample (list (α × β)) : gen ((list (α × β)))), ⟨x⟩ ← (uliftable.up $ sample β : gen (ulift.{(max u v)} β)), pure $ total_function.with_default (list.to_finmap' xs) x }, shrink := total_function.shrink } end section sampleable_ext open sampleable_ext @[priority 2000] instance pi_pred.sampleable_ext {α : Type u} [sampleable_ext (α → bool)] : sampleable_ext.{u+1} (α → Prop) := { proxy_repr := proxy_repr (α → bool), interp := λ m x, interp (α → bool) m x, sample := sample (α → bool), shrink := shrink } @[priority 2000] instance pi_uncurry.sampleable_ext {α : Type u} {β : Type v} {γ : Sort w} [sampleable_ext (α × β → γ)] : sampleable_ext.{(imax (u+1) (v+1) w)} (α → β → γ) := { proxy_repr := proxy_repr (α × β → γ), interp := λ m x y, interp (α × β → γ) m (x, y), sample := sample (α × β → γ), shrink := shrink } end sampleable_ext end total_function /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `map_to_self f` encodes `x ↦ f x` when `x ∈ f` and `x ↦ x`, i.e. `x` to itself, otherwise. We use `Σ` to encode mappings instead of `×` because we rely on the association list API defined in `data.list.sigma`. -/ inductive injective_function (α : Type u) : Type u | map_to_self (xs : list (Σ _ : α, α)) : xs.map sigma.fst ~ xs.map sigma.snd → list.nodup (xs.map sigma.snd) → injective_function instance {α} : inhabited (injective_function α) := ⟨ ⟨ [], list.perm.nil, list.nodup_nil ⟩ ⟩ namespace injective_function /-- Apply a total function to an argument. -/ def apply {α : Type u} [decidable_eq α] : injective_function α → α → α | (injective_function.map_to_self m _ _) x := (m.lookup x).get_or_else x /-- Produce a string for a given `total_function`. The output is of the form `[x₀ ↦ f x₀, .. xₙ ↦ f xₙ, x ↦ x]`. Unlike for `total_function`, the default value is not a constant but the identity function. -/ protected def repr {α : Type u} [has_repr α] : injective_function α → string | (injective_function.map_to_self m _ _) := sformat!"[{total_function.repr_aux m}x ↦ x]" instance (α : Type u) [has_repr α] : has_repr (injective_function α) := ⟨ injective_function.repr ⟩ /-- Interpret a list of pairs as a total function, defaulting to the identity function when no entries are found for a given function -/ def list.apply_id {α : Type u} [decidable_eq α] (xs : list (α × α)) (x : α) : α := ((xs.map prod.to_sigma).lookup x).get_or_else x @[simp] lemma list.apply_id_cons {α : Type u} [decidable_eq α] (xs : list (α × α)) (x y z : α) : list.apply_id ((y, z) :: xs) x = if y = x then z else list.apply_id xs x := by simp only [list.apply_id, list.lookup, eq_rec_constant, prod.to_sigma, list.map]; split_ifs; refl open function list prod (to_sigma) open nat lemma list.apply_id_zip_eq {α : Type u} [decidable_eq α] {xs ys : list α} (h₀ : list.nodup xs) (h₁ : xs.length = ys.length) (x y : α) (i : ℕ) (h₂ : xs.nth i = some x) : list.apply_id.{u} (xs.zip ys) x = y ↔ ys.nth i = some y := begin induction xs generalizing ys i, case list.nil : ys i h₁ h₂ { cases h₂ }, case list.cons : x' xs xs_ih ys i h₁ h₂ { cases i, { injection h₂ with h₀ h₁, subst h₀, cases ys, { cases h₁ }, { simp only [list.apply_id, to_sigma, option.get_or_else_some, nth, lookup_cons_eq, zip_cons_cons, list.map], } }, { cases ys, { cases h₁ }, { cases h₀ with _ _ h₀ h₁, simp only [nth, zip_cons_cons, list.apply_id_cons] at h₂ ⊢, rw if_neg, { apply xs_ih; solve_by_elim [succ.inj] }, { apply h₀, apply nth_mem h₂ } } } } end lemma apply_id_mem_iff {α : Type u} [decidable_eq α] {xs ys : list α} (h₀ : list.nodup xs) (h₁ : xs ~ ys) (x : α) : list.apply_id.{u} (xs.zip ys) x ∈ ys ↔ x ∈ xs := begin simp only [list.apply_id], cases h₃ : (lookup x (map prod.to_sigma (xs.zip ys))), { dsimp [option.get_or_else], rw h₁.mem_iff }, { have h₂ : ys.nodup := h₁.nodup_iff.1 h₀, replace h₁ : xs.length = ys.length := h₁.length_eq, dsimp, induction xs generalizing ys, case list.nil : ys h₃ h₂ h₁ { contradiction }, case list.cons : x' xs xs_ih ys h₃ h₂ h₁ { cases ys with y ys, { cases h₃ }, dsimp [lookup] at h₃, split_ifs at h₃, { subst x', subst val, simp only [mem_cons_iff, true_or, eq_self_iff_true], }, { cases h₀ with _ _ h₀ h₅, cases h₂ with _ _ h₂ h₄, have h₆ := nat.succ.inj h₁, specialize @xs_ih h₅ ys h₃ h₄ h₆, simp only [ne.symm h, xs_ih, mem_cons_iff, false_or], suffices : val ∈ ys, tauto!, erw [← option.mem_def, mem_lookup_iff] at h₃, simp only [to_sigma, mem_map, heq_iff_eq, prod.exists] at h₃, rcases h₃ with ⟨a, b, h₃, h₄, h₅⟩, subst a, subst b, apply (mem_zip h₃).2, simp only [nodupkeys, keys, comp, prod.fst_to_sigma, map_map], rwa map_fst_zip _ _ (le_of_eq h₆) } } } end lemma list.apply_id_eq_self {α : Type u} [decidable_eq α] {xs ys : list α} (x : α) : x ∉ xs → list.apply_id.{u} (xs.zip ys) x = x := begin intro h, dsimp [list.apply_id], rw lookup_eq_none.2, refl, simp only [keys, not_exists, to_sigma, exists_and_distrib_right, exists_eq_right, mem_map, comp_app, map_map, prod.exists], intros y hy, exact h (mem_zip hy).1, end lemma apply_id_injective {α : Type u} [decidable_eq α] {xs ys : list α} (h₀ : list.nodup xs) (h₁ : xs ~ ys) : injective.{u+1 u+1} (list.apply_id (xs.zip ys)) := begin intros x y h, by_cases hx : x ∈ xs; by_cases hy : y ∈ xs, { rw mem_iff_nth at hx hy, cases hx with i hx, cases hy with j hy, suffices : some x = some y, { injection this }, have h₂ := h₁.length_eq, rw [list.apply_id_zip_eq h₀ h₂ _ _ _ hx] at h, rw [← hx, ← hy], congr, apply nth_injective _ (h₁.nodup_iff.1 h₀), { symmetry, rw h, rw ← list.apply_id_zip_eq; assumption }, { rw ← h₁.length_eq, rw nth_eq_some at hx, cases hx with hx hx', exact hx } }, { rw ← apply_id_mem_iff h₀ h₁ at hx hy, rw h at hx, contradiction, }, { rw ← apply_id_mem_iff h₀ h₁ at hx hy, rw h at hx, contradiction, }, { rwa [list.apply_id_eq_self, list.apply_id_eq_self] at h; assumption }, end open total_function (list.to_finmap') open sampleable /-- Remove a slice of length `m` at index `n` in a list and a permutation, maintaining the property that it is a permutation. -/ def perm.slice {α} [decidable_eq α] (n m : ℕ) : (Σ' xs ys : list α, xs ~ ys ∧ ys.nodup) → (Σ' xs ys : list α, xs ~ ys ∧ ys.nodup) | ⟨xs, ys, h, h'⟩ := let xs' := list.slice n m xs in have h₀ : xs' ~ ys.inter xs', from perm.slice_inter _ _ h h', ⟨xs', ys.inter xs', h₀, nodup_inter_of_nodup _ h'⟩ /-- A lazy list, in decreasing order, of sizes that should be sliced off a list of length `n` -/ def slice_sizes : ℕ → lazy_list ℕ+ | n := if h : 0 < n then have n / 2 < n, from div_lt_self h dec_trivial, lazy_list.cons ⟨_, h⟩ (slice_sizes $ n / 2) else lazy_list.nil /-- Shrink a permutation of a list, slicing a segment in the middle. The sizes of the slice being removed start at `n` (with `n` the length of the list) and then `n / 2`, then `n / 4`, etc down to 1. The slices will be taken at index `0`, `n / k`, `2n / k`, `3n / k`, etc. -/ protected def shrink_perm {α} [decidable_eq α] [has_sizeof α] : shrink_fn (Σ' xs ys : list α, xs ~ ys ∧ ys.nodup) | xs := do let k := xs.1.length, n ← slice_sizes k, i ← lazy_list.of_list $ list.fin_range $ k / n, have ↑i * ↑n < xs.1.length, from nat.lt_of_div_lt_div (lt_of_le_of_lt (by simp only [nat.mul_div_cancel, gt_iff_lt, fin.val_eq_coe, pnat.pos]) i.2), pure ⟨perm.slice (i*n) n xs, by rcases xs with ⟨a,b,c,d⟩; dsimp [sizeof_lt]; unfold_wf; simp only [perm.slice]; unfold_wf; apply list.sizeof_slice_lt _ _ n.2 _ this⟩ instance {α} [has_sizeof α] : has_sizeof (injective_function α) := ⟨ λ ⟨xs,_,_⟩, sizeof (xs.map sigma.fst) ⟩ /-- Shrink an injective function slicing a segment in the middle of the domain and removing the corresponding elements in the codomain, hence maintaining the property that one is a permutation of the other. -/ protected def shrink {α} [has_sizeof α] [decidable_eq α] : shrink_fn (injective_function α) | ⟨xs, h₀, h₁⟩ := do ⟨⟨xs', ys', h₀, h₁⟩, h₂⟩ ← injective_function.shrink_perm ⟨_, _, h₀, h₁⟩, have h₃ : xs'.length ≤ ys'.length, from le_of_eq (perm.length_eq h₀), have h₄ : ys'.length ≤ xs'.length, from le_of_eq (perm.length_eq h₀.symm), pure ⟨⟨(list.zip xs' ys').map prod.to_sigma, by simp only [comp, map_fst_zip, map_snd_zip, *, prod.fst_to_sigma, prod.snd_to_sigma, map_map], by simp only [comp, map_snd_zip, *, prod.snd_to_sigma, map_map] ⟩, by revert h₂; dsimp [sizeof_lt]; unfold_wf; simp only [has_sizeof._match_1, map_map, comp, map_fst_zip, *, prod.fst_to_sigma]; unfold_wf; intro h₂; convert h₂ ⟩ /-- Create an injective function from one list and a permutation of that list. -/ protected def mk {α} (xs ys : list α) (h : xs ~ ys) (h' : ys.nodup) : injective_function α := have h₀ : xs.length ≤ ys.length, from le_of_eq h.length_eq, have h₁ : ys.length ≤ xs.length, from le_of_eq h.length_eq.symm, injective_function.map_to_self (list.to_finmap' (xs.zip ys)) (by { simp only [list.to_finmap', comp, map_fst_zip, map_snd_zip, *, prod.fst_to_sigma, prod.snd_to_sigma, map_map] }) (by { simp only [list.to_finmap', comp, map_snd_zip, *, prod.snd_to_sigma, map_map] }) protected lemma injective {α : Type u} [decidable_eq α] (f : injective_function α) : injective (apply f) := begin cases f with xs hperm hnodup, generalize h₀ : map sigma.fst xs = xs₀, generalize h₁ : xs.map (@id ((Σ _ : α, α) → α) $ @sigma.snd α (λ _ : α, α)) = xs₁, dsimp [id] at h₁, have hxs : xs = total_function.list.to_finmap' (xs₀.zip xs₁), { rw [← h₀, ← h₁, list.to_finmap'], clear h₀ h₁ xs₀ xs₁ hperm hnodup, induction xs, case list.nil { simp only [zip_nil_right, map_nil] }, case list.cons : xs_hd xs_tl xs_ih { simp only [true_and, to_sigma, eq_self_iff_true, sigma.eta, zip_cons_cons, list.map], exact xs_ih }, }, revert hperm hnodup, rw hxs, intros, apply apply_id_injective, { rwa [← h₀, hxs, hperm.nodup_iff], }, { rwa [← hxs, h₀, h₁] at hperm, }, end instance pi_injective.sampleable_ext : sampleable_ext { f : ℤ → ℤ // function.injective f } := { proxy_repr := injective_function ℤ, interp := λ f, ⟨ apply f, f.injective ⟩, sample := gen.sized $ λ sz, do { let xs' := int.range (-(2*sz+2)) (2*sz + 2), ys ← gen.permutation_of xs', have Hinj : injective (λ (r : ℕ), -(2*sz + 2 : ℤ) + ↑r), from λ x y h, int.coe_nat_inj (add_right_injective _ h), let r : injective_function ℤ := injective_function.mk.{0} xs' ys.1 ys.2 (ys.2.nodup_iff.1 $ nodup_map Hinj (nodup_range _)) in pure r }, shrink := @injective_function.shrink ℤ _ _ } end injective_function open function instance injective.testable {α β} (f : α → β) [I : testable (named_binder "x" $ ∀ x : α, named_binder "y" $ ∀ y : α, named_binder "H" $ f x = f y → x = y)] : testable (injective f) := I instance monotone.testable {α β} [preorder α] [preorder β] (f : α → β) [I : testable (named_binder "x" $ ∀ x : α, named_binder "y" $ ∀ y : α, named_binder "H" $ x ≤ y → f x ≤ f y)] : testable (monotone f) := I end slim_check
6f201ffc8607944e7c92286c36610e4e01cd1a1f
67190c9aacc0cac64fb4463d93e84c696a5be896
/Lists of exercises/List 4/fol.lean
9c7ae7ea526a3dd03b1a4a545cb0a811e5b2400f
[]
no_license
lucasresck/Discrete-Mathematics
ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738
0a08081c5f393e5765259d3f1253c3a6dd043dac
refs/heads/master
1,596,627,857,734
1,573,411,500,000
1,573,411,500,000
212,489,764
0
0
null
null
null
null
UTF-8
Lean
false
false
1,518
lean
/- (X) We agree with sharing this code with the classmates. Alunos: - Lucas Emanuel Resck Domingues - Lucas Machado Moschen Assume that we have a language with the following parameters: ∀, intended to mean “for all things”; N, intended to mean “is a number”; I , intended to mean “is interesting”; ; 'lt', intended to mean “is less than”; and 'z', a constant symbol intended to denote zero. Translate into this language the English sentences listed below. If the English sentence is ambiguous, you will need more than one translation. (a) Zero is less than any number. (b) If any number is interesting, then zero is interesting. (c) No number is less than zero. (d) Any uninteresting number with the property that all smaller numbers are interesting certainly is interesting. (e) There is no number such that all numbers are less than it. (f) There is no number such that no number is less than it. Complete o exercício criando as demais variáveis hb...hf. Se a frase for ambigua, use hX1, hX2... -/ constant U : Type constant N : U → Prop constant I : U → Prop constant lt : U → U → Prop constant z : U variable ha : ∀ x : U , N(x) → lt z x variable hb1 : (¬ ∀ x : U, ¬ (N(x) ∧ I(x))) → I(z) variable hb2 : (∀ x : U, N(x) ∧ I(x)) → I(z) variable hc : ∀ x : U, N(x) → ¬ lt x z variable hd : ∀ x : U, ¬ I(x) ∧ (∀ y : U, lt y x → I(y)) → I(x) variable he : ∀ x : U, ¬ (∀ y : U, lt y x) variable hf : ∀ x : U, ¬ (∀ y : U, ¬ lt y x)
570b7f5281e045743a7486e4c93c9a3772e1d58d
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/analysis/calculus/times_cont_diff.lean
195226f7af9f9bd905f5ebd7751f7e8d2ccbf315
[ "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
80,984
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.fderiv /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff 𝕜 n f` and `times_cont_diff_on 𝕜 n f s` saying that the function is `C^n`, respectively in the whole space or on the set `s`. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `times_cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `formal_multilinear_series 𝕜 E F`: a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `times_cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `times_cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `times_cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `times_cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. Also, there are locality problems in time: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and time in our definition of `times_cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical universes u v w open set fin open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ @[derive add_comm_group] def formal_multilinear_series (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] (F : Type*) [normed_group F] [normed_space 𝕜 F] := Π (n : ℕ), (E [×n]→L[𝕜] F) instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩ section module /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ local attribute [reducible] formal_multilinear_series instance : module 𝕜 (formal_multilinear_series 𝕜 E F) := begin letI : ∀ n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) := λ n, by apply_instance, apply_instance end end module namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) := λn, (p n.succ).curry_right /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) : formal_multilinear_series 𝕜 E F | 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z | (n + 1) := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F) (q n) /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) : p m v = p n w := by { cases h1, congr, funext i, cases i with i hi, exact h2 i hi hi } end formal_multilinear_series variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa continuous_linear_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, have : (m : with_top ℕ) = ((0 : ℕ) : with_bot ℕ) := le_antisymm hm bot_le, rw with_top.coe_eq_coe at this, rw this, have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, continuous_linear_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ⊤ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m (le_refl _) } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr, ext i, have : i = 0 := subsingleton.elim i 0, rw this, refl end lemma has_ftaylor_series_up_to_on.differentiable_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) (le_refl _)⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) s, rw continuous_linear_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa continuous_linear_equiv.comp_continuous_on_iff at this } } } end variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives within `s` up to order `n`, which are continuous. There is a subtlety on sets where derivatives are not unique, that choices of derivatives around different points might not match. To ensure that being `C^n` is a local property, we therefore require it locally around each point. There is another subtlety that one might be able to find nice derivatives up to `n` for any finite `n`, but that they don't match so that one can not find them up to infinity. To get a good notion for `n = ∞`, we only require that for any finite `n` we may find such matching derivatives. -/ definition times_cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∀ x ∈ s, ∃ u ∈ nhds_within x s, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma times_cont_diff_on_nat {n : ℕ} : times_cont_diff_on 𝕜 n f s ↔ ∀ x ∈ s, ∃ u ∈ nhds_within x s, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := begin refine ⟨λ H, H n (le_refl _), λ H m hm x hx, _⟩, rcases H x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp.of_le hm⟩ end lemma times_cont_diff_on_top : times_cont_diff_on 𝕜 ⊤ f s ↔ ∀ (n : ℕ), times_cont_diff_on 𝕜 n f s := begin split, { assume H n m hm x hx, rcases H m le_top x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp⟩ }, { assume H m hm x hx, rcases H m m (le_refl _) x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp⟩ } end lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) : continuous_on f s := begin apply continuous_on_of_locally_continuous_on (λ x hx, _), rcases h 0 bot_le x hx with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, refine ⟨t, t_open, xt, _⟩, rw inter_comm at tu, exact (H.mono tu).continuous_on end lemma times_cont_diff_on.congr {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s := begin assume m hm x hx, rcases h m hm x hx with ⟨u, hu, p, H⟩, refine ⟨u ∩ s, filter.inter_mem_sets hu self_mem_nhds_within, p, _⟩, exact (H.mono (inter_subset_left u s)).congr (λ x hx, h₁ x hx.2) end lemma times_cont_diff_on_congr {n : with_top ℕ} (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s ↔ times_cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma times_cont_diff_on.mono {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : times_cont_diff_on 𝕜 n f t := begin assume m hm x hx, rcases h m hm x (hst hx) with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_mono x hst hu, p, H⟩ end lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : times_cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : times_cont_diff_on 𝕜 m f s := begin assume k hk x hx, rcases h k (le_trans hk hmn) x hx with ⟨u, hu, p, H⟩, exact ⟨u, hu, p, H⟩ end /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma times_cont_diff_on.differentiable_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := begin apply differentiable_on_of_locally_differentiable_on (λ x hx, _), rcases h 1 hn x hx with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, exact ⟨t, t_open, xt, (H.mono tu).differentiable_on (le_refl _)⟩ end /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) : times_cont_diff_on 𝕜 n f s := begin assume m hm x hx, rcases h x hx with ⟨u, u_open, xu, Hu⟩, rcases Hu m hm x ⟨hx, xu⟩ with ⟨v, hv, p, H⟩, rw ← nhds_within_restrict s xu u_open at hv, exact ⟨v, hv, p, H⟩, end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ nhds_within x s, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases h n.succ (le_refl _) x hx with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume m hm z hz, exact ⟨u, self_mem_nhds_within, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩ }, { assume h, rw times_cont_diff_on_nat, assume x hx, rcases h x hx with ⟨u, hu, f', f'_eq_deriv, Hf'⟩, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, rcases Hf' n (le_refl _) x xu with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, filter.inter_mem_sets (nhds_within_le_of_mem hu hv) hu, λ x, (p' x).unshift (f x), _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ (z : E), (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, continuous_linear_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F), have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw continuous_linear_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (mem_nhds_sets hu hx.2) ((unique_diff_within_at_inter (mem_nhds_sets hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ nhds_within x s) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ nhds x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume m hm x hx, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨H, λ x hx, by simp [ftaylor_series_within]⟩ end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on.ftaylor_series_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases h m.succ (with_top.add_one_le_of_lt hm) x hx with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (mem_nhds_sets o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h m hm x hx with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m (le_refl _)).congr (λ y hy, (A y hy).symm) } end lemma times_cont_diff_on_of_continuous_on_differentiable_on {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : times_cont_diff_on 𝕜 n f s := begin assume m hm x hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk x hx, convert (Hdiff k (lt_of_lt_of_le hk hm) x hx).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma times_cont_diff_on_of_differentiable_on {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : times_cont_diff_on 𝕜 n f s := times_cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma times_cont_diff_on.continuous_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma times_cont_diff_on.differentiable_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma times_cont_diff_on_iff_continuous_on_differentiable_on {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact times_cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume H, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), _⟩, apply times_cont_diff_on_of_locally_times_cont_diff_on, assume x hx, rcases times_cont_diff_on_succ_iff_has_fderiv_within_at.1 H x hx with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, apply (hf'.mono ho).congr (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (mem_nhds_sets o_open hy.2) (hs y hy.1) at A }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at, rintros ⟨hdiff, h⟩ x hx, exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ x hx, (hdiff x hx).has_fderiv_within_at, h⟩ } end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ⊤ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ⊤ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ⊤ := le_top, apply ((times_cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end lemma times_cont_diff_on.fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ⊤ + 1 ≤ n at hmn, have : n = ⊤, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff {n : with_top ℕ} : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm, -add_comm, -with_bot.coe_add] variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition times_cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ m hm x hx, exact ⟨univ, self_mem_nhds_within, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma times_cont_diff_top : times_cont_diff 𝕜 ⊤ f ↔ ∀ (n : ℕ), times_cont_diff 𝕜 n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_top] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_on 𝕜 n f s := (times_cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma times_cont_diff_zero : times_cont_diff 𝕜 0 f ↔ continuous f := begin rw [← times_cont_diff_on_univ, continuous_iff_continuous_on_univ], exact times_cont_diff_on_zero end lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hmn : m ≤ n) : times_cont_diff 𝕜 m f := times_cont_diff_on_univ.1 $ (times_cont_diff_on_univ.2 h).of_le hmn lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : continuous f := times_cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma times_cont_diff.differentiable {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (times_cont_diff_on_univ.2 h).differentiable_on hn variable (𝕜) /-! ### Iterated derivative -/ /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on_iff_ftaylor_series {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← times_cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, times_cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma times_cont_diff_iff_continuous_differentiable {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [times_cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, times_cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma times_cont_diff_of_differentiable_iterated_fderiv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_fderiv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ, times_cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ, -with_bot.coe_add, -add_comm] /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_top_iff_fderiv : times_cont_diff 𝕜 ⊤ f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 ⊤ (λ y, fderiv 𝕜 f y) := begin simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw times_cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((times_cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma times_cont_diff_zero_fun {n : with_top ℕ} : times_cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply times_cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) := begin suffices h : times_cont_diff 𝕜 ⊤ (λx : E, c), by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact times_cont_diff_zero_fun end lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} : times_cont_diff_on 𝕜 n (λx : E, c) s := times_cont_diff_const.times_cont_diff_on /-! ### Linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) : times_cont_diff 𝕜 n f := begin suffices h : times_cont_diff 𝕜 ⊤ f, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const end lemma continuous_linear_map.times_cont_diff {n : with_top ℕ} (f : E →L[𝕜] F) : times_cont_diff 𝕜 n f := f.is_bounded_linear_map.times_cont_diff /-- The first projection in a product is `C^∞`. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The second projection in a product is `C^∞`. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The identity is `C^∞`. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.times_cont_diff /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) : times_cont_diff 𝕜 n b := begin suffices h : times_cont_diff 𝕜 ⊤ b, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin split, { assume x hx, simp [(hf.zero_eq x hx).symm] }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, have := hf.fderiv_within m hm x hx, convert has_fderiv_at.comp_has_fderiv_within_at x (hA.has_fderiv_at) this }, { assume m hm, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, exact hA.continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin assume m hm x hx, rcases hf m hm x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma times_cont_diff.continuous_linear_map_comp {n : with_top ℕ} {f : E → F} (g : F →L[𝕜] G) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.continuous_linear_map_comp _ (times_cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_on_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_on 𝕜 n (e ∘ f) s ↔ times_cont_diff_on 𝕜 n f s := begin split, { assume H, have : f = e.symm ∘ (e ∘ f), by { ext y, simp only [function.comp_app], rw e.symm_apply_apply (f y) }, rw this, exact H.continuous_linear_map_comp _ }, { assume H, exact H.continuous_linear_map_comp _ } end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map 𝕜 E g) (g ⁻¹' s) := begin split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ h, h.comp_continuous_linear_map 𝕜 E g, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_continuous_multilinear_map_comp_linear g, convert (hA.has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, let A : (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ h, h.comp_continuous_linear_map 𝕜 E g, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_continuous_multilinear_map_comp_linear g, exact hA.continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_continuous_linear_map {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := begin assume m hm x hx, rcases hf m hm (g x) hx with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { exact nhds_within_mono (g x) (image_preimage_subset g s) hu } end /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma times_cont_diff.comp_continuous_linear_map {n : with_top ℕ} {f : E → F} {g : G →L[𝕜] E} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (f ∘ g) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_continuous_linear_map (times_cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.times_cont_diff_on_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ times_cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map _⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _ end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, convert hA.has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, exact hA.continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s := begin assume m hm x hx, rcases hf m hm x hx with ⟨u, hu, p, hp⟩, rcases hg m hm x hx with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem_sets hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `times_cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma times_cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {n : with_top ℕ} {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezeI, induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (times_cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ nhds_within x s, { apply filter.inter_mem_sets self_mem_nhds_within, apply filter.inter_mem_sets hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { exact nhds_within_mono _ (image_subset_iff.2 st) hv } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show times_cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : times_cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : times_cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : times_cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w := times_cont_diff_on.prod B A, have D : times_cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on, exact IH D C (subset_univ _) } }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. The instances are not found automatically by Lean, so we declare them by hand. TODO: fix. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := @continuous_multilinear_map.to_normed_group 𝕜 (fin 0) (λ (i : fin 0), E × F × G) E _ _ _ _ _ _ _, letI : normed_space 𝕜 Eu := @continuous_multilinear_map.to_normed_space 𝕜 (fin 0) (λ (i : fin 0), E × F × G) E _ _ _ _ _ _ _, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := @continuous_multilinear_map.to_normed_group 𝕜 (fin 0) (λ (i : fin 0), E × F × G) F _ _ _ _ _ _ _, letI : normed_space 𝕜 Fu := @continuous_multilinear_map.to_normed_space 𝕜 (fin 0) (λ (i : fin 0), E × F × G) F _ _ _ _ _ _ _, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := @continuous_multilinear_map.to_normed_group 𝕜 (fin 0) (λ (i : fin 0), E × F × G) G _ _ _ _ _ _ _, letI : normed_space 𝕜 Gu := @continuous_multilinear_map.to_normed_space 𝕜 (fin 0) (λ (i : fin 0), E × F × G) G _ _ _ _ _ _ _, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : times_cont_diff_on 𝕜 n fu (isoE ⁻¹' s) := by rwa [isoE.times_cont_diff_on_comp_iff, isoF.symm.comp_times_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : times_cont_diff_on 𝕜 n gu (isoF ⁻¹' t) := by rwa [isoF.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff], have main : times_cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply times_cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff] at main end /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := (times_cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) (subset_univ _) /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (set.prod s (univ : set E)) := begin have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _, { have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply times_cont_diff.times_cont_diff_on _ , apply is_bounded_linear_map.snd.times_cont_diff } }, exact A.comp_times_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-- The sum of two `C^n`functions on a domain is `C^n`. -/ lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x + g x) s := begin have : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd }, exact this.comp_times_cont_diff_on (hf.prod hg) end /-- The sum of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x + g x) := begin have : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd }, exact this.comp (hf.prod hg) end /-- The negative of a `C^n`function on a domain is `C^n`. -/ lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λx, -f x) s := begin have : times_cont_diff 𝕜 n (λp : F, -p), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.neg is_bounded_linear_map.id }, exact this.comp_times_cont_diff_on hf end /-- The negative of a `C^n`function is `C^n`. -/ lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, -f x) := begin have : times_cont_diff 𝕜 n (λp : F, -p), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.neg is_bounded_linear_map.id }, exact this.comp hf end /-- The difference of two `C^n`functions on a domain is `C^n`. -/ lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x - g x) s := hf.add (hg.neg) /-- The difference of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) := hf.add hg.neg
8b275313bdfc828c719b2a16cee5ec1d33bbab2a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/polynomial/homogeneous.lean
bbab5e81fb9e2c94f4bc4d1ca0d1ddca72ba9295
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
10,892
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Eric Wieser -/ import algebra.direct_sum.internal import algebra.graded_monoid import data.fintype.card import data.mv_polynomial.variables /-! # Homogeneous polynomials A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_submodule σ R n`: the submodule of homogeneous polynomials of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ open_locale big_operators namespace mv_polynomial variables {σ : Type*} {τ : Type*} {R : Type*} {S : Type*} /- TODO * create definition for `∑ i in d.support, d i` * show that `mv_polynomial σ R ≃ₐ[R] ⨁ i, homogeneous_submodule σ R i` -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ ⦃d⦄, coeff d φ ≠ 0 → ∑ i in d.support, d i = n variables (σ R) /-- The submodule of homogeneous `mv_polynomial`s of degree `n`. -/ def homogeneous_submodule [comm_semiring R] (n : ℕ) : submodule R (mv_polynomial σ R) := { carrier := { x | x.is_homogeneous n }, smul_mem' := λ r a ha c hc, begin rw coeff_smul at hc, apply ha, intro h, apply hc, rw h, exact smul_zero r, end, zero_mem' := λ d hd, false.elim (hd $ coeff_zero _), add_mem' := λ a b ha hb c hc, begin rw coeff_add at hc, obtain h|h : coeff c a ≠ 0 ∨ coeff c b ≠ 0, { contrapose! hc, simp only [hc, add_zero] }, { exact ha h }, { exact hb h } end } variables {σ R} @[simp] lemma mem_homogeneous_submodule [comm_semiring R] (n : ℕ) (p : mv_polynomial σ R) : p ∈ homogeneous_submodule σ R n ↔ p.is_homogeneous n := iff.rfl variables (σ R) /-- While equal, the former has a convenient definitional reduction. -/ lemma homogeneous_submodule_eq_finsupp_supported [comm_semiring R] (n : ℕ) : homogeneous_submodule σ R n = finsupp.supported _ R {d | ∑ i in d.support, d i = n} := begin ext, rw [finsupp.mem_supported, set.subset_def], simp only [finsupp.mem_support_iff, finset.mem_coe], refl, end variables {σ R} lemma homogeneous_submodule_mul [comm_semiring R] (m n : ℕ) : homogeneous_submodule σ R m * homogeneous_submodule σ R n ≤ homogeneous_submodule σ R (m + n) := begin rw submodule.mul_le, intros φ hφ ψ hψ c hc, rw [coeff_mul] at hc, obtain ⟨⟨d, e⟩, hde, H⟩ := finset.exists_ne_zero_of_sum_ne_zero hc, have aux : coeff d φ ≠ 0 ∧ coeff e ψ ≠ 0, { contrapose! H, by_cases h : coeff d φ = 0; simp only [*, ne.def, not_false_iff, zero_mul, mul_zero] at * }, specialize hφ aux.1, specialize hψ aux.2, rw finsupp.mem_antidiagonal at hde, classical, have hd' : d.support ⊆ d.support ∪ e.support := finset.subset_union_left _ _, have he' : e.support ⊆ d.support ∪ e.support := finset.subset_union_right _ _, rw [← hde, ← hφ, ← hψ, finset.sum_subset (finsupp.support_add), finset.sum_subset hd', finset.sum_subset he', ← finset.sum_add_distrib], { congr }, all_goals { intros i hi, apply finsupp.not_mem_support_iff.mp }, end section variables [comm_semiring R] variables {σ R} lemma is_homogeneous_monomial (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : ∑ i in d.support, d i = n) : is_homogeneous (monomial d r) n := begin intros c hc, classical, rw coeff_monomial at hc, split_ifs at hc with h, { subst c, exact hn }, { contradiction } end variables (σ) {R} lemma is_homogeneous_of_total_degree_zero {p : mv_polynomial σ R} (hp : p.total_degree = 0) : is_homogeneous p 0 := begin erw [total_degree, finset.sup_eq_bot_iff] at hp, -- we have to do this in two steps to stop simp changing bot to zero simp_rw [mem_support_iff] at hp, exact hp, end lemma is_homogeneous_C (r : R) : is_homogeneous (C r : mv_polynomial σ R) 0 := begin apply is_homogeneous_monomial, simp only [finsupp.zero_apply, finset.sum_const_zero], end variables (σ R) lemma is_homogeneous_zero (n : ℕ) : is_homogeneous (0 : mv_polynomial σ R) n := (homogeneous_submodule σ R n).zero_mem lemma is_homogeneous_one : is_homogeneous (1 : mv_polynomial σ R) 0 := is_homogeneous_C _ _ variables {σ} (R) lemma is_homogeneous_X (i : σ) : is_homogeneous (X i : mv_polynomial σ R) 1 := begin apply is_homogeneous_monomial, simp only [finsupp.support_single_ne_zero _ one_ne_zero, finset.sum_singleton], exact finsupp.single_eq_same end end namespace is_homogeneous variables [comm_semiring R] {φ ψ : mv_polynomial σ R} {m n : ℕ} lemma coeff_eq_zero (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : ∑ i in d.support, d i ≠ n) : coeff d φ = 0 := by { have aux := mt (@hφ d) hd, classical, rwa not_not at aux } lemma inj_right (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := begin obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero hφ, rw [← hm hd, ← hn hd] end lemma add (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := (homogeneous_submodule σ R n).add_mem hφ hψ lemma sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) n) : is_homogeneous (∑ i in s, φ i) n := (homogeneous_submodule σ R n).sum_mem h lemma mul (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := homogeneous_submodule_mul m n $ submodule.mul_mem_mul hφ hψ lemma prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) (n i)) : is_homogeneous (∏ i in s, φ i) (∑ i in s, n i) := begin classical, revert h, apply finset.induction_on s, { intro, simp only [is_homogeneous_one, finset.sum_empty, finset.prod_empty] }, { intros i s his IH h, simp only [his, finset.prod_insert, finset.sum_insert, not_false_iff], apply (h i (finset.mem_insert_self _ _)).mul (IH _), intros j hjs, exact h j (finset.mem_insert_of_mem hjs) } end lemma total_degree (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := begin rw total_degree, apply le_antisymm, { apply finset.sup_le, intros d hd, rw mem_support_iff at hd, rw [finsupp.sum, hφ hd], }, { obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero h, simp only [← hφ hd, finsupp.sum], replace hd := finsupp.mem_support_iff.mpr hd, exact finset.le_sup hd, } end /-- The homogeneous submodules form a graded ring. This instance is used by `direct_sum.comm_semiring` and `direct_sum.algebra`. -/ instance homogeneous_submodule.gcomm_semiring : set_like.graded_monoid (homogeneous_submodule σ R) := { one_mem := is_homogeneous_one σ R, mul_mem := λ i j xi xj, is_homogeneous.mul} open_locale direct_sum noncomputable example : comm_semiring (⨁ i, homogeneous_submodule σ R i) := infer_instance noncomputable example : algebra R (⨁ i, homogeneous_submodule σ R i) := infer_instance end is_homogeneous section noncomputable theory open_locale classical open finset /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component [comm_semiring R] (n : ℕ) : mv_polynomial σ R →ₗ[R] mv_polynomial σ R := (submodule.subtype _).comp $ finsupp.restrict_dom _ _ {d | ∑ i in d.support, d i = n} section homogeneous_component open finset variables [comm_semiring R] (n : ℕ) (φ ψ : mv_polynomial σ R) lemma coeff_homogeneous_component (d : σ →₀ ℕ) : coeff d (homogeneous_component n φ) = if ∑ i in d.support, d i = n then coeff d φ else 0 := by convert finsupp.filter_apply (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ d lemma homogeneous_component_apply : homogeneous_component n φ = ∑ d in φ.support.filter (λ d, ∑ i in d.support, d i = n), monomial d (coeff d φ) := by convert finsupp.filter_eq_sum (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ lemma homogeneous_component_is_homogeneous : (homogeneous_component n φ).is_homogeneous n := begin intros d hd, contrapose! hd, rw [coeff_homogeneous_component, if_neg hd] end @[simp] lemma homogeneous_component_zero : homogeneous_component 0 φ = C (coeff 0 φ) := begin ext1 d, rcases em (d = 0) with (rfl|hd), { simp only [coeff_homogeneous_component, sum_eq_zero_iff, finsupp.zero_apply, if_true, coeff_C, eq_self_iff_true, forall_true_iff] }, { rw [coeff_homogeneous_component, if_neg, coeff_C, if_neg (ne.symm hd)], simp only [finsupp.ext_iff, finsupp.zero_apply] at hd, simp [hd] } end @[simp] lemma homogeneous_component_C_mul (n : ℕ) (r : R) : homogeneous_component n (C r * φ) = C r * homogeneous_component n φ := by simp only [C_mul', linear_map.map_smul] lemma homogeneous_component_eq_zero' (h : ∀ d : σ →₀ ℕ, d ∈ φ.support → ∑ i in d.support, d i ≠ n) : homogeneous_component n φ = 0 := begin rw [homogeneous_component_apply, sum_eq_zero], intros d hd, rw mem_filter at hd, exfalso, exact h _ hd.1 hd.2 end lemma homogeneous_component_eq_zero (h : φ.total_degree < n) : homogeneous_component n φ = 0 := begin apply homogeneous_component_eq_zero', rw [total_degree, finset.sup_lt_iff] at h, { intros d hd, exact ne_of_lt (h d hd), }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma sum_homogeneous_component : ∑ i in range (φ.total_degree + 1), homogeneous_component i φ = φ := begin ext1 d, suffices : φ.total_degree < d.support.sum d → 0 = coeff d φ, by simpa [coeff_sum, coeff_homogeneous_component], exact λ h, (coeff_eq_zero_of_total_degree_lt h).symm end lemma homogeneous_component_homogeneous_polynomial (m n : ℕ) (p : mv_polynomial σ R) (h : p ∈ homogeneous_submodule σ R n) : homogeneous_component m p = if m = n then p else 0 := begin simp only [mem_homogeneous_submodule] at h, ext x, rw coeff_homogeneous_component, by_cases zero_coeff : coeff x p = 0, { split_ifs, all_goals { simp only [zero_coeff, coeff_zero], }, }, { rw h zero_coeff, simp only [show n = m ↔ m = n, from eq_comm], split_ifs with h1, { refl }, { simp only [coeff_zero] } } end end homogeneous_component end end mv_polynomial
44320438a1d5e90bed7de628cd6205b6c3c5cd8f
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/server/edits.lean
a215e5d3e8b59dabf06d007db404a4d34ae358d6
[ "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
1,311
lean
import Lean.Data.Lsp open IO Lean Lsp def main : IO Unit := do Ipc.runWith (←IO.appPath) #["--server"] do let hIn ← Ipc.stdin hIn.write (←FS.readBinFile "init_vscode_1_47_2.log") hIn.flush discard $ Ipc.readResponseAs 0 InitializeResult Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩ hIn.write (←FS.readBinFile "open_content.log") hIn.flush discard <| Ipc.collectDiagnostics 1 "file:///test.lean" 1 hIn.write (←FS.readBinFile "content_changes.log") hIn.flush let diags ← Ipc.collectDiagnostics 2 "file:///test.lean" 7 if diags.isEmpty then throw $ userError "Test failed, no diagnostics received." else let diag := diags.getLast! FS.writeFile "edits_diag.json.produced" (toString <| toJson (diag : JsonRpc.Message)) if let Except.ok (refDiag : JsonRpc.Notification PublishDiagnosticsParams) := (Json.parse $ ←FS.readFile "edits_diag.json") >>= fromJson? then assert! (diag == refDiag) else throw $ userError "Failed parsing test file." Ipc.writeRequest ⟨3, "shutdown", Json.null⟩ let shutResp ← Ipc.readResponseAs 3 Json assert! shutResp.result.isNull Ipc.writeNotification ⟨"exit", Json.null⟩ discard $ Ipc.waitForExit
01785674e48b290634510f010e2e770d08536bf5
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/envExtensionSealed.lean
7899e4f1292de1b8bea3d9f06ab38a227dc23ee1
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
245
lean
import Lean namespace Lean def ex1 : CoreM Nat := do let env ← getEnv pure $ privateExt.getState env #eval ex1 def ex2 : CoreM Nat := do let env ← getEnv pure $ { privateExt with idx := 3 }.getState env -- Error -- #eval ex2 end Lean
9cd1f097d47bdb60bf606dc9b8309e0712aa6ddd
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/ring_theory/ideal/operations.lean
debc027c3e256155684171bc13b4b1f28ab40ff8
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
74,754
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.operations import algebra.algebra.tower import data.equiv.ring import data.nat.choose.sum import ring_theory.ideal.basic import ring_theory.non_zero_divisors /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators pointwise namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] open_locale pointwise instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, (r : R) • N⟩ /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left _ hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h @[simp] theorem annihilator_smul (N : submodule R M) : annihilator N • N = ⊥ := eq_bot_iff.2 (smul_le.2 (λ r, mem_annihilator.1)) @[simp] theorem annihilator_mul (I : ideal R) : annihilator I * I = ⊥ := annihilator_smul I @[simp] theorem mul_annihilator (I : ideal R) : I * annihilator I = ⊥ := by rw [mul_comm, annihilator_mul] variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) variables {M' : Type w} [add_comm_group M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end /-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/ def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := quotient.lift (⨅ i, f i) (pi.ring_hom (λ i : ι, (quotient.mk (f i) : _))) $ λ r hr, begin rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder section mul_and_radical variables {R : Type u} {ι : Type*} [comm_ring R] variables {I J K L : ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_range, linear_map.range_id] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs lemma pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n := begin induction n with n ih, { simp only [pow_zero, ideal.one_eq_top], }, simpa only [pow_succ] using mul_mem_mul hx ih, end theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, J.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span, } lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], } lemma span_singleton_pow (s : R) (n : ℕ): span {s} ^ n = (span {s ^ n} : ideal R) := begin induction n with n ih, { simp [set.singleton_one], }, simp only [pow_succ, ih, span_singleton_mul_span_singleton], end lemma mem_mul_span_singleton {x y : R} {I : ideal R} : x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x := submodule.mem_smul_span_singleton lemma mem_span_singleton_mul {x y : R} {I : ideal R} : x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x := by simp only [mul_comm, mem_mul_span_singleton] lemma le_span_singleton_mul_iff {x : R} {I J : ideal R} : I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (hzI : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI, by simp only [mem_span_singleton_mul] lemma span_singleton_mul_le_iff {x : R} {I J : ideal R} : span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := begin simp only [mul_le, mem_span_singleton_mul, mem_span_singleton], split, { intros h zI hzI, exact h x (dvd_refl x) zI hzI }, { rintros h _ ⟨z, rfl⟩ zI hzI, rw [mul_comm x z, mul_assoc], exact J.mul_mem_left _ (h zI hzI) }, end lemma span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} : span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ := by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm] lemma eq_span_singleton_mul {x : R} (I J : ideal R) : I = span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) := by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff] lemma span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : ideal R) : span {x} * I = span {y} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧ (∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) := by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm] theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem multiset_prod_le_inf {s : multiset (ideal R)} : s.prod ≤ s.inf := begin classical, refine s.induction_on _ _, { rw [multiset.inf_zero], exact le_top }, intros a s ih, rw [multiset.prod_cons, multiset.inf_cons], exact le_trans mul_le_inf (inf_le_inf (le_refl _) ih) end theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := multiset_prod_le_inf theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) @[simp] theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I @[simp] theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I @[simp] theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I @[simp] theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma mul_eq_bot {R : Type*} [integral_domain R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ instance {R : Type*} [integral_domain R] : no_zero_divisors (ideal R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 } /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ lemma prod_eq_bot {R : Type*} [integral_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) @[simp] theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := ⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩ theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_nonempty_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_integral_domain {R : Type u} [integral_domain R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ } ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.multiset_prod_le {s : multiset (ideal R)} {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P := suffices s.prod ≤ P → ∃ I ∈ s, I ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans multiset_prod_le_inf $ le_trans (multiset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := multiset.exists_mem_of_ne_zero hne, obtain ⟨t, rfl⟩ : ∃ t, s = b ::ₘ t, from ⟨s.erase b, (multiset.cons_erase hb).symm⟩, refine t.induction_on _ _, { simp only [exists_prop, ←multiset.singleton_eq_cons, multiset.prod_singleton, multiset.mem_singleton, exists_eq_left, imp_self] }, intros a s ih h, rw [multiset.cons_swap, multiset.prod_cons, hp.mul_le] at h, rw multiset.cons_swap, cases h, { exact ⟨a, multiset.mem_cons_self a _, h⟩ }, obtain ⟨I, hI, ih⟩ : ∃ I ∈ b ::ₘ s, I ≤ P := ih h, exact ⟨I, multiset.mem_cons_of_mem hI, ih⟩ end theorem is_prime.multiset_prod_map_le {s : multiset ι} (f : ι → ideal R) {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : (s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P := begin rw hp.multiset_prod_le (mt multiset.map_eq_zero.mp hne), simp_rw [exists_prop, multiset.mem_map, exists_exists_and_eq_and], end theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne : s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := hp.multiset_prod_map_le f (mt finset.val_eq_zero.mp hne.ne_empty) theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_bUnion_iff at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, tactic.unfreeze_local_instances, by_cases has : a ∈ s, { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩, by_cases hbt : b ∈ t, { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { subst hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end section dvd /-- If `I` divides `J`, then `I` contains `J`. In a Dedekind domain, to divide and contain are equivalent, see `ideal.dvd_iff_le`. -/ lemma le_of_dvd {I J : ideal R} : I ∣ J → J ≤ I | ⟨K, h⟩ := h.symm ▸ le_trans mul_le_inf inf_le_left lemma is_unit_iff {I : ideal R} : is_unit I ↔ I = ⊤ := is_unit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸ ⟨λ h, eq_top_iff.mpr (ideal.le_of_dvd h), λ h, ⟨⊤, by rw [mul_top, h]⟩⟩) instance unique_units : unique (units (ideal R)) := { default := 1, uniq := λ u, units.ext (show (u : ideal R) = 1, by rw [is_unit_iff.mp u.is_unit, one_eq_top]) } end dvd end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [ring R] [ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left _ hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem (f : R →+* S) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ lemma apply_coe_mem_map (f : R →+* S) (I : ideal R) (x : I) : f x ∈ I.map f := mem_map_of_mem f x.prop theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [ring T] {I : ideal T} (f : R →+* S) (g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [ring T] {I : ideal R} (f : R →+* S) (g : S →+*T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) lemma map_span (f : R →+* S) (s : set R) : map f (span s) = span (f '' s) := symm $ submodule.span_eq_of_le _ (λ y ⟨x, hy, x_eq⟩, x_eq ▸ mem_map_of_mem f (subset_span hy)) (map_le_iff_le_comap.2 $ span_le.2 $ set.image_subset_iff.1 subset_span) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := congr_fun (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := congr_fun (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.ne_top, λ x y h, H.mem_or_mem $ by rwa [mem_comap, ring_hom.map_mul] at h⟩ variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩ theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end end surjective /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/ @[simp] lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, map_map] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/ @[simp] lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) : (I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/ lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm := le_antisymm (le_comap_of_map_le (map_of_equiv I f).le) (le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le) section injective variables (hf : function.injective f) include hf open function lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective section bijective variables (hf : function.bijective f) include hf open function /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) : (⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal := ⟨λ h, (@map_bot _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h, λ h, (@map_bot _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩ end map_and_comap section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end variables (I J K L) theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem f (mul_mem_mul hri hsj)) theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem f hrni⟩ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) end map_and_comap section is_primary variables {R : Type u} [comm_ring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} section ring variables [ring R] [ring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = set.preimage f {0} := rfl lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact f.injective_iff' } lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by { rw [← f.injective_iff, injective_iff_ker_eq_bot] } /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using f.injective end ring section comm_ring variables [comm_ring R] [comm_ring S] (f : R →+* S) /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : f.ker.quotient →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), quotient.sound' $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] variable {f} /-- The first isomorphism theorem for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : f.ker.quotient ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : f.ker.quotient) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The first isomorphism theorem for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : f.ker.quotient ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end comm_ring /-- The kernel of a homomorphism to an integral domain is a prime ideal. -/ lemma ker_is_prime [ring R] [integral_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ /-- The kernel of a homomorphism to a field is a maximal ideal. -/ lemma ker_is_maximal_of_surjective {R K : Type*} [ring R] [field K] (f : R →+* K) (hf : function.surjective f) : f.ker.is_maximal := begin refine ideal.is_maximal_iff.mpr ⟨λ h1, @one_ne_zero K _ _ $ f.map_one ▸ f.mem_ker.mp h1, λ J x hJ hxf hxJ, _⟩, obtain ⟨y, hy⟩ := hf (f x)⁻¹, have H : 1 = y * x - (y * x - 1) := (sub_sub_cancel _ _).symm, rw H, refine J.sub_mem (J.mul_mem_left _ hxJ) (hJ _), rw f.mem_ker, simp only [hy, ring_hom.map_sub, ring_hom.map_one, ring_hom.map_mul, inv_mul_cancel (mt f.mem_ker.mpr hxf), sub_self], end end ring_hom namespace ideal variables {R : Type*} {S : Type*} section ring variables [ring R] [ring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem f _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← ring_hom.map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)), abel }, exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) } end theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] : is_prime (map (f : R →+* S) I) := map_is_prime_of_surjective f.surjective $ by simp end ring section comm_ring variables [comm_ring R] [comm_ring S] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ := by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h } lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) : (ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk := begin ext x, split, { intro hx, obtain ⟨y, hy⟩ := quotient.mk_surjective x, rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx, rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective], exact ⟨y, hx, rfl⟩ }, { intro hx, rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx, obtain ⟨y, hy⟩ := hx, rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)], exact hy.left }, end theorem map_eq_iff_sup_ker_eq_of_surjective {I J : ideal R} (f : R →+* S) (hf : function.surjective f) : map f I = map f J ↔ I ⊔ f.ker = J ⊔ f.ker := by rw [← (comap_injective_of_surjective f hf).eq_iff, comap_map_of_surjective f hf, comap_map_of_surjective f hf, ring_hom.ker_eq_comap_bot] theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal I.quotient).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) ⊥ quotient.mk_surjective hI, λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩ section quotient_algebra variables (R) {A : Type*} [comm_ring A] [algebra R A] /-- The `R`-algebra structure on `A/I` for an `R`-algebra `A` -/ instance {I : ideal A} : algebra R (ideal.quotient I) := (ring_hom.comp (ideal.quotient.mk I) (algebra_map R A)).to_algebra /-- The canonical morphism `A →ₐ[R] I.quotient` as morphism of `R`-algebras, for `I` an ideal of `A`, where `A` is an `R`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R] I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_map_eq (I : ideal A) : algebra_map R I.quotient = (algebra_map A I.quotient).comp (algebra_map R A) := by simp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_id] instance [algebra S A] [algebra S R] [is_scalar_tower S R A] {I : ideal A} : is_scalar_tower S R (ideal.quotient I) := is_scalar_tower.of_algebra_map_eq' $ by rw [quotient.alg_map_eq R, quotient.alg_map_eq S, ring_hom.comp_assoc, is_scalar_tower.algebra_map_eq S R A] lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R I) = ideal.quotient.mk I := rfl /-- The canonical morphism `A →ₐ[R] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R I : A →+* I.quotient).ker = I := ideal.mk_ker variables {R} {B : Type*} [comm_ring B] [algebra R B] lemma ker_lift.map_smul (f : A →ₐ[R] B) (r : R) (x : f.to_ring_hom.ker.quotient) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R] B) : f.to_ring_hom.ker.quotient →ₐ[R] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The first isomorphism theorem for agebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) (x : f.to_ring_hom.ker.quotient) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R f.to_ring_hom.ker (g x) := rfl /-- The first isomorphism theorem for algebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : I.quotient →+* J.quotient := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : I.quotient ≃+* J.quotient := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _}) } /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (quotient_map I f H).injective_iff.2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end variables {I : ideal R} {J: ideal S} [algebra R S] /-- The algebra hom `A/I →+* S/J` induced by an algebra hom `f : A →ₐ[R] S` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (hIJ : I ≤ J.comap f) : I.quotient →ₐ[R] J.quotient := { commutes' := λ r, begin have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl, simpa [h] end ..quotient_map J ↑f hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R I) = (quotient.mkₐ R J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] S/J` induced by an algebra equiv `f : A ≃ₐ[R] S`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal S) (f : A ≃ₐ[R] S) (hIJ : J = I.map (f : A →+* S)) : I.quotient ≃ₐ[R] J.quotient := { commutes' := λ r, begin have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl, simpa [h] end, ..quotient_equiv I J (f : A ≃+* S) hIJ } @[priority 100] instance quotient_algebra : algebra (J.comap (algebra_map R S)).quotient J.quotient := (quotient_map J (algebra_map R S) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective : function.injective (algebra_map (J.comap (algebra_map R S)).quotient J.quotient) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end comm_ring end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- TODO: show `[algebra R A] : algebra (ideal R) A` too instance module_submodule : module (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [ring A] [ring B] [ring C] variables (f : A →+* B) (f_inv : B → A) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (f_inv b), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact hf 1 end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [hf _], end, .. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ } @[simp] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a /-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`), * where `f : A →+* B` is has a right_inverse `f_inv` (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end ring_hom namespace double_quot open ideal variables {R : Type u} [comm_ring R] (I J : ideal R) /-- The obvious ring hom `R/I → R/(I ⊔ J)` -/ def quot_left_to_quot_sup : I.quotient →+* (I ⊔ J).quotient := ideal.quotient.factor I (I ⊔ J) le_sup_left /-- The kernel of `quot_left_to_quot_sup` -/ lemma ker_quot_left_to_quot_sup : (quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) := by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift, map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc] /-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'` is the image of `J` in `R/I`-/ def quot_quot_to_quot_sup : (J.map (ideal.quotient.mk I)).quotient →+* (I ⊔ J).quotient := ideal.quotient.lift (ideal.map (ideal.quotient.mk I) J) (quot_left_to_quot_sup I J) (ker_quot_left_to_quot_sup I J).symm.le /-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/ def quot_quot_mk : R →+* (J.map I^.quotient.mk).quotient := ((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk /-- The kernel of `quot_quot_mk` -/ lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J := by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker, comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker, sup_comm] /-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/ def lift_sup_quot_quot_mk (I J : ideal R) : (I ⊔ J).quotient →+* (J.map (ideal.quotient.mk I)).quotient := ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le /-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms -/ def quot_quot_equiv_quot_sup : (J.map (ideal.quotient.mk I)).quotient ≃+* (I ⊔ J).quotient := ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J) (by { ext z, refl }) (by { ext z, refl }) end double_quot
6922f4a922aa7d6859eb75c9f568fc22529bbe5d
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/nat/digits.lean
45946615fe0b9d775411f98d7700a223ddd8d945
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
17,703
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam -/ import data.int.modeq import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. -/ namespace nat /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := rfl lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := begin cases b, { refl, }, { cases b; refl, }, end @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := rfl @[simp] lemma digits_of_lt (b x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := begin cases b, { cases w₂ }, { cases b, { interval_cases x, }, { cases x, { cases w₁, }, { dsimp [digits], rw digits_aux, rw nat.div_eq_of_lt w₂, dsimp only [digits_aux_zero], rw nat.mod_eq_of_lt w₂, } } } end lemma digits_add (b : ℕ) (h : 2 ≤ b) (x y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := begin cases b, { cases h, }, { cases b, { norm_num at h, }, { cases y, { norm_num at w', simp [w, w'], }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, nat.mod_eq_of_lt w], }, { simp [mul_comm (b+2), nat.add_mul_div_right, nat.div_eq_of_lt w], } }, { apply nat.succ_pos, }, }, }, end /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end @[simp] lemma of_digits_singleton {b n : ℕ} : of_digits b [n] = n := by simp [of_digits] @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, pow_succ'], ring } end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end lemma digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : list ℕ} (w : of_digits b L = 0) : ∀ l ∈ L, l = 0 := begin induction L with d L ih, { intros l m, cases m, }, { intros l m, dsimp [of_digits] at w, rcases m with ⟨rfl⟩, { convert nat.eq_zero_of_add_eq_zero_right w, simp, }, { exact ih ((nat.mul_right_inj h).mp (nat.eq_zero_of_add_eq_zero_left w)) _ m, }, } end lemma digits_of_digits (b : ℕ) (h : 2 ≤ b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { simp, }, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons _ h] at w₂, convert w₂, }}}, { convert w₁ d (list.mem_cons_self _ _), simp, }, { by_cases h' : L = [], { rcases h' with rfl, simp at w₂, left, apply nat.pos_of_ne_zero, convert w₂, simp, }, { right, apply nat.pos_of_ne_zero, contrapose! w₂, apply digits_zero_of_eq_zero _ w₂, { rw list.last_cons _ h', exact list.last_mem h', }, { exact le_of_lt h, }, }, }, }, end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.cast_id, nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ lemma digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := begin split, { intro h, have : of_digits b (digits b n) = of_digits b [], by rw h, convert this, rw of_digits_digits }, { rintro rfl, simp } end lemma digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero private lemma digits_last_aux {b n : ℕ} (h : 2 ≤ b) (w : 0 < n) : digits b n = ((n % b) :: digits b (n / b)) := begin rcases b with _|_|b, { finish }, { norm_num at h }, rcases n with _|n, { norm_num at w }, simp, end lemma digits_last {b m : ℕ} (h : 2 ≤ b) (hm : 0 < m) (p q) : (digits b m).last p = (digits b (m/b)).last q := by { simp only [digits_last_aux h hm], rw list.last_cons } lemma last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).last (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := begin rcases b with _|_|b, { cases m; finish }, { cases m, { finish }, simp_rw [digits_one, list.last_repeat_succ 1 m], norm_num }, revert hm, apply nat.strong_induction_on m, intros n IH hn, have hnpos : 0 < n := nat.pos_of_ne_zero hn, by_cases hnb : n < b + 2, { simp_rw [digits_of_lt b.succ.succ n hnpos hnb], exact nat.pos_iff_ne_zero.mp hnpos }, { rw digits_last (show 2 ≤ b + 2, from dec_trivial) hnpos, refine IH _ (nat.div_lt_self hnpos dec_trivial) _, { rw ←nat.pos_iff_ne_zero, exact nat.div_pos (le_of_not_lt hnb) dec_trivial } }, end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, unfold digits at hd IH, cases n with n, { cases hd }, -- base b+2 expansion of 0 has no digits rw digits_aux_def (b+2) (by linarith) n.succ (nat.zero_lt_succ n) at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 2 ≤ b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, pow_succ], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 2 ≤ b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 2 ≤ b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin cases b, { -- base 0 cases n; simp }, { cases b, { -- base 1 simp }, { -- base >= 2 apply nat.strong_induction_on n, clear n, intros n IH, cases n, { simp }, { rw [digits_add_two_add_one, digits_add_two_add_one], by_cases hdvd : (b.succ.succ) ∣ (n.succ+1), { rw [nat.succ_div_of_dvd hdvd, list.length_cons, list.length_cons, nat.succ_le_succ_iff], apply IH, exact nat.div_lt_self (by linarith) (by linarith) }, { rw nat.succ_div_of_not_dvd hdvd, refl } } } } end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_of_monotone_nat (digits_len_le_digits_len_succ b) h lemma pow_length_le_mul_of_digits {b : ℕ} {l : list ℕ} (hl : l ≠ []) (hl2 : l.last hl ≠ 0): (b + 2) ^ l.length ≤ (b + 2) * of_digits (b+2) l := begin rw [←list.init_append_last hl], simp only [list.length_append, list.length, zero_add, list.length_init, of_digits_append, list.length_init, of_digits_singleton, add_comm (l.length - 1), pow_add, pow_one], apply nat.mul_le_mul_left, refine le_trans _ (nat.le_add_left _ _), have : 0 < l.last hl, { rwa [nat.pos_iff_ne_zero] }, convert nat.mul_le_mul_left _ this, rw [mul_one] end /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ lemma base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin have : digits (b + 2) m ≠ [], from digits_ne_nil_iff_ne_zero.mpr hm, convert pow_length_le_mul_of_digits this (last_digit_ne_zero _ hm), rwa of_digits_digits, end /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ lemma base_pow_length_digits_le (b m : ℕ) (hb : 2 ≤ b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (nat.modeq.symm (nat.modeq.mod_modeq b k)) L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (int.modeq.symm (int.modeq.mod_modeq b ↑k)) L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], push_cast, ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) dec_trivial n, rw of_digits_neg_one at t, exact t, end /-! ## Divisibility -/ lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (int.modeq.modeq_iff_dvd.1 (zmodeq_of_digits_digits b b' c (int.modeq.modeq_iff_dvd.2 h).symm _).symm), end lemma eleven_dvd_iff (n : ℕ) : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end end nat
65c6d315d2a959dc50e3ec712d21ec16d9ed2774
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/equiv/fin.lean
c50909704e3b744a62690c731ebef4cfca97c1d9
[ "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
2,855
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau Equivalences between finite numbers. -/ import data.fin data.equiv.basic variables {m n : ℕ} def fin_zero_equiv : fin 0 ≃ empty := ⟨fin_zero_elim, empty.elim, assume a, fin_zero_elim a, assume a, empty.elim a⟩ def fin_one_equiv : fin 1 ≃ punit := ⟨λ_, (), λ_, 0, fin.cases rfl (λa, fin_zero_elim a), assume ⟨⟩, rfl⟩ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, refl, refine fin.cases _ _, refl, exact λi, fin_zero_elim i end, assume b, match b with tt := rfl | ff := rfl end⟩ def sum_fin_sum_equiv : (fin m ⊕ fin n) ≃ fin (m + n) := { to_fun := λ x, sum.rec_on x (λ y, ⟨y.1, nat.lt_of_lt_of_le y.2 $ nat.le_add_right m n⟩) (λ y, ⟨m + y.1, nat.add_lt_add_left y.2 m⟩), inv_fun := λ x, if H : x.1 < m then sum.inl ⟨x.1, H⟩ else sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $ show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ le_of_not_gt H).symm ▸ x.2⟩, left_inv := λ x, begin cases x with y y, { simp [y.2, fin.ext_iff] }, { have H : ¬m + y.val < m := not_lt_of_ge (nat.le_add_right _ _), simp [H, nat.add_sub_cancel_left, fin.ext_iff] } end, right_inv := λ x, begin by_cases H : x.1 < m, { dsimp, rw [dif_pos H], simp }, { dsimp, rw [dif_neg H], simp [fin.ext_iff, nat.add_sub_of_le (le_of_not_gt H)] } end } def fin_prod_fin_equiv : (fin m × fin n) ≃ fin (m * n) := { to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, have H : n > 0, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2, (⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩, ⟨x.1 % n, nat.mod_lt _ H⟩), left_inv := λ ⟨x, y⟩, have H : n > 0, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
09cefd84248f67ed67931ceb2d1ab23667f29f61
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/finbug2.lean
a67f5c71b4c90fd5e43b94477ede419c6dea627a
[ "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
950
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.fin Author: Leonardo de Moura Finite ordinals. -/ open nat inductive fin : nat → Type := fz : Π n, fin (succ n), fs : Π {n}, fin n → fin (succ n) namespace fin definition to_nat : Π {n}, fin n → nat, @to_nat (succ n) (fz n) := zero, @to_nat (succ n) (fs f) := succ (@to_nat n f) definition lift : Π {n : nat}, fin n → Π (m : nat), fin (add m n), @lift (succ n) (fz n) m := fz (add m n), @lift (succ n) (@fs n f) m := fs (@lift n f m) theorem to_nat_lift : ∀ {n : nat} (f : fin n) (m : nat), to_nat f = to_nat (lift f m), to_nat_lift (fz n) m := rfl, to_nat_lift (@fs n f) m := calc to_nat (fs f) = (to_nat f) + 1 : rfl ... = (to_nat (lift f m)) + 1 : to_nat_lift f ... = to_nat (lift (fs f) m) : rfl end fin
10d8e1931ce32552ee7837e77dde631d15bed25a
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/while/BExp.lean
e255876ab69e8be40108455c04800796dd88fc43
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
412
lean
import Env import AExp -- Shallow embedding for boolean expressions def BExp : Type := Env -> Prop -- A variable 'x' is read by a shallowly embedded boolean expression 'b', if and -- only if, there is a environment 's' and an integer 'n' such that evaluating b in -- s after binding x to n, makes a difference def BRead (b:BExp) : set string := {x | ∃ (s:Env)(n:ℕ), b (bindVar x (aNum n) s) ≠ b s }
608540167c08afe0d6c9a771c4662e951a8190bd
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/category/Group/epi_mono.lean
ca6fc836c22f519050f57143f3fbdd52b57ce35e
[ "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
12,730
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebra.category.Group.equivalence_Group_AddGroup import category_theory.epi_mono import group_theory.quotient_group /-! # Monomorphisms and epimorphisms in `Group` In this file, we prove monomorphisms in category of group are injective homomorphisms and epimorphisms are surjective homomorphisms. -/ noncomputable theory universes u v namespace monoid_hom open quotient_group variables {A : Type u} {B : Type v} section variables [group A] [group B] @[to_additive add_monoid_hom.ker_eq_bot_of_cancel] lemma ker_eq_bot_of_cancel {f : A →* B} (h : ∀ (u v : f.ker →* A), f.comp u = f.comp v → u = v) : f.ker = ⊥ := by simpa using _root_.congr_arg range (h f.ker.subtype 1 (by tidy)) end section variables [comm_group A] [comm_group B] @[to_additive add_monoid_hom.range_eq_top_of_cancel] lemma range_eq_top_of_cancel {f : A →* B} (h : ∀ (u v : B →* B ⧸ f.range), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin specialize h 1 (quotient_group.mk' _) _, { ext1, simp only [one_apply, coe_comp, coe_mk', function.comp_app], rw [show (1 : B ⧸ f.range) = (1 : B), from quotient_group.coe_one _, quotient_group.eq, inv_one, one_mul], exact ⟨x, rfl⟩, }, replace h : (quotient_group.mk' _).ker = (1 : B →* B ⧸ f.range).ker := by rw h, rwa [ker_one, quotient_group.ker_mk] at h, end end end monoid_hom section open category_theory namespace Group variables {A B : Group.{u}} (f : A ⟶ B) @[to_additive AddGroup.ker_eq_bot_of_mono] lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := monoid_hom.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ (show Group.of f.ker ⟶ A, from u) _).1 @[to_additive AddGroup.mono_iff_ker_eq_bot] lemma mono_iff_ker_eq_bot : mono f ↔ f.ker = ⊥ := ⟨λ h, @@ker_eq_bot_of_mono f h, λ h, concrete_category.mono_of_injective _ $ (monoid_hom.ker_eq_bot_iff f).1 h⟩ @[to_additive AddGroup.mono_iff_injective] lemma mono_iff_injective : mono f ↔ function.injective f := iff.trans (mono_iff_ker_eq_bot f) $ monoid_hom.ker_eq_bot_iff f namespace surjective_of_epi_auxs local notation `X` := set.range (function.swap left_coset f.range.carrier) /-- Define `X'` to be the set of all left cosets with an extra point at "infinity". -/ @[nolint has_nonempty_instance] inductive X_with_infinity | from_coset : set.range (function.swap left_coset f.range.carrier) → X_with_infinity | infinity : X_with_infinity open X_with_infinity equiv.perm open_locale coset local notation `X'` := X_with_infinity f local notation `∞` := X_with_infinity.infinity local notation `SX'` := equiv.perm X' instance : has_smul B X' := { smul := λ b x, match x with | from_coset y := from_coset ⟨b *l y, begin rw [←subtype.val_eq_coe, ←y.2.some_spec, left_coset_assoc], use b * y.2.some, end⟩ | ∞ := ∞ end } lemma mul_smul (b b' : B) (x : X') : (b * b') • x = b • b' • x := match x with | from_coset y := begin change from_coset _ = from_coset _, simp only [←subtype.val_eq_coe, left_coset_assoc], end | ∞ := rfl end lemma one_smul (x : X') : (1 : B) • x = x := match x with | from_coset y := begin change from_coset _ = from_coset _, simp only [←subtype.val_eq_coe, one_left_coset, subtype.ext_iff_val], end | ∞ := rfl end lemma from_coset_eq_of_mem_range {b : B} (hb : b ∈ f.range) : from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩ = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := begin congr, change b *l f.range = f.range, nth_rewrite 1 [show (f.range : set B) = 1 *l f.range, from (one_left_coset _).symm], rw [left_coset_eq_iff, mul_one], exact subgroup.inv_mem _ hb, end lemma from_coset_ne_of_nin_range {b : B} (hb : b ∉ f.range) : from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩ ≠ from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := begin intros r, simp only [subtype.mk_eq_mk] at r, change b *l f.range = f.range at r, nth_rewrite 1 [show (f.range : set B) = 1 *l f.range, from (one_left_coset _).symm] at r, rw [left_coset_eq_iff, mul_one] at r, exact hb (inv_inv b ▸ (subgroup.inv_mem _ r)), end instance : decidable_eq X' := classical.dec_eq _ /-- Let `τ` be the permutation on `X'` exchanging `f.range` and the point at infinity. -/ noncomputable def tau : SX' := equiv.swap (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) ∞ local notation `τ` := tau f lemma τ_apply_infinity : τ ∞ = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := equiv.swap_apply_right _ _ lemma τ_apply_from_coset : τ (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = ∞ := equiv.swap_apply_left _ _ lemma τ_apply_from_coset' (x : B) (hx : x ∈ f.range) : τ (from_coset ⟨x *l f.range.carrier, ⟨x, rfl⟩⟩) = ∞ := (from_coset_eq_of_mem_range _ hx).symm ▸ τ_apply_from_coset _ lemma τ_symm_apply_from_coset : (equiv.symm τ) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = ∞ := by rw [tau, equiv.symm_swap, equiv.swap_apply_left] lemma τ_symm_apply_infinity : (equiv.symm τ) ∞ = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := by rw [tau, equiv.symm_swap, equiv.swap_apply_right] /-- Let `g : B ⟶ S(X')` be defined as such that, for any `β : B`, `g(β)` is the function sending point at infinity to point at infinity and sending coset `y` to `β *l y`. -/ def G : B →* SX' := { to_fun := λ β, { to_fun := λ x, β • x, inv_fun := λ x, β⁻¹ • x, left_inv := λ x, by { dsimp only, rw [←mul_smul, mul_left_inv, one_smul] }, right_inv := λ x, by { dsimp only, rw [←mul_smul, mul_right_inv, one_smul] } }, map_one' := by { ext, simp [one_smul] }, map_mul' := λ b1 b2, by { ext, simp [mul_smul] } } local notation `g` := G f /-- Define `h : B ⟶ S(X')` to be `τ g τ⁻¹` -/ def H : B →* SX':= { to_fun := λ β, ((τ).symm.trans (g β)).trans τ, map_one' := by { ext, simp }, map_mul' := λ b1 b2, by { ext, simp } } local notation `h` := H f /-! The strategy is the following: assuming `epi f` * prove that `f.range = {x | h x = g x}`; * thus `f ≫ h = f ≫ g` so that `h = g`; * but if `f` is not surjective, then some `x ∉ f.range`, then `h x ≠ g x` at the coset `f.range`. -/ lemma g_apply_from_coset (x : B) (y : X) : (g x) (from_coset y) = from_coset ⟨x *l y, by tidy⟩ := rfl lemma g_apply_infinity (x : B) : (g x) ∞ = ∞ := rfl lemma h_apply_infinity (x : B) (hx : x ∈ f.range) : (h x) ∞ = ∞ := begin simp only [H, monoid_hom.coe_mk, equiv.to_fun_as_coe, equiv.coe_trans, function.comp_app], rw [τ_symm_apply_infinity, g_apply_from_coset], simpa only [←subtype.val_eq_coe] using τ_apply_from_coset' f x hx, end lemma h_apply_from_coset (x : B) : (h x) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := by simp [H, τ_symm_apply_from_coset, g_apply_infinity, τ_apply_infinity] lemma h_apply_from_coset' (x : B) (b : B) (hb : b ∈ f.range): (h x) (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) = from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩ := (from_coset_eq_of_mem_range _ hb).symm ▸ h_apply_from_coset f x lemma h_apply_from_coset_nin_range (x : B) (hx : x ∈ f.range) (b : B) (hb : b ∉ f.range) : (h x) (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) = from_coset ⟨(x * b) *l f.range.carrier, ⟨x * b, rfl⟩⟩ := begin simp only [H, tau, monoid_hom.coe_mk, equiv.to_fun_as_coe, equiv.coe_trans, function.comp_app], rw [equiv.symm_swap, @equiv.swap_apply_of_ne_of_ne X' _ (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) ∞ (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) (from_coset_ne_of_nin_range _ hb) (by simp)], simp only [g_apply_from_coset, ←subtype.val_eq_coe, left_coset_assoc], refine equiv.swap_apply_of_ne_of_ne (from_coset_ne_of_nin_range _ (λ r, hb _)) (by simp), convert subgroup.mul_mem _ (subgroup.inv_mem _ hx) r, rw [←mul_assoc, mul_left_inv, one_mul], end lemma agree : f.range.carrier = {x | h x = g x} := begin refine set.ext (λ b, ⟨_, λ (hb : h b = g b), classical.by_contradiction (λ r, _)⟩), { rintros ⟨a, rfl⟩, change h (f a) = g (f a), ext ⟨⟨_, ⟨y, rfl⟩⟩⟩, { rw [g_apply_from_coset], by_cases m : y ∈ f.range, { rw [h_apply_from_coset' _ _ _ m, from_coset_eq_of_mem_range _ m], change from_coset _ = from_coset ⟨f a *l (y *l _), _⟩, simpa only [←from_coset_eq_of_mem_range _ (subgroup.mul_mem _ ⟨a, rfl⟩ m), left_coset_assoc] }, { rw [h_apply_from_coset_nin_range _ _ ⟨_, rfl⟩ _ m], simpa only [←subtype.val_eq_coe, left_coset_assoc], }, }, { rw [g_apply_infinity, h_apply_infinity _ _ ⟨_, rfl⟩], } }, { have eq1 : (h b) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) := by simp [H, tau, g_apply_infinity], have eq2 : (g b) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) := rfl, exact (from_coset_ne_of_nin_range _ r).symm (by rw [←eq1, ←eq2, fun_like.congr_fun hb]) } end lemma comp_eq : f ≫ (show B ⟶ Group.of SX', from g) = f ≫ h := fun_like.ext _ _ $ λ a, by simp only [comp_apply, show h (f a) = _, from (by simp [←agree] : f a ∈ {b | h b = g b})] lemma g_ne_h (x : B) (hx : x ∉ f.range) : g ≠ h := begin intros r, replace r := fun_like.congr_fun (fun_like.congr_fun r x) ((from_coset ⟨f.range, ⟨1, one_left_coset _⟩⟩)), rw [H, g_apply_from_coset, monoid_hom.coe_mk, tau] at r, simp only [monoid_hom.coe_range, subtype.coe_mk, equiv.symm_swap, equiv.to_fun_as_coe, equiv.coe_trans, function.comp_app] at r, erw [equiv.swap_apply_left, g_apply_infinity, equiv.swap_apply_right] at r, exact from_coset_ne_of_nin_range _ hx r, end end surjective_of_epi_auxs lemma surjective_of_epi [epi f] : function.surjective f := begin by_contra r, push_neg at r, rcases r with ⟨b, hb⟩, exact surjective_of_epi_auxs.g_ne_h f b (λ ⟨c, hc⟩, hb _ hc) ((cancel_epi f).1 (surjective_of_epi_auxs.comp_eq f)), end lemma epi_iff_surjective : epi f ↔ function.surjective f := ⟨λ h, @@surjective_of_epi f h, concrete_category.epi_of_surjective _⟩ lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := iff.trans (epi_iff_surjective _) (subgroup.eq_top_iff' f.range).symm end Group namespace AddGroup variables {A B : AddGroup.{u}} (f : A ⟶ B) lemma epi_iff_surjective : epi f ↔ function.surjective f := begin have i1 : epi f ↔ epi (Group_AddGroup_equivalence.inverse.map f), { refine ⟨_, Group_AddGroup_equivalence.inverse.epi_of_epi_map⟩, introsI e', apply Group_AddGroup_equivalence.inverse.map_epi }, rwa Group.epi_iff_surjective at i1, end lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := iff.trans (epi_iff_surjective _) (add_subgroup.eq_top_iff' f.range).symm end AddGroup namespace CommGroup variables {A B : CommGroup.{u}} (f : A ⟶ B) @[to_additive AddCommGroup.ker_eq_bot_of_mono] lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := monoid_hom.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ (show CommGroup.of f.ker ⟶ A, from u) _).1 @[to_additive AddCommGroup.mono_iff_ker_eq_bot] lemma mono_iff_ker_eq_bot : mono f ↔ f.ker = ⊥ := ⟨λ h, @@ker_eq_bot_of_mono f h, λ h, concrete_category.mono_of_injective _ $ (monoid_hom.ker_eq_bot_iff f).1 h⟩ @[to_additive AddCommGroup.mono_iff_injective] lemma mono_iff_injective : mono f ↔ function.injective f := iff.trans (mono_iff_ker_eq_bot f) $ monoid_hom.ker_eq_bot_iff f @[to_additive] lemma range_eq_top_of_epi [epi f] : f.range = ⊤ := monoid_hom.range_eq_top_of_cancel $ λ u v h, (@cancel_epi _ _ _ _ _ f _ (show B ⟶ ⟨B ⧸ monoid_hom.range f⟩, from u) v).1 h @[to_additive] lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := ⟨λ hf, by exactI range_eq_top_of_epi _, λ hf, concrete_category.epi_of_surjective _ $ monoid_hom.range_top_iff_surjective.mp hf⟩ @[to_additive] lemma epi_iff_surjective : epi f ↔ function.surjective f := by rw [epi_iff_range_eq_top, monoid_hom.range_top_iff_surjective] @[to_additive] instance : functor.preserves_epimorphisms (forget₂ CommGroup Group) := { preserves := λ X Y f e, by rwa [epi_iff_surjective, ←@Group.epi_iff_surjective ⟨X⟩ ⟨Y⟩ f] at e } end CommGroup end
b11940275c54a53206409ec010f6066c4c7707e8
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/punit.lean
66d2ca4ed970e5539f38e4502c2f969f86172d8e
[ "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
757
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.const universes v w u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory instance punit_category : small_category punit := { hom := λ X Y, punit, id := λ _, punit.star, comp := λ _ _ _ _ _, punit.star } namespace functor variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 def star : C ⥤ punit.{w+1} := (const C).obj punit.star @[simp] lemma star_obj (X : C) : star.obj X = punit.star := rfl @[simp] lemma star_map {X Y : C} (f : X ⟶ Y) : star.map f = 𝟙 _ := rfl end functor end category_theory
370ecc607a90736e28a79b307c5541ac28cec354
9b0cdc31ceef59f5fbd4e20acad77a7a59044088
/src/solutions/03_forall_or.lean
99f8460559996f9c31af7143312388c542f91bad
[ "Apache-2.0" ]
permissive
andrewparr/tutorials
964ebb8b4eae2b658a946843f8f9fc5c69b79761
0fd6cefe7e62f0d4bfa12ebd115913f8ef4fbd62
refs/heads/master
1,687,573,595,883
1,626,653,659,000
1,626,653,659,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,254
lean
import data.real.basic import algebra.group.pi set_option pp.beta true /- In this file, we'll learn about the ∀ quantifier, and the disjunction operator ∨ (logical OR). Let P be a predicate on a type X. This means for every mathematical object x with type X, we get a mathematical statement P x. In Lean, P x has type Prop. Lean sees a proof h of `∀ x, P x` as a function sending any `x : X` to a proof `h x` of `P x`. This already explains the main way to use an assumption or lemma which starts with a ∀. In order to prove `∀ x, P x`, we use `intros x` to fix an arbitrary object with type X, and call it x. Note also we don't need to give the type of x in the expression `∀ x, P x` as long as the type of P is clear to Lean, which can then infer the type of x. Let's define two predicates to play with ∀. -/ def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x def odd_fun (f : ℝ → ℝ) := ∀ x, f (-x) = -f x /- In the next proof, we also take the opportunity to introduce the `unfold` tactic, which simply unfolds definitions. Here this is purely for didactic reason, Lean doesn't need those `unfold` invocations. We will also use `rfl` which is a term proving equalities that are true by definition (in a very strong sense to be discussed later). -/ example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) := begin -- Assume f is even intros hf, -- which means ∀ x, f (-x) = f x unfold even_fun at hf, -- and the same for g intros hg, unfold even_fun at hg, -- We need to prove ∀ x, (f+g)(-x) = (f+g)(x) unfold even_fun, -- Let x be any real number intros x, -- and let's compute calc (f + g) (-x) = f (-x) + g (-x) : rfl ... = f x + g (-x) : by rw hf x ... = f x + g x : by rw hg x ... = (f + g) x : rfl end /- In the preceding proof, all `unfold` lines are purely for psychological comfort. Sometimes unfolding is necessary because we want to apply a tactic that operates purely on the syntactical level. The main such tactic is `rw`. The same property of `rw` explain why the first computation line is necessary, although its proof is simply `rfl`. Before that line, `rw hf x` won't find anything like `f (-x)` hence will give up. The last line is not necessary however, since it only proves something that is true by definition, and is not followed by a `rw`. Also, Lean doesn't need to be told that hf should be specialized to x before rewriting, exactly as in the first file 01_equality_rewriting. We can also gather several rewrites using a list of expressions. One last trick is that `rw` can take a list of expressions to use for rewriting. For instance `rw [h₁, h₂, h₃]` is equivalent to three lines `rw h₁`, `rw h₂` and `rw h₃`. Note that you can inspect the tactic state between those rewrites when reading a proof using this syntax. You simply need to move the cursor inside the list. Hence we can compress the above proof to: -/ example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) := begin intros hf hg x, calc (f + g) (-x) = f (-x) + g (-x) : rfl ... = f x + g x : by rw [hf, hg] end /- Now let's practice. If you need to learn how to type a unicode symbol, you can put your mouse cursor above the symbol and wait for one second. -/ -- 0023 example (f g : ℝ → ℝ) : even_fun f → even_fun (g ∘ f) := begin -- sorry intros hf x, calc (g ∘ f) (-x) = g (f (-x)) : rfl ... = g (f x) : by rw hf -- sorry end -- 0024 example (f g : ℝ → ℝ) : odd_fun f → odd_fun g → odd_fun (g ∘ f) := begin -- sorry intros hf hg x, calc (g ∘ f) (-x) = g (f (-x)) : rfl ... = - (g ∘ f) x : by rw [hf, hg], -- sorry end /- Let's have more quantifiers, and play with forward and backward reasoning. In the next definitions, note how `∀ x₁, ∀ x₂` is abreviated to `∀ x₁ x₂`. -/ def non_decreasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≤ f x₂ def non_increasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≥ f x₂ /- Let's be very explicit and use forward reasonning first. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin -- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂ intros x₁ x₂ h, -- Since f is non-decreasing, f x₁ ≤ f x₂. have step₁ : f x₁ ≤ f x₂, exact hf x₁ x₂ h, -- Since g is non-decreasing, we then get g (f x₁) ≤ g (f x₂). exact hg (f x₁) (f x₂) step₁, end /- In the above proof, note how inconvenient it is to specify x₁ and x₂ in `hf x₁ x₂ h` since they could be inferred from the type of h. We could have written `hf _ _ h` and Lean would have filled the holes denoted by _. Even better we could have written the definition of `non_decreasing` as: ∀ {x₁ x₂}, x₁ ≤ x₂ → f x₁ ≤ f x₂, with curly braces to denote implicit arguments. But let's leave that aside for now. One possible variation on the above proof is to use the `specialize` tactic to replace hf by its specialization to the relevant value. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin intros x₁ x₂ h, specialize hf x₁ x₂ h, exact hg (f x₁) (f x₂) hf, end /- This `specialize` tactic is mostly useful for exploration, or in preparation for rewriting in the assumption. One can very often replace its use by using more complicated expressions directly involving the original assumption, as in the next variation: -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin intros x₁ x₂ h, exact hg (f x₁) (f x₂) (hf x₁ x₂ h), end /- Since the above proof uses only `intros` and `exact`, we could very easily replace it by the raw proof term: -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := λ x₁ x₂ h, hg (f x₁) (f x₂) (hf x₁ x₂ h) /- Of course the above proof is difficult to decipher. The principle in mathlib is to use such a proof when the result is obvious and you don't want to read the proof anyway. Instead of pursuing this style, let's see how backward reasoning would look like here. As usual with this style, we use `apply` and enjoy Lean specializing assumptions for us using unification. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin -- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂ intros x₁ x₂ h, -- We need to prove (g ∘ f) x₁ ≤ (g ∘ f) x₂. -- Since g is non-decreasing, it suffices to prove f x₁ ≤ f x₂ apply hg, -- which follows from our assumption on f apply hf, -- and on x₁ and x₂ exact h end -- 0025 example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_increasing g) : non_increasing (g ∘ f) := begin -- sorry intros x₁ x₂ h, apply hg, exact hf x₁ x₂ h -- sorry end /- Let's switch to disjunctions now. Lean denotes by ∨ the logical OR operator. In order to make use of an assumption hyp : P ∨ Q we use the cases tactic: cases hyp with hP hQ which creates two proof branches: one branch assuming hP : P, and one branch assuming hQ : Q. In order to directly prove a goal P ∨ Q, we use either the `left` tactic and prove P or the `right` tactic and prove Q. In the next proof we use `ring` and `linarith` to get rid of easy computations or inequalities, as well as one lemma: mul_eq_zero : a*b = 0 ↔ a = 0 ∨ b = 0 -/ example (a b : ℝ) : a = a*b → a = 0 ∨ b = 1 := begin intro hyp, have H : a*(1 - b) = 0, { calc a*(1 - b) = a - a*b : by ring ... = 0 : by linarith, }, rw mul_eq_zero at H, cases H with Ha Hb, { left, exact Ha, }, { right, linarith, }, end -- 0026 example (x y : ℝ) : x^2 = y^2 → x = y ∨ x = -y := begin -- sorry intros hyp, have H : (x-y)*(x+y) = 0, calc (x-y)*(x+y) = x^2 - y^2 : by ring ... = y^2 - y^2 : by rw hyp ... = 0 : by ring, rw mul_eq_zero at H, cases H with h1 h2, { left, linarith, }, { right, linarith, }, -- sorry end /- In the next exercise, we can use: eq_or_lt_of_le : x ≤ y → x = y ∨ x < y -/ -- 0027 example (f : ℝ → ℝ) : non_decreasing f ↔ ∀ x y, x < y → f x ≤ f y := begin -- sorry split, { intros hf x y hxy, apply hf, linarith, }, { intros hf x y hxy, have clef : x = y ∨ x < y, { exact eq_or_lt_of_le hxy }, cases clef with hxy hxy, rw hxy, exact hf x y hxy, }, -- sorry end /- In the next exercise, we can use: le_total x y : x ≤ y ∨ y ≤ x -/ -- 0028 example (f : ℝ → ℝ) (h : non_decreasing f) (h' : ∀ x, f (f x) = x) : ∀ x, f x = x := begin -- sorry intro x, have : f (f x) = x, { rw h' }, have : (f x ≤ x) ∨ (x ≤ f x), { exact le_total (f x) x }, cases this with hx hx, { have f1: f (f x) ≤ f x, { exact h (f x) x hx, }, rw h' at f1, linarith, }, { have f1: f x ≤ f (f x), { exact h x (f x) hx, }, rw h' x at f1, linarith, }, -- sorry end
92579eb59e6f3c4980214cf3b8fc5922765cc492
e16f547df783f1d9a7117fa3080541a01d6f1bc8
/src/basic_cat.lean
a1d69b0865430ac0075ff771d0fefffe4d0b2b3b
[]
no_license
iamcxds/Galois
fd5070420eae1306bb5048b903ba40146fb7a472
8ad1c22b5efcf332bc77901e1f1c64c2667ec11f
refs/heads/master
1,668,080,244,889
1,593,267,894,000
1,593,267,894,000
275,388,802
1
0
null
null
null
null
UTF-8
Lean
false
false
4,848
lean
import category_theory.functor_category --import field_theory.splitting_field --import field_theory.subfield import algebra.field import algebra.ring --import ring_theory.algebra --import ring_theory.algebraic import category_theory.isomorphism import algebra.group.hom import data.set.basic open category_theory universes v u --variables (k : Type u) [𝕜 :field k] (L : Type u) [𝕃 :field L] (F : Type u) [𝔽 :field F] structure fields : Type (u+1) := (k : Type u) (fStruct : field k) instance fields_to_sort : has_coe_to_sort fields := {S := Type u, coe := λ F, F.k} instance fieldIsField (a : fields) : field a := a.fStruct instance fields_has_hom : has_hom fields := { hom:= λ a b, ring_hom a b } instance fields_has_cat_struct : category_struct fields := {to_has_hom:= fields_has_hom, id:=λ X, ring_hom.id X, comp := λ a b c fab fbc,ring_hom.comp fbc fab } structure fieldsOver (L : fields.{u}) : Type (u+1) := (k : fields.{u}) (L2k : L →+* k ) instance ext_fields_coe (L : fields.{u}) : has_coe (fieldsOver L) fields.{u}:= ⟨fieldsOver.k⟩ @[ext] structure kLinearMor {L : fields.{u}} (k₁ k₂ : fieldsOver L) : Type u := (mor : k₁ →+* k₂ ) (coincide : ring_hom.comp mor k₁.L2k = k₂.L2k ) instance morphism_to_fun {L : fields.{u}} (k₁ k₂ : fieldsOver L) : has_coe_to_fun ( kLinearMor k₁ k₂) := { F := λ _, k₁ → k₂, coe := λ m, m.mor } instance ext_fields_has_hom (L : fields.{u}) : has_hom (fieldsOver L) := {hom := kLinearMor } instance ext_fields_has_cat_struct (L : fields.{u}) : category_struct (fieldsOver L) := {to_has_hom:= ext_fields_has_hom L, id:=λ X, {mor := ring_hom.id X, coincide:= ring_hom.id_comp _ }, comp := λ a b c fab fbc,⟨ring_hom.comp fbc.mor fab.mor, by rw [ring_hom.comp_assoc,fab.coincide,fbc.coincide] ⟩ } /- variables (L : fields.{u})(X Y Z :fieldsOver L) #check (ext_fields_has_cat_struct L).comp #check kLinearMor.mor (𝟙X) -/ instance ext_fields_cat (L : fields.{u}): category (fieldsOver L):= { to_category_struct := ext_fields_has_cat_struct L, id_comp' :=begin intros X Y fXY ,ext, dsimp [kLinearMor.mor], refl, end , comp_id':=begin intros X Y fXY ,ext, dsimp [kLinearMor.mor], refl, end , assoc' := begin intros W X Y Z f g h ,ext, dsimp [kLinearMor.mor], refl, end } /- structure subFields (F : Type u) [𝔽 :field F] : Type (u+1):= (k : Type u) (𝕜 :field k) (k2F : k →+* F ) -/ def AutGrp (L : fields.{u})(F : fieldsOver L):Type u := --F ≃ₐ[L] F F ≅ F --notation `Aut(`:30 F `/` L := AutGrp L F instance aut_grp_struct (L : fields.{u})(F : fieldsOver L) : group (AutGrp L F) := { mul:= λ a b, iso.trans b a, mul_assoc := begin intros a b c, ext, simp, end, one := iso.refl F, one_mul := begin intro a, ext,simp,refl, end, mul_one := begin intro a, ext,simp, refl, end, inv := iso.symm, mul_left_inv := category_theory.iso.self_symm_id } /- { mul:= alg_equiv.trans, mul_assoc := begin intros a b c, ext, simp, refl, end, one := alg_equiv.refl, one_mul := begin intro a, ext,simp, refl, end, mul_one := begin intro a, ext,simp, refl, end, inv := alg_equiv.symm, mul_left_inv := begin intro a,ext,simp,rw a.left_inv, end } -/ structure fieldsBetween (L : fields.{u})(F : fieldsOver L) :Type (u+1) := (k:fieldsOver L) (k2F : k ⟶ F) instance bet_fields_coe (L : fields.{u})(F : fieldsOver L) : has_coe (fieldsBetween L F) (fieldsOver L) := ⟨fieldsBetween.k⟩ variables (L : fields.{u})(F : fieldsOver L)(E : fieldsOver F.k) instance inbeding_coe : has_coe (fieldsOver F.k) (fieldsOver L ):= ⟨ λ E, {k:= E.k, L2k:= ring_hom.comp E.L2k F.L2k }⟩ lemma induce1 : (↑E: fieldsOver L).L2k = ring_hom.comp E.L2k F.L2k := begin ext,refl, end def base_change_functor : functor (fieldsOver F.k) (fieldsOver L) := { obj := λ E , ↑E, map := λ A B f , ⟨f.mor, begin cases f,dsimp,rw [induce1,induce1, ←ring_hom.comp_assoc ,f_coincide], end ⟩, map_id':= begin intro X, ext, refl, end, map_comp':= begin intros X Y Z f g, ext,refl, end } instance AutSubGrp_lift : has_lift (AutGrp F.k E) (AutGrp L ↑E) := ⟨functor.map_iso (base_change_functor L F)⟩ lemma lift_inj(g: AutGrp F.k E) : ⇑(g.hom.mor)=(↑ g : (AutGrp L ↑E)).hom.mor := begin ext, refl, end def AutSubGrp : monoid_hom (AutGrp F.k E) (AutGrp L ↑E) := { to_fun :=λ g, ↑g, map_one' := by refl, map_mul' := begin intros x y, ext, refl, end, } lemma AutSub_inj : function.injective ⇑(AutSubGrp L F E) := begin rw monoid_hom.injective_iff, intros a h, apply iso.ext, have h0 : ⇑(AutSubGrp L F E) = λa, ↑a := by refl, rw h0 at h, dsimp at h, have h1:= (lift_inj _ _ _ a), rw h at h1, symmetry, ext, rw h1,refl, end def normal_ext(F: fieldsOver L) : Prop := ∀ (K : fieldsOver L) (f g : F ⟶ K) , set.range f = set.range g
b7eac82214d039ef66c2ecb7c2abc219cf5ff046
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/array/lemmas.lean
8dc397ce65cfd7b32ce02b8ab873c6e07efffe26
[ "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
9,454
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import category.traversable.equiv data.vector2 universes u w namespace d_array variables {n : ℕ} {α : fin n → Type u} instance [∀ i, inhabited (α i)] : inhabited (d_array n α) := ⟨⟨λ _, default _⟩⟩ end d_array namespace array instance {n α} [inhabited α] : inhabited (array n α) := d_array.inhabited theorem to_list_of_heq {n₁ n₂ α} {a₁ : array n₁ α} {a₂ : array n₂ α} (hn : n₁ = n₂) (ha : a₁ == a₂) : a₁.to_list = a₂.to_list := by congr; assumption /- rev_list -/ section rev_list variables {n : ℕ} {α : Type u} {a : array n α} theorem rev_list_reverse_aux : ∀ i (h : i ≤ n) (t : list α), (a.iterate_aux (λ _, (::)) i h []).reverse_core t = a.rev_iterate_aux (λ _, (::)) i h t | 0 h t := rfl | (i+1) h t := rev_list_reverse_aux i _ _ @[simp] theorem rev_list_reverse : a.rev_list.reverse = a.to_list := rev_list_reverse_aux _ _ _ @[simp] theorem to_list_reverse : a.to_list.reverse = a.rev_list := by rw [←rev_list_reverse, list.reverse_reverse] end rev_list /- mem -/ section mem variables {n : ℕ} {α : Type u} {v : α} {a : array n α} theorem mem.def : v ∈ a ↔ ∃ i, a.read i = v := iff.rfl theorem mem_rev_list_aux : ∀ {i} (h : i ≤ n), (∃ (j : fin n), j.1 < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _, (::)) i h [] | 0 _ := ⟨λ ⟨i, n, _⟩, absurd n i.val.not_lt_zero, false.elim⟩ | (i+1) h := let IH := mem_rev_list_aux (le_of_lt h) in ⟨λ ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1) (λ ji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩) (λ je, by simp [d_array.iterate_aux]; apply or.inl; unfold read at e; have H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [←H, e]), λ m, begin simp [d_array.iterate_aux, list.mem] at m, cases m with e m', exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩, exact let ⟨j, ji, e⟩ := IH.2 m' in ⟨j, nat.le_succ_of_le ji, e⟩ end⟩ @[simp] theorem mem_rev_list : v ∈ a.rev_list ↔ v ∈ a := iff.symm $ iff.trans (exists_congr $ λ j, iff.symm $ show j.1 < n ∧ read a j = v ↔ read a j = v, from and_iff_right j.2) (mem_rev_list_aux _) @[simp] theorem mem_to_list : v ∈ a.to_list ↔ v ∈ a := by rw ←rev_list_reverse; exact list.mem_reverse.trans mem_rev_list end mem /- foldr -/ section foldr variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} theorem rev_list_foldr_aux : ∀ {i} (h : i ≤ n), (d_array.iterate_aux a (λ _, (::)) i h []).foldr f b = d_array.iterate_aux a (λ _, f) i h b | 0 h := rfl | (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _) theorem rev_list_foldr : a.rev_list.foldr f b = a.foldl b f := rev_list_foldr_aux _ end foldr /- foldl -/ section foldl variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α} theorem to_list_foldl : a.to_list.foldl f b = a.foldl b (function.swap f) := by rw [←rev_list_reverse, list.foldl_reverse, rev_list_foldr] end foldl /- length -/ section length variables {n : ℕ} {α : Type u} theorem rev_list_length_aux (a : array n α) (i h) : (a.iterate_aux (λ _, (::)) i h []).length = i := by induction i; simp [*, d_array.iterate_aux] @[simp] theorem rev_list_length (a : array n α) : a.rev_list.length = n := rev_list_length_aux a _ _ @[simp] theorem to_list_length (a : array n α) : a.to_list.length = n := by rw[←rev_list_reverse, list.length_reverse, rev_list_length] end length /- nth -/ section nth variables {n : ℕ} {α : Type u} {a : array n α} theorem to_list_nth_le_aux (i : ℕ) (ih : i < n) : ∀ j {jh t h'}, (∀ k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) → (a.rev_iterate_aux (λ _, (::)) j jh t).nth_le i h' = a.read ⟨i, ih⟩ | 0 _ _ _ al := al i _ $ zero_add _ | (j+1) jh t h' al := to_list_nth_le_aux j $ λ k tl hjk, show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from match k, hjk, tl with | 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end | k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simp [*]; cc) end theorem to_list_nth_le (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ := to_list_nth_le_aux _ _ _ (λ k tl, absurd tl k.not_lt_zero) @[simp] theorem to_list_nth_le' (a : array n α) (i : fin n) (h') : list.nth_le a.to_list i.1 h' = a.read i := by cases i; apply to_list_nth_le theorem to_list_nth {i v} : list.nth a.to_list i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v := begin rw list.nth_eq_some, have ll := to_list_length a, split; intro h; cases h with h e; subst v, { exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ }, { exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ } end theorem write_to_list {i v} : (a.write i v).to_list = a.to_list.update_nth i.1 v := list.ext_le (by simp) $ λ j h₁ h₂, begin have h₃ : j < n, {simpa using h₁}, rw [to_list_nth_le _ h₃], refine let ⟨_, e⟩ := list.nth_eq_some.1 _ in e.symm, by_cases ij : i.1 = j, { subst j, rw [show fin.mk i.val h₃ = i, from fin.eq_of_veq rfl, array.read_write, list.nth_update_nth_of_lt], simp [h₃] }, { rw [list.nth_update_nth_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 ⟨h₃, rfl⟩], exact fin.ne_of_vne ij } end end nth /- enum -/ section enum variables {n : ℕ} {α : Type u} {a : array n α} theorem mem_to_list_enum {i v} : (i, v) ∈ a.to_list.enum ↔ ∃ h, a.read ⟨i, h⟩ = v := by simp [list.mem_iff_nth, to_list_nth, and.comm, and.assoc, and.left_comm] end enum /- to_array -/ section to_array variables {n : ℕ} {α : Type u} @[simp] theorem to_list_to_array (a : array n α) : a.to_list.to_array == a := heq_of_heq_of_eq (@@eq.drec_on (λ m (e : a.to_list.length = m), (d_array.mk (λ v, a.to_list.nth_le v.1 v.2)) == (@d_array.mk m (λ _, α) $ λ v, a.to_list.nth_le v.1 $ e.symm ▸ v.2)) a.to_list_length heq.rfl) $ d_array.ext $ λ ⟨i, h⟩, to_list_nth_le i h _ @[simp] theorem to_array_to_list (l : list α) : l.to_array.to_list = l := list.ext_le (to_list_length _) $ λ n h1 h2, to_list_nth_le _ _ _ end to_array /- push_back -/ section push_back variables {n : ℕ} {α : Type u} {v : α} {a : array n α} lemma push_back_rev_list_aux : ∀ i h h', d_array.iterate_aux (a.push_back v) (λ _, (::)) i h [] = d_array.iterate_aux a (λ _, (::)) i h' [] | 0 h h' := rfl | (i+1) h h' := begin simp [d_array.iterate_aux], refine ⟨_, push_back_rev_list_aux _ _ _⟩, dsimp [read, d_array.read, push_back], rw [dif_neg], refl, exact ne_of_lt h', end @[simp] theorem push_back_rev_list : (a.push_back v).rev_list = v :: a.rev_list := begin unfold push_back rev_list foldl iterate d_array.iterate, dsimp [d_array.iterate_aux, read, d_array.read, push_back], rw [dif_pos (eq.refl n)], apply congr_arg, apply push_back_rev_list_aux end @[simp] theorem push_back_to_list : (a.push_back v).to_list = a.to_list ++ [v] := by rw [←rev_list_reverse, ←rev_list_reverse, push_back_rev_list, list.reverse_cons] end push_back /- foreach -/ section foreach variables {n : ℕ} {α : Type u} {i : fin n} {f : fin n → α → α} {a : array n α} theorem read_foreach_aux : ∀ i h (b : array n α) (j : fin n), j.1 < i → (d_array.iterate_aux a (λ i v a', write a' i (f i v)) i h b).read j = f j (a.read j) | 0 hi a ⟨j, hj⟩ ji := absurd ji (nat.not_lt_zero _) | (i+1) hi a ⟨j, hj⟩ ji := begin dsimp [d_array.iterate_aux], dsimp at ji, by_cases e : (⟨i, hi⟩ : fin _) = ⟨j, hj⟩, { rw [e], simp, refl }, { rw [read_write_of_ne _ _ e, read_foreach_aux _ _ _ ⟨j, hj⟩], exact (lt_or_eq_of_le (nat.le_of_lt_succ ji)).resolve_right (ne.symm $ mt (@fin.eq_of_veq _ ⟨i, hi⟩ ⟨j, hj⟩) e) } end @[simp] theorem read_foreach : (foreach a f).read i = f i (a.read i) := read_foreach_aux _ _ _ _ i.2 end foreach /- map -/ section map variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α} {a : array n α} theorem read_map : (map f a).read i = f (a.read i) := read_foreach end map /- map₂ -/ section map₂ variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ a₂ : array n α} @[simp] theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) := read_foreach end map₂ end array namespace equiv def d_array_equiv_fin {n : ℕ} (α : fin n → Type*) : d_array n α ≃ (∀ i, α i) := ⟨d_array.read, d_array.mk, λ ⟨f⟩, rfl, λ f, rfl⟩ def array_equiv_fin (n : ℕ) (α : Type*) : array n α ≃ (fin n → α) := d_array_equiv_fin _ def vector_equiv_fin (α : Type*) (n : ℕ) : vector α n ≃ (fin n → α) := ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩ def vector_equiv_array (α : Type*) (n : ℕ) : vector α n ≃ array n α := (vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm end equiv namespace array open function variable {n : ℕ} instance : traversable (array n) := @equiv.traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ instance : is_lawful_traversable (array n) := @equiv.is_lawful_traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ _ end array
1e29326dc77857e46c876a480a413ff58202d3e6
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/fintype/card.lean
683895bab7a33a2f768d0aa7611483372f5594ec
[ "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
2,043
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Haitao Zhang Cardinality for finite types. -/ import .basic data.list data.finset.card open eq.ops nat function list finset namespace fintype definition card [reducible] (A : Type) [finA : fintype A] := finset.card (@finset.univ A _) lemma card_eq_card_image_of_inj {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {B : Type} [finB : fintype B] [deceqB : decidable_eq B] {f : A → B} : injective f → finset.card (image f univ) = card A := assume Pinj, card_image_eq_of_inj_on (to_set_univ⁻¹ ▸ (iff.mp !set.injective_iff_inj_on_univ Pinj)) -- General version of the pigeonhole principle. See also data.less_than. lemma card_le_of_inj (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (B : Type) [finB : fintype B] [deceqB : decidable_eq B] : (∃ f : A → B, injective f) → card A ≤ card B := assume Pex, obtain f Pinj, from Pex, assert Pinj_on_univ : _, from iff.mp !set.injective_iff_inj_on_univ Pinj, assert Pinj_ts : set.inj_on f (ts univ), from to_set_univ⁻¹ ▸ Pinj_on_univ, assert Psub : (image f univ) ⊆ univ, from !subset_univ, finset.card_le_of_inj_on univ univ (exists.intro f (and.intro Pinj_ts Psub)) -- used to prove that inj ∧ eq card => surj lemma univ_of_card_eq_univ {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {s : finset A} : finset.card s = card A → s = univ := assume Pcardeq, ext (take a, assert D : decidable (a ∈ s), from decidable_mem a s, begin apply iff.intro, intro ain, apply mem_univ, intro ain, cases D with Pin Pnin, exact Pin, assert Pplus1 : finset.card (insert a s) = finset.card s + 1, exact card_insert_of_not_mem Pnin, rewrite Pcardeq at Pplus1, assert Ple : finset.card (insert a s) ≤ card A, apply card_le_card_of_subset, apply subset_univ, rewrite Pplus1 at Ple, exact false.elim (not_succ_le_self Ple) end) end fintype
912d6543a53819c26d313a02fc6934d372e1c09a
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/tactic/lint.lean
a643d13dbb9be7d9a6261a1d1430a682bfa15095
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
21,550
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis -/ import tactic.core /-! # lint command This file defines the following user commands to spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) The following linters are run by default: 1. `unused_arguments` checks for unused arguments in declarations. 2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma. 3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration. 4. `illegal_constant` checks whether ≥/> is used in the declaration. 5. `instance_priority` checks that instances that always apply have priority below default. 6. `doc_blame` checks for missing doc strings on definitions and constants. Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems. This is not run by default. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output of passing checks. A silent lint will fail if any test fails. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint]` to a declaration omits it from all linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ universe variable u open expr tactic native reserve notation `#lint` reserve notation `#lint_mathlib` reserve notation `#lint_all` reserve notation `#list_linters` run_cmd tactic.skip -- apparently doc strings can't come directly after `reserve notation` /-- Defines the user attribute `nolint` for skipping `#lint` -/ @[user_attribute] meta def nolint_attr : user_attribute := { name := "nolint", descr := "Do not report this declaration in any of the tests of `#lint`" } attribute [nolint] imp_intro classical.dec classical.dec_pred classical.dec_rel classical.dec_eq /-- A linting test for the `#lint` command. `test` defines a test to perform on every declaration. It should never fail. Returning `none` signifies a passing test. Returning `some msg` reports a failing test with error `msg`. `no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed when at least one test is positive. If `is_fast` is false, this test will be omitted from `#lint-`. -/ meta structure linter := (test : declaration → tactic (option string)) (no_errors_found : string) (errors_found : string) (is_fast : bool := tt) /-- Takes a list of names that resolve to declarations of type `linter`, and produces a list of linters. -/ meta def get_linters (l : list name) : tactic (list linter) := l.mmap (λ n, mk_const n >>= eval_expr linter <|> fail format!"invalid linter: {n}") /-- Defines the user attribute `linter` for adding a linter to the default set. Linters should be defined in the `linter` namespace. A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace) when used in `#lint`. -/ @[user_attribute] meta def linter_attr : user_attribute unit unit := { name := "linter", descr := "Use this declaration as a linting test in #lint", after_set := some $ λ nm _ _, mk_const nm >>= infer_type >>= unify `(linter) } setup_tactic_parser universe variable v /-- Find all declarations in `l` where tac returns `some x` and list them. -/ meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d /-- Find all declarations in `l` where tac returns `some x` and sort the resulting list by file name. -/ meta def fold_over_with_cond_sorted {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (string × list (declaration × α))) := do e ← get_env, ds ← fold_over_with_cond l tac, let ds₂ := rb_lmap.of_list (ds.map (λ x, ((e.decl_olean x.1.to_name).iget, x))), return $ ds₂.to_list /-- Make the output of `fold_over_with_cond` printable, in the following form: `#print <name> <open multiline comment> <elt of α> <close multiline comment>` -/ meta def print_decls {α} [has_to_format α] (ds : list (declaration × α)) : format := ds.foldl (λ f x, f ++ "\n" ++ to_fmt "#print " ++ to_fmt x.1.to_name ++ " /- " ++ to_fmt x.2 ++ " -/") format.nil /-- Make the output of `fold_over_with_cond_sorted` printable, with the file path + name inserted.-/ meta def print_decls_sorted {α} [has_to_format α] (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt x.1 ++ print_decls x.2) format.nil /-- Same as `print_decls_sorted`, but removing the first `n` characters from the string. Useful for omitting the mathlib directory from the output. -/ meta def print_decls_sorted_mathlib {α} [has_to_format α] (n : ℕ) (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt (x.1.popn n) ++ print_decls x.2) format.nil /-- Auxilliary definition for `check_unused_arguments` -/ meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e := if n > n_max then l else if ¬ is_lambda e ∧ ¬ is_pi e then l else let b := e.binding_body in let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b /-- Check which arguments of a declaration are not used. Prints a list of natural numbers corresponding to which arguments are not used (e.g. this outputs [1, 4] if the first and fourth arguments are unused). Checks both the type and the value of `d` for whether the argument is used (in rare cases an argument is used in the type but not in the value). We return [] if the declaration was automatically generated. We print arguments that are larger than the arity of the type of the declaration (without unfolding definitions). -/ meta def check_unused_arguments (d : declaration) : option (list ℕ) := let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in if l = [] then none else let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in (l.filter $ λ n, n ∈ l2).reverse /-- Check for unused arguments, and print them with their position, variable name, type and whether the argument is a duplicate. See also `check_unused_arguments`. This tactic additionally filters out all unused arguments of type `parse _` -/ meta def unused_arguments (d : declaration) : tactic (option string) := do let ns := check_unused_arguments d, if ¬ ns.is_some then return none else do let ns := ns.iget, (ds, _) ← get_pi_binders d.type, let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)), let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []), if ns = [] then return none else do ds' ← ds.mmap pp, ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++ (if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b), return $ some $ ns.to_string_aux tt /-- A linter object for checking for unused arguments. This is in the default linter set. -/ @[linter, priority 1500] meta def linter.unused_arguments : linter := { test := unused_arguments, no_errors_found := "No unused arguments", errors_found := "UNUSED ARGUMENTS" } /-- Checks whether the correct declaration constructor (definition or theorem) by comparing it to its sort. Instances will not be printed. -/ /- This test is not very quick: maybe we can speed-up testing that something is a proposition? This takes almost all of the execution time. -/ meta def incorrect_def_lemma (d : declaration) : tactic (option string) := if d.is_constant ∨ d.is_axiom then return none else do is_instance_d ← is_instance d.to_name, if is_instance_d then return none else do -- the following seems to be a little quicker than `is_prop d.type`. expr.sort n ← infer_type d.type, return $ if d.is_theorem ↔ n = level.zero then none else if (d.is_definition : bool) then "is a def, should be a lemma/theorem" else "is a lemma/theorem, should be a def" /-- A linter for checking whether the correct declaration constructor (definition or theorem) has been used. -/ @[linter, priority 1490] meta def linter.def_lemma : linter := { test := incorrect_def_lemma, no_errors_found := "All declarations correctly marked as def/lemma", errors_found := "INCORRECT DEF/LEMMA" } /-- Checks whether a declaration has a namespace twice consecutively in its name -/ meta def dup_namespace (d : declaration) : tactic (option string) := is_instance d.to_name >>= λ is_inst, return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in some $ "The namespace `" ++ s ++ "` is duplicated in the name" /-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/ @[linter, priority 1480] meta def linter.dup_namespace : linter := { test := dup_namespace, no_errors_found := "No declarations have a duplicate namespace", errors_found := "DUPLICATED NAMESPACES IN NAME" } /-- Checks whether a `>`/`≥` is used in the statement of `d`. -/ -- TODO: the commented out code also checks for classicality in statements, but needs fixing -- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _ -- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := -- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧ -- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge]) -- then -- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, `classical.dec_eq], -- illegal2 := [`gt, `ge], -- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)), -- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in -- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++ -- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++ -- (if occur2 = [] then "" else " Use ≤/< instead.") -- else none meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := return $ let illegal := [`gt, `ge] in if d.type.contains_constant (λ n, n ∈ illegal) then some "the type contains ≥/>. Use ≤/< instead." else none /-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/ @[linter, priority 1470] meta def linter.illegal_constants : linter := { test := illegal_constants_in_statement, no_errors_found := "No illegal constants in declarations", errors_found := "ILLEGAL CONSTANTS IN DECLARATIONS", is_fast := ff } /-- checks whether an instance that always applies has priority ≥ 1000. -/ meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do prio ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "" else return none /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter, priority 1460] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES.\n The following instances always apply, and therefore should have a priority < 1000" } /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_defn : declaration → tactic (option string) | (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string" | (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string" | _ := return none /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_thm : declaration → tactic (option string) | (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string" | _ := return none /-- A linter for checking definition doc strings -/ @[linter, priority 1450] meta def linter.doc_blame : linter := { test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none), no_errors_found := "No definitions are missing documentation.", errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS" } /-- A linter for checking theorem doc strings. This is not in the default linter set. -/ meta def linter.doc_blame_thm : linter := { test := doc_blame_report_thm, no_errors_found := "No theorems are missing documentation.", errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS", is_fast := ff } /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list linter) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (λ l, l.is_fast), list.append default <$> get_linters extra /-- If `verbose` is true, return `old ++ new`, else return `old`. -/ private meta def append_when (verbose : bool) (old new : format) : format := cond verbose (old ++ new) old /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `printer` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. -/ meta def lint_aux (l : list declaration) (printer : (declaration → tactic (option string)) → tactic format) (where_desc : string) (slow verbose : bool) (checks : list linter) : tactic format := do let s : format := append_when verbose format.nil "/- Note: This command is still in development. -/\n", let s := append_when verbose s format!"/- Checking {l.length} declarations {where_desc} -/\n\n", s ← checks.mfoldl (λ s ⟨tac, ok_string, warning_string, _⟩, show tactic format, from do f ← printer tac, if f.is_nil then return $ append_when verbose s format!"/- OK: {ok_string}. -/\n" else return $ s ++ format!"/- {warning_string}: -/" ++ f ++ "\n\n") s, return $ if slow then s else append_when verbose s "/- (slow tests skipped) -/\n" /-- Return the message printed by `#lint`. -/ meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic format := do checks ← get_checks slow extra use_only, e ← get_env, l ← e.mfilter (λ d, if e.in_current_file' d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), lint_aux l (λ t, print_decls <$> fold_over_with_cond l t) "in the current file" slow verbose checks /-- Return the message printed by `#lint_mathlib`. -/ meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic format := do checks ← get_checks slow extra use_only, e ← get_env, ml ← get_mathlib_dir, /- note: we don't separate out some of these tests in `lint_aux` because that causes a performance hit. That is also the reason for the current formulation using if then else. -/ l ← e.mfilter (λ d, if e.is_prefix_of_file ml d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), let ml' := ml.length, lint_aux l (λ t, print_decls_sorted_mathlib ml' <$> fold_over_with_cond_sorted l t) "in mathlib (only in imported files)" slow verbose checks /-- Return the message printed by `#lint_all`. -/ meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic format := do checks ← get_checks slow extra use_only, e ← get_env, l ← e.mfilter (λ d, if ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), lint_aux l (λ t, print_decls_sorted <$> fold_over_with_cond_sorted l t) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ private meta def parse_lint_additions : parser (bool × list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*) /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic format) : parser unit := do silent ← optional (tk "-"), fast_only ← optional (tk "*"), silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *- (use_only, extra) ← parse_lint_additions, s ← scope fast_only.is_none silent.is_none extra use_only, when (¬ s.is_nil) $ do trace s, when silent.is_some $ fail "Linting did not succeed" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := lint_cmd_aux @lint_mathlib /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ λ dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ λ n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" /-- Use `lint` as a hole command. Note: In a large file, there might be some delay between choosing the option and the information appearing -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := λ es, do s ← lint, return [(s.to_string,"")] }
48c37072e42f55f2e5851811542f93688ad89f8b
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/order/zorn.lean
90f7f6ed3ad149d312740921b07ce65df2940657
[ "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
11,957
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import data.set.lattice noncomputable theory universes u open set classical local attribute [instance] prop_decidable namespace zorn section chain parameters {α : Type u} (r : α → α → Prop) local infix ` ≺ `:50 := r /-- A chain is a subset `c` satisfying `x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/ def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) parameters {r} theorem chain.total_of_refl [is_refl α r] {c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) : x ≺ y ∨ y ≺ x := if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e theorem chain.directed [is_refl α r] {c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) : ∃ z, z ∈ c ∧ x ≺ z ∧ y ≺ z := match H.total_of_refl hx hy with | or.inl h := ⟨y, hy, h, refl _⟩ | or.inr h := ⟨x, hx, refl _, h⟩ end theorem chain.mono {c c'} : c' ⊆ c → chain c → chain c' := pairwise_on.mono theorem chain.directed_on [is_refl α r] {c} (H : chain c) : directed_on (≺) c := λ x xc y yc, let ⟨z, hz, h⟩ := H.directed xc yc in ⟨z, hz, h⟩ theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) def super_chain (c₁ c₂ : set α) := chain c₂ ∧ c₁ ⊂ c₂ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') def succ_chain (c : set α) := if h : ∃c', chain c ∧ super_chain c c' then some h else c theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂, cases hc₂.neg_resolve_left hc₁ with c' hc', exact succ_spec ⟨c', hc₁, hc'⟩ end theorem succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) theorem chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case _root_.zorn.chain_closure.succ : c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case _root_.zorn.chain_closure.union : s hs ih { refine (classical.or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case _root_.zorn.chain_closure.succ : c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case _root_.zorn.chain_closure.union : s hs ih { apply or.imp_left (assume h', subset.antisymm h' h), apply classical.by_contradiction, simp [not_or_distrib, sUnion_subset_iff, classical.not_forall], intros c₃ hc₃ h₁ h₂, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₁ $ h' ▸ subset.refl _) }, { exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₁ $ subset.trans succ_increasing h) } } end theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case _root_.zorn.chain_closure.succ : c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case _root_.zorn.chain_closure.union : s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ theorem chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case _root_.zorn.chain_closure.succ : c hc h { exact chain_succ h }, case _root_.zorn.chain_closure.union : s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ chain_closure), have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := this in have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ theorem zorn (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @zorn α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α) (ih : ∀ c ⊆ s, chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) : ∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m := let ⟨⟨m, hms, hxm⟩, h⟩ := @zorn_partial_order {m // m ∈ s ∧ x ≤ m} _ (λ c hc, classical.by_cases (assume hce : c = ∅, hce.symm ▸ ⟨⟨x, hxs, le_refl _⟩, λ _, false.elim⟩) (assume hce : c ≠ ∅, let ⟨m, hmc⟩ := set.exists_mem_of_ne_empty hce in let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (image_subset_iff.2 $ λ z hzc, z.2.1) (by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq; exact hc p hpc q hqc (mt (by rintro rfl; refl) hpq)) m.1 (mem_image_of_mem _ hmc) in ⟨⟨ub, hubs, le_trans m.2.2 $ hub m.1 $ mem_image_of_mem _ hmc⟩, λ a hac, hub a.1 ⟨a, hac, rfl⟩⟩)) in ⟨m, hms, hxm, λ z hzs hmz, congr_arg subtype.val $ h ⟨z, hzs, le_trans hxm hmz⟩ hmz⟩ theorem zorn_subset {α : Type u} (S : set (set α)) (h : ∀c ⊆ S, chain (⊆) c → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) : ∃ m ∈ S, ∀a ∈ S, m ⊆ a → a = m := begin letI : partial_order S := partial_order.lift subtype.val (λ _ _, subtype.eq'), have : ∀c:set S, @chain S (≤) c → ∃ub, ∀a∈c, a ≤ ub, { intros c hc, rcases h (subtype.val '' c) (image_subset_iff.2 _) _ with ⟨s, sS, hs⟩, { exact ⟨⟨s, sS⟩, λ ⟨x, hx⟩ H, hs _ (mem_image_of_mem _ H)⟩ }, { rintro ⟨x, hx⟩ _, exact hx }, { rintro _ ⟨x, cx, rfl⟩ _ ⟨y, cy, rfl⟩ xy, exact hc x cx y cy (mt (congr_arg _) xy) } }, rcases zorn_partial_order this with ⟨⟨m, mS⟩, hm⟩, exact ⟨m, mS, λ a aS ha, congr_arg subtype.val (hm ⟨a, aS⟩ ha)⟩ end theorem zorn_subset₀ {α : Type u} (S : set (set α)) (H : ∀c ⊆ S, chain (⊆) c → c ≠ ∅ → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) : ∃ m ∈ S, x ⊆ m ∧ ∀a ∈ S, m ⊆ a → a = m := begin let T := {s ∈ S | x ⊆ s}, rcases zorn_subset T _ with ⟨m, ⟨mS, mx⟩, hm⟩, { exact ⟨m, mS, mx, λ a ha ha', hm a ⟨ha, subset.trans mx ha'⟩ ha'⟩ }, { intros c cT hc, by_cases c0 : c = ∅, { rw c0, exact ⟨x, ⟨hx, subset.refl _⟩, λ _, false.elim⟩ }, { rcases H _ (subset.trans cT (sep_subset _ _)) hc c0 with ⟨ub, us, h⟩, refine ⟨ub, ⟨us, _⟩, h⟩, rcases ne_empty_iff_exists_mem.1 c0 with ⟨s, hs⟩, exact subset.trans (cT hs).2 (h _ hs) } } end theorem chain.total {α : Type u} [preorder α] {c} (H : @chain α (≤) c) : ∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x := @chain.total_of_refl _ (≤) ⟨le_refl⟩ _ H end zorn
887f2cd71e65f7bc082402d581b98c2a5b510375
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_2209.lean
a5f61a58f6426f3c7176ad6240f8a609094b1b0c
[]
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
131
lean
import data.real.basic -- BEGIN example : (λ x y : ℝ, (x + y)^2) = (λ x y : ℝ, x^2 + 2*x*y + y^2) := by { ext, ring } -- END
dd3f12fd90b583d240a7b0d88d3f6a17ca58a596
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/indicator_function.lean
0214d2e6582ca22a7252bdb102f98521cd67b31e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,353
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import analysis.normed.group.basic import algebra.indicator_function /-! # Indicator function and norm This file contains a few simple lemmas about `set.indicator` and `norm`. ## Tags indicator, norm -/ variables {α E : Type*} [seminormed_add_comm_group E] {s t : set α} (f : α → E) (a : α) open set lemma norm_indicator_eq_indicator_norm : ‖indicator s f a‖ = indicator s (λa, ‖f a‖) a := flip congr_fun a (indicator_comp_of_zero norm_zero).symm lemma nnnorm_indicator_eq_indicator_nnnorm : ‖indicator s f a‖₊ = indicator s (λa, ‖f a‖₊) a := flip congr_fun a (indicator_comp_of_zero nnnorm_zero).symm lemma norm_indicator_le_of_subset (h : s ⊆ t) (f : α → E) (a : α) : ‖indicator s f a‖ ≤ ‖indicator t f a‖ := begin simp only [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset ‹_› (λ _, norm_nonneg _) _ end lemma indicator_norm_le_norm_self : indicator s (λa, ‖f a‖) a ≤ ‖f a‖ := indicator_le_self' (λ _ _, norm_nonneg _) a lemma norm_indicator_le_norm_self : ‖indicator s f a‖ ≤ ‖f a‖ := by { rw norm_indicator_eq_indicator_norm, apply indicator_norm_le_norm_self }
7066f6be5203a7dfd1234409ba894f16dbd8341d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/category/DistLat.lean
c4633bbbe1434cc2a3138d8bb5429e2cd192b3fc
[ "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,347
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 order.category.Lat /-! # The category of distributive lattices > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `DistLat`, the category of distributive lattices. Note that [`DistLat`](https://ncatlab.org/nlab/show/DistLat) in the literature doesn't always correspond to `DistLat` as we don't require bottom or top elements. Instead, this `DistLat` corresponds to `BddDistLat`. -/ universes u open category_theory /-- The category of distributive lattices. -/ def DistLat := bundled distrib_lattice namespace DistLat instance : has_coe_to_sort DistLat Type* := bundled.has_coe_to_sort instance (X : DistLat) : distrib_lattice X := X.str /-- Construct a bundled `DistLat` from a `distrib_lattice` underlying type and typeclass. -/ def of (α : Type*) [distrib_lattice α] : DistLat := bundled.of α @[simp] lemma coe_of (α : Type*) [distrib_lattice α] : ↥(of α) = α := rfl instance : inhabited DistLat := ⟨of punit⟩ instance : bundled_hom.parent_projection @distrib_lattice.to_lattice := ⟨⟩ attribute [derive [large_category, concrete_category]] DistLat instance has_forget_to_Lat : has_forget₂ DistLat Lat := bundled_hom.forget₂ _ _ /-- Constructs an equivalence between distributive lattices from an order isomorphism between them. -/ @[simps] def iso.mk {α β : DistLat.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- `order_dual` as a functor. -/ @[simps] def dual : DistLat ⥤ DistLat := { obj := λ X, of Xᵒᵈ, map := λ X Y, lattice_hom.dual } /-- The equivalence between `DistLat` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : DistLat ≌ DistLat := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end DistLat lemma DistLat_dual_comp_forget_to_Lat : DistLat.dual ⋙ forget₂ DistLat Lat = forget₂ DistLat Lat ⋙ Lat.dual := rfl
5b8946fd7ea67d3476f44b60f0174ebf9c239736
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/homotopy/product.lean
06b9d0449ed710671158ef7f04f4340bdc33dc19
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,334
lean
/- Copyright (c) 2021 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import topology.constructions import topology.homotopy.path /-! # Product of homotopies In this file, we introduce definitions for the product of homotopies. We show that the products of relative homotopies are still relative homotopies. Finally, we specialize to the case of path homotopies, and provide the definition for the product of path classes. We show various lemmas associated with these products, such as the fact that path products commute with path composition, and that projection is the inverse of products. ## Definitions ### General homotopies - `continuous_map.homotopy.pi homotopies`: Let f and g be a family of functions indexed on I, such that for each i ∈ I, fᵢ and gᵢ are maps from A to Xᵢ. Let `homotopies` be a family of homotopies from fᵢ to gᵢ for each i. Then `homotopy.pi homotopies` is the canonical homotopy from ∏ f to ∏ g, where ∏ f is the product map from A to Πi, Xᵢ, and similarly for ∏ g. - `continuous_map.homotopy_rel.pi homotopies`: Same as `continuous_map.homotopy.pi`, but all homotopies are done relative to some set S ⊆ A. - `continuous_map.homotopy.prod F G` is the product of homotopies F and G, where F is a homotopy between f₀ and f₁, G is a homotopy between g₀ and g₁. The result F × G is a homotopy between (f₀ × g₀) and (f₁ × g₁). Again, all homotopies are done relative to S. - `continuous_map.homotopy_rel.prod F G`: Same as `continuous_map.homotopy.prod`, but all homotopies are done relative to some set S ⊆ A. ### Path products - `path.homotopic.pi` The product of a family of path classes, where a path class is an equivalence class of paths up to path homotopy. - `path.homotopic.prod` The product of two path classes. -/ noncomputable theory namespace continuous_map open continuous_map section pi variables {I A : Type*} {X : I → Type*} [Π i, topological_space (X i)] [topological_space A] {f g : Π i, C(A, X i)} {S : set A} /-- The product homotopy of `homotopies` between functions `f` and `g` -/ @[simps] def homotopy.pi (homotopies : Π i, homotopy (f i) (g i)) : homotopy (pi f) (pi g) := { to_fun := λ t i, homotopies i t, map_zero_left' := λ t, by { ext i, simp only [pi_eval, homotopy.apply_zero] }, map_one_left' := λ t, by { ext i, simp only [pi_eval, homotopy.apply_one] } } /-- The relative product homotopy of `homotopies` between functions `f` and `g` -/ @[simps] def homotopy_rel.pi (homotopies : Π i : I, homotopy_rel (f i) (g i) S) : homotopy_rel (pi f) (pi g) S := { prop' := begin intros t x hx, dsimp only [coe_mk, pi_eval, to_fun_eq_coe, homotopy_with.coe_to_continuous_map], simp only [function.funext_iff, ← forall_and_distrib], intro i, exact (homotopies i).prop' t x hx, end, ..(homotopy.pi (λ i, (homotopies i).to_homotopy)), } end pi section prod variables {α β : Type*} [topological_space α] [topological_space β] {A : Type*} [topological_space A] {f₀ f₁ : C(A, α)} {g₀ g₁ : C(A, β)} {S : set A} /-- The product of homotopies `F` and `G`, where `F` takes `f₀` to `f₁` and `G` takes `g₀` to `g₁` -/ @[simps] def homotopy.prod (F : homotopy f₀ f₁) (G : homotopy g₀ g₁) : homotopy (prod_mk f₀ g₀) (prod_mk f₁ g₁) := { to_fun := λ t, (F t, G t), map_zero_left' := λ x, by simp only [prod_eval, homotopy.apply_zero], map_one_left' := λ x, by simp only [prod_eval, homotopy.apply_one] } /-- The relative product of homotopies `F` and `G`, where `F` takes `f₀` to `f₁` and `G` takes `g₀` to `g₁` -/ @[simps] def homotopy_rel.prod (F : homotopy_rel f₀ f₁ S) (G : homotopy_rel g₀ g₁ S) : homotopy_rel (prod_mk f₀ g₀) (prod_mk f₁ g₁) S := { prop' := begin intros t x hx, have hF := F.prop' t x hx, have hG := G.prop' t x hx, simp only [coe_mk, prod_eval, prod.mk.inj_iff, homotopy.prod] at hF hG ⊢, exact ⟨⟨hF.1, hG.1⟩, ⟨hF.2, hG.2⟩⟩, end, ..(homotopy.prod F.to_homotopy G.to_homotopy) } end prod end continuous_map namespace path.homotopic local attribute [instance] path.homotopic.setoid local infix ` ⬝ `:70 := quotient.comp section pi variables {ι : Type*} {X : ι → Type*} [∀ i, topological_space (X i)] {as bs cs : Π i, X i} /-- The product of a family of path homotopies. This is just a specialization of `homotopy_rel` -/ def pi_homotopy (γ₀ γ₁ : Π i, path (as i) (bs i)) (H : ∀ i, path.homotopy (γ₀ i) (γ₁ i)) : path.homotopy (path.pi γ₀) (path.pi γ₁) := continuous_map.homotopy_rel.pi H /-- The product of a family of path homotopy classes -/ def pi (γ : Π i, path.homotopic.quotient (as i) (bs i)) : path.homotopic.quotient as bs := (quotient.map path.pi (λ x y hxy, nonempty.map (pi_homotopy x y) (classical.nonempty_pi.mpr hxy))) (quotient.choice γ) lemma pi_lift (γ : Π i, path (as i) (bs i)) : path.homotopic.pi (λ i, ⟦γ i⟧) = ⟦path.pi γ⟧ := by { unfold pi, simp, } /-- Composition and products commute. This is `path.trans_pi_eq_pi_trans` descended to path homotopy classes -/ lemma comp_pi_eq_pi_comp (γ₀ : Π i, path.homotopic.quotient (as i) (bs i)) (γ₁ : Π i, path.homotopic.quotient (bs i) (cs i)) : pi γ₀ ⬝ pi γ₁ = pi (λ i, γ₀ i ⬝ γ₁ i) := begin apply quotient.induction_on_pi γ₁, apply quotient.induction_on_pi γ₀, intros, simp only [pi_lift], rw [← path.homotopic.comp_lift, path.trans_pi_eq_pi_trans, ← pi_lift], refl, end /-- Abbreviation for projection onto the ith coordinate -/ @[reducible] def proj (i : ι) (p : path.homotopic.quotient as bs) : path.homotopic.quotient (as i) (bs i) := p.map_fn ⟨_, continuous_apply i⟩ /-- Lemmas showing projection is the inverse of pi -/ @[simp] lemma proj_pi (i : ι) (paths : Π i, path.homotopic.quotient (as i) (bs i)) : proj i (pi paths) = paths i := begin apply quotient.induction_on_pi paths, intro, unfold proj, rw [pi_lift, ← path.homotopic.map_lift], congr, ext, refl, end @[simp] lemma pi_proj (p : path.homotopic.quotient as bs) : pi (λ i, proj i p) = p := begin apply quotient.induction_on p, intro, unfold proj, simp_rw ← path.homotopic.map_lift, rw pi_lift, congr, ext, refl, end end pi section prod variables {α β : Type*} [topological_space α] [topological_space β] {a₁ a₂ a₃ : α} {b₁ b₂ b₃ : β} {p₁ p₁' : path a₁ a₂} {p₂ p₂' : path b₁ b₂} (q₁ : path.homotopic.quotient a₁ a₂) (q₂ : path.homotopic.quotient b₁ b₂) /-- The product of homotopies h₁ and h₂. This is `homotopy_rel.prod` specialized for path homotopies. -/ def prod_homotopy (h₁ : path.homotopy p₁ p₁') (h₂ : path.homotopy p₂ p₂') : path.homotopy (p₁.prod p₂) (p₁'.prod p₂') := continuous_map.homotopy_rel.prod h₁ h₂ /-- The product of path classes q₁ and q₂. This is `path.prod` descended to the quotient -/ def prod (q₁ : path.homotopic.quotient a₁ a₂) (q₂ : path.homotopic.quotient b₁ b₂) : path.homotopic.quotient (a₁, b₁) (a₂, b₂) := quotient.map₂ path.prod (λ p₁ p₁' h₁ p₂ p₂' h₂, nonempty.map2 prod_homotopy h₁ h₂) q₁ q₂ variables (p₁ p₁' p₂ p₂') lemma prod_lift : prod ⟦p₁⟧ ⟦p₂⟧ = ⟦p₁.prod p₂⟧ := rfl variables (r₁ : path.homotopic.quotient a₂ a₃) (r₂ : path.homotopic.quotient b₂ b₃) /-- Products commute with path composition. This is `trans_prod_eq_prod_trans` descended to the quotient.-/ lemma comp_prod_eq_prod_comp : (prod q₁ q₂) ⬝ (prod r₁ r₂) = prod (q₁ ⬝ r₁) (q₂ ⬝ r₂) := begin apply quotient.induction_on₂ q₁ q₂, apply quotient.induction_on₂ r₁ r₂, intros, simp only [prod_lift, ← path.homotopic.comp_lift, path.trans_prod_eq_prod_trans], end variables {c₁ c₂ : α × β} /-- Abbreviation for projection onto the left coordinate of a path class -/ @[reducible] def proj_left (p : path.homotopic.quotient c₁ c₂) : path.homotopic.quotient c₁.1 c₂.1 := p.map_fn ⟨_, continuous_fst⟩ /-- Abbreviation for projection onto the right coordinate of a path class -/ @[reducible] def proj_right (p : path.homotopic.quotient c₁ c₂) : path.homotopic.quotient c₁.2 c₂.2 := p.map_fn ⟨_, continuous_snd⟩ /-- Lemmas showing projection is the inverse of product -/ @[simp] lemma proj_left_prod : proj_left (prod q₁ q₂) = q₁ := begin apply quotient.induction_on₂ q₁ q₂, intros p₁ p₂, unfold proj_left, rw [prod_lift, ← path.homotopic.map_lift], congr, ext, refl, end @[simp] lemma proj_right_prod : proj_right (prod q₁ q₂) = q₂ := begin apply quotient.induction_on₂ q₁ q₂, intros p₁ p₂, unfold proj_right, rw [prod_lift, ← path.homotopic.map_lift], congr, ext, refl, end @[simp] lemma prod_proj_left_proj_right (p : path.homotopic.quotient (a₁, b₁) (a₂, b₂)) : prod (proj_left p) (proj_right p) = p := begin apply quotient.induction_on p, intro p', unfold proj_left, unfold proj_right, simp only [← path.homotopic.map_lift, prod_lift], congr, ext; refl, end end prod end path.homotopic
92f61f07956374bcc749584712e25d6494c65d0c
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/fintype/intervals.lean
201ef15f96ed2af3ea87a24fab7bc9dda27f84e8
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
909
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.set.intervals import data.set.finite import data.fintype import data.pnat.intervals /-! # fintype instances for intervals We provide `fintype` instances for `Ico l u`, for `l u : ℕ`, and for `l u : ℤ`. -/ namespace set instance Ico_ℕ_fintype (l u : ℕ) : fintype (Ico l u) := fintype.of_finset (finset.Ico l u) $ (λ n, by { simp only [mem_Ico, finset.Ico.mem], }) instance Ico_pnat_fintype (l u : ℕ+) : fintype (Ico l u) := fintype.of_finset (pnat.Ico l u) $ (λ n, by { simp only [mem_Ico, pnat.Ico.mem], }) instance Ico_ℤ_fintype (l u : ℤ) : fintype (Ico l u) := fintype.of_finset (finset.Ico_ℤ l u) $ (λ n, by { simp only [mem_Ico, finset.Ico_ℤ.mem], }) -- TODO other useful instances: fin n, zmod? end set
1aa290c7a8a55835ec22d4b06ab6b62c178a49cf
618003631150032a5676f229d13a079ac875ff77
/src/algebra/continued_fractions/computation/translations.lean
15c55600d1b6c33d1268394398197e5ac4f72dbd
[ "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
10,500
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.basic import algebra.continued_fractions.translations /-! # Basic Translation Lemmas Between Structures Defined for Computing Continued Fractions ## Summary This is a collection of simple lemmas between the different structures used for the computation of continued fractions defined in `algebra.continued_fractions.computation.basic`. The file consists of three sections: 1. Recurrences and inversion lemmas for `int_fract_pair.stream`: these lemmas give us inversion rules and recurrences for the computation of the stream of integer and fractional parts of a value. 2. Translation lemmas for the head term: these lemmas show us that the head term of the computed continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation process. 3. Translation lemmas for the sequence: these lemmas show how the sequences of the involved structures (`int_fract_pair.stream`, `int_fract_pair.seq1`, and `generalized_continued_fraction.of`) are connected, i.e. how the values are moved along the structures and the termination of one sequence implies the termination of another sequence. ## Main Theorems - `succ_nth_stream_eq_some_iff` gives as a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of non-termination. - `succ_nth_stream_eq_none_iff` gives as a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of termination. - `nth_of_eq_some_of_succ_nth_int_fract_pair_stream` and `nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero` show how the entries of the sequence of the computed continued fraction can be obtained from the stream of integer and fractional parts. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf /- Fix a discrete linear ordered floor field and a value `v`. -/ variables {K : Type*} [discrete_linear_ordered_field K] [floor_ring K] {v : K} namespace int_fract_pair /-! ### Recurrences and Inversion Lemmas for `int_fract_pair.stream` Here we state some lemmas that give us inversion rules and recurrences for the computation of the stream of integer and fractional parts of a value. -/ variable {n : ℕ} lemma stream_eq_none_of_fr_eq_zero {ifp_n : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp_n) (nth_fr_eq_zero : ifp_n.fr = 0) : int_fract_pair.stream v (n + 1) = none := begin cases ifp_n with _ fr, change fr = 0 at nth_fr_eq_zero, simp [int_fract_pair.stream, stream_nth_eq, nth_fr_eq_zero] end /-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of termination. -/ lemma succ_nth_stream_eq_none_iff : int_fract_pair.stream v (n + 1) = none ↔ (int_fract_pair.stream v n = none ∨ ∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0) := begin cases stream_nth_eq : (int_fract_pair.stream v n) with ifp, case option.none : { simp [stream_nth_eq, int_fract_pair.stream] }, case option.some : { cases ifp with _ fr, cases decidable.em (fr = 0); finish [int_fract_pair.stream] } end /-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of non-termination. -/ lemma succ_nth_stream_eq_some_iff {ifp_succ_n : int_fract_pair K} : int_fract_pair.stream v (n + 1) = some ifp_succ_n ↔ ∃ (ifp_n : int_fract_pair K), int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n := begin split, { assume stream_succ_nth_eq, have : int_fract_pair.stream v (n + 1) ≠ none, by simp [stream_succ_nth_eq], have : ¬int_fract_pair.stream v n = none ∧ ¬(∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0), by { have not_none_not_fract_zero, from (not_iff_not_of_iff succ_nth_stream_eq_none_iff).elim_left this, exact (not_or_distrib.elim_left not_none_not_fract_zero) }, cases this with stream_nth_ne_none nth_fr_ne_zero, replace nth_fr_ne_zero : ∀ ifp, int_fract_pair.stream v n = some ifp → ifp.fr ≠ 0, by simpa using nth_fr_ne_zero, obtain ⟨ifp_n, stream_nth_eq⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n, from with_one.ne_one_iff_exists.elim_left stream_nth_ne_none, existsi ifp_n, have ifp_n_fr_ne_zero : ifp_n.fr ≠ 0, from nth_fr_ne_zero ifp_n stream_nth_eq, cases ifp_n with _ ifp_n_fr, suffices : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by simpa [stream_nth_eq, ifp_n_fr_ne_zero], simp only [int_fract_pair.stream, stream_nth_eq, ifp_n_fr_ne_zero, option.some_bind, if_false] at stream_succ_nth_eq, injection stream_succ_nth_eq }, { rintro ⟨⟨_⟩, ifp_n_props⟩, finish [int_fract_pair.stream, ifp_n_props] } end lemma obtain_succ_nth_stream_of_fr_zero {ifp_succ_n : int_fract_pair K} (stream_succ_nth_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) (succ_nth_fr_eq_zero : ifp_succ_n.fr = 0) : ∃ (ifp_n : int_fract_pair K), int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ := begin -- get the witness from `succ_nth_stream_eq_some_iff` and prove that it has the additional -- properties rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with ⟨ifp_n, stream_nth_eq, nth_fr_ne_zero, _⟩, existsi ifp_n, cases ifp_n with _ ifp_n_fr, suffices : ifp_n_fr⁻¹ = ⌊ifp_n_fr⁻¹⌋, by simpa [stream_nth_eq], have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by finish, cases ifp_succ_n with _ ifp_succ_n_fr, change ifp_succ_n_fr = 0 at succ_nth_fr_eq_zero, have : fract ifp_n_fr⁻¹ = ifp_succ_n_fr, by injection this, have : fract ifp_n_fr⁻¹ = 0, by rwa [succ_nth_fr_eq_zero] at this, calc ifp_n_fr⁻¹ = fract ifp_n_fr⁻¹ + ⌊ifp_n_fr⁻¹⌋ : by rw (fract_add_floor ifp_n_fr⁻¹) ... = ⌊ifp_n_fr⁻¹⌋ : by simp [‹fract ifp_n_fr⁻¹ = 0›] end end int_fract_pair section head /-! ### Translation of the Head Term Here we state some lemmas that show us that the head term of the computed continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation process. -/ /-- The head term of the sequence with head of `v` is just the integer part of `v`. -/ @[simp] lemma int_fract_pair.seq1_fst_eq_of : (int_fract_pair.seq1 v).fst = int_fract_pair.of v := rfl lemma of_h_eq_int_fract_pair_seq1_fst_b : (gcf.of v).h = (int_fract_pair.seq1 v).fst.b := by { cases aux_seq_eq : (int_fract_pair.seq1 v), simp [gcf.of, aux_seq_eq] } /-- The head term of the gcf of `v` is `⌊v⌋`. -/ @[simp] lemma of_h_eq_floor : (gcf.of v).h = ⌊v⌋ := by simp [of_h_eq_int_fract_pair_seq1_fst_b, int_fract_pair.of] end head section sequence /-! ### Translation of the Sequences Here we state some lemmas that show how the sequences of the involved structures (`int_fract_pair.stream`, `int_fract_pair.seq1`, and `generalized_continued_fraction.of`) are connected, i.e. how the values are moved along the structures and how the termination of one sequence implies the termination of another sequence. -/ variable {n : ℕ} lemma int_fract_pair.nth_seq1_eq_succ_nth_stream : (int_fract_pair.seq1 v).snd.nth n = (int_fract_pair.stream v) (n + 1) := rfl section termination /-! #### Translation of the Termination of the Sequences Let's first show how the termination of one sequence implies the termination of another sequence. -/ lemma of_terminated_at_iff_int_fract_pair_seq1_terminated_at : (gcf.of v).terminated_at n ↔ (int_fract_pair.seq1 v).snd.terminated_at n := begin rw [gcf.terminated_at_iff_s_none, gcf.of], rcases (int_fract_pair.seq1 v) with ⟨head, ⟨st⟩⟩, cases st_n_eq : st n; simp [gcf.of, st_n_eq, seq.map, seq.nth, stream.map, seq.terminated_at, stream.nth] end lemma of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none : (gcf.of v).terminated_at n ↔ int_fract_pair.stream v (n + 1) = none := by rw [of_terminated_at_iff_int_fract_pair_seq1_terminated_at, seq.terminated_at, int_fract_pair.nth_seq1_eq_succ_nth_stream] end termination section values /-! #### Translation of the Values of the Sequence Now let's show how the values of the sequences correspond to one another. -/ lemma int_fract_pair.obtain_succ_nth_stream_of_gcf_of_nth_eq_some {gp_n : gcf.pair K} (s_nth_eq : (gcf.of v).s.nth n = some gp_n) : ∃ (ifp : int_fract_pair K), int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b := begin obtain ⟨ifp, stream_succ_nth_eq, gp_n_eq⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ gcf.pair.mk 1 (ifp.b : K) = gp_n, by { unfold gcf.of int_fract_pair.seq1 at s_nth_eq, rwa [seq.map_tail, seq.nth_tail, seq.map_nth, option.map_eq_some'] at s_nth_eq }, cases gp_n_eq, injection gp_n_eq with _ ifp_b_eq_gp_n_b, existsi ifp, exact ⟨stream_succ_nth_eq, ifp_b_eq_gp_n_b⟩ end /-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the integer parts of the stream of integer and fractional parts. -/ lemma nth_of_eq_some_of_succ_nth_int_fract_pair_stream {ifp_succ_n : int_fract_pair K} (stream_succ_nth_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (gcf.of v).s.nth n = some ⟨1, ifp_succ_n.b⟩ := begin unfold gcf.of int_fract_pair.seq1, rw [seq.map_tail, seq.nth_tail, seq.map_nth], simp [seq.nth, stream_succ_nth_eq] end /-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the fractional parts of the stream of integer and fractional parts. -/ lemma nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero {ifp_n : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp_n) (nth_fr_ne_zero : ifp_n.fr ≠ 0) : (gcf.of v).s.nth n = some ⟨1, (int_fract_pair.of ifp_n.fr⁻¹).b⟩ := have int_fract_pair.stream v (n + 1) = some (int_fract_pair.of ifp_n.fr⁻¹), by { cases ifp_n, simp [int_fract_pair.stream, stream_nth_eq, nth_fr_ne_zero], refl }, nth_of_eq_some_of_succ_nth_int_fract_pair_stream this end values end sequence end generalized_continued_fraction
99e62162cacdf2d0c7c25e02f431f84544b9f8c3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/coe_to_sort.lean
463f2a3d83680ba63ea9382846d2ee0ec5678e71
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
253
lean
universes u structure pointed := (carrier : Type u) (point : carrier) instance: has_coe_to_sort pointed.{u} (Type u) := ⟨pointed.carrier⟩ example (p : pointed) := list p -- coercion works in argument position example (p : pointed) : p := p.point
f81d2abbff4314911e78b0011598148d626ceec2
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/calculus/inverse.lean
de850dabe3232dfffc1222d43bdb898acf8406cc
[ "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
37,274
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth, Sébastien Gouëzel -/ import analysis.calculus.cont_diff import analysis.normed_space.banach /-! # Inverse function theorem In this file we prove the inverse function theorem. It says that if a map `f : E → F` has an invertible strict derivative `f'` at `a`, then it is locally invertible, and the inverse function has derivative `f' ⁻¹`. We define `has_strict_deriv_at.to_local_homeomorph` that repacks a function `f` with a `hf : has_strict_fderiv_at f f' a`, `f' : E ≃L[𝕜] F`, into a `local_homeomorph`. The `to_fun` of this `local_homeomorph` is `defeq` to `f`, so one can apply theorems about `local_homeomorph` to `hf.to_local_homeomorph f`, and get statements about `f`. Then we define `has_strict_fderiv_at.local_inverse` to be the `inv_fun` of this `local_homeomorph`, and prove two versions of the inverse function theorem: * `has_strict_fderiv_at.to_local_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense (`hf`), then `hf.local_inverse f f' a` has derivative `f'.symm` at `f a` in the strict sense; * `has_strict_fderiv_at.to_local_left_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense and `g` is locally left inverse to `f` near `a`, then `g` has derivative `f'.symm` at `f a` in the strict sense. In the one-dimensional case we reformulate these theorems in terms of `has_strict_deriv_at` and `f'⁻¹`. We also reformulate the theorems in terms of `cont_diff`, to give that `C^k` (respectively, smooth) inputs give `C^k` (smooth) inverses. These versions require that continuous differentiability implies strict differentiability; this is false over a general field, true over `ℝ` or `ℂ` and implemented here assuming `is_R_or_C 𝕂`. Some related theorems, providing the derivative and higher regularity assuming that we already know the inverse function, are formulated in `fderiv.lean`, `deriv.lean`, and `cont_diff.lean`. ## Notations In the section about `approximates_linear_on` we introduce some `local notation` to make formulas shorter: * by `N` we denote `‖f'⁻¹‖`; * by `g` we denote the auxiliary contracting map `x ↦ x + f'.symm (y - f x)` used to prove that `{x | f x = y}` is nonempty. ## Tags derivative, strictly differentiable, continuously differentiable, smooth, inverse function -/ open function set filter metric open_locale topology classical nnreal noncomputable theory variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_add_comm_group G'] [normed_space 𝕜 G'] variables {ε : ℝ} open asymptotics filter metric set open continuous_linear_map (id) /-! ### Non-linear maps close to affine maps In this section we study a map `f` such that `‖f x - f y - f' (x - y)‖ ≤ c * ‖x - y‖` on an open set `s`, where `f' : E →L[𝕜] F` is a continuous linear map and `c` is suitably small. Maps of this type behave like `f a + f' (x - a)` near each `a ∈ s`. When `f'` is onto, we show that `f` is locally onto. When `f'` is a continuous linear equiv, we show that `f` is a homeomorphism between `s` and `f '' s`. More precisely, we define `approximates_linear_on.to_local_homeomorph` to be a `local_homeomorph` with `to_fun = f`, `source = s`, and `target = f '' s`. Maps of this type naturally appear in the proof of the inverse function theorem (see next section), and `approximates_linear_on.to_local_homeomorph` will imply that the locally inverse function exists. We define this auxiliary notion to split the proof of the inverse function theorem into small lemmas. This approach makes it possible - to prove a lower estimate on the size of the domain of the inverse function; - to reuse parts of the proofs in the case if a function is not strictly differentiable. E.g., for a function `f : E × F → G` with estimates on `f x y₁ - f x y₂` but not on `f x₁ y - f x₂ y`. -/ /-- We say that `f` approximates a continuous linear map `f'` on `s` with constant `c`, if `‖f x - f y - f' (x - y)‖ ≤ c * ‖x - y‖` whenever `x, y ∈ s`. This predicate is defined to facilitate the splitting of the inverse function theorem into small lemmas. Some of these lemmas can be useful, e.g., to prove that the inverse function is defined on a specific set. -/ def approximates_linear_on (f : E → F) (f' : E →L[𝕜] F) (s : set E) (c : ℝ≥0) : Prop := ∀ (x ∈ s) (y ∈ s), ‖f x - f y - f' (x - y)‖ ≤ c * ‖x - y‖ @[simp] lemma approximates_linear_on_empty (f : E → F) (f' : E →L[𝕜] F) (c : ℝ≥0) : approximates_linear_on f f' ∅ c := by simp [approximates_linear_on] namespace approximates_linear_on variables [cs : complete_space E] {f : E → F} /-! First we prove some properties of a function that `approximates_linear_on` a (not necessarily invertible) continuous linear map. -/ section variables {f' : E →L[𝕜] F} {s t : set E} {c c' : ℝ≥0} theorem mono_num (hc : c ≤ c') (hf : approximates_linear_on f f' s c) : approximates_linear_on f f' s c' := λ x hx y hy, le_trans (hf x hx y hy) (mul_le_mul_of_nonneg_right hc $ norm_nonneg _) theorem mono_set (hst : s ⊆ t) (hf : approximates_linear_on f f' t c) : approximates_linear_on f f' s c := λ x hx y hy, hf x (hst hx) y (hst hy) lemma approximates_linear_on_iff_lipschitz_on_with {f : E → F} {f' : E →L[𝕜] F} {s : set E} {c : ℝ≥0} : approximates_linear_on f f' s c ↔ lipschitz_on_with c (f - f') s := begin have : ∀ x y, f x - f y - f' (x - y) = (f - f') x - (f - f') y, { assume x y, simp only [map_sub, pi.sub_apply], abel }, simp only [this, lipschitz_on_with_iff_norm_sub_le, approximates_linear_on], end alias approximates_linear_on_iff_lipschitz_on_with ↔ lipschitz_on_with _root_.lipschitz_on_with.approximates_linear_on lemma lipschitz_sub (hf : approximates_linear_on f f' s c) : lipschitz_with c (λ x : s, f x - f' x) := begin refine lipschitz_with.of_dist_le_mul (λ x y, _), rw [dist_eq_norm, subtype.dist_eq, dist_eq_norm], convert hf x x.2 y y.2 using 2, rw [f'.map_sub], abel end protected lemma lipschitz (hf : approximates_linear_on f f' s c) : lipschitz_with (‖f'‖₊ + c) (s.restrict f) := by simpa only [restrict_apply, add_sub_cancel'_right] using (f'.lipschitz.restrict s).add hf.lipschitz_sub protected lemma continuous (hf : approximates_linear_on f f' s c) : continuous (s.restrict f) := hf.lipschitz.continuous protected lemma continuous_on (hf : approximates_linear_on f f' s c) : continuous_on f s := continuous_on_iff_continuous_restrict.2 hf.continuous end section locally_onto /-! We prove that a function which is linearly approximated by a continuous linear map with a nonlinear right inverse is locally onto. This will apply to the case where the approximating map is a linear equivalence, for the local inverse theorem, but also whenever the approximating map is onto, by Banach's open mapping theorem. -/ include cs variables {s : set E} {c : ℝ≥0} {f' : E →L[𝕜] F} /-- If a function is linearly approximated by a continuous linear map with a (possibly nonlinear) right inverse, then it is locally onto: a ball of an explicit radius is included in the image of the map. -/ theorem surj_on_closed_ball_of_nonlinear_right_inverse (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {ε : ℝ} {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : surj_on f (closed_ball b ε) (closed_ball (f b) (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε)) := begin assume y hy, cases le_or_lt (f'symm.nnnorm : ℝ) ⁻¹ c with hc hc, { refine ⟨b, by simp [ε0], _⟩, have : dist y (f b) ≤ 0 := (mem_closed_ball.1 hy).trans (mul_nonpos_of_nonpos_of_nonneg (by linarith) ε0), simp only [dist_le_zero] at this, rw this }, have If' : (0 : ℝ) < f'symm.nnnorm, by { rw [← inv_pos], exact (nnreal.coe_nonneg _).trans_lt hc }, have Icf' : (c : ℝ) * f'symm.nnnorm < 1, by rwa [inv_eq_one_div, lt_div_iff If'] at hc, have Jf' : (f'symm.nnnorm : ℝ) ≠ 0 := ne_of_gt If', have Jcf' : (1 : ℝ) - c * f'symm.nnnorm ≠ 0, by { apply ne_of_gt, linarith }, /- We have to show that `y` can be written as `f x` for some `x ∈ closed_ball b ε`. The idea of the proof is to apply the Banach contraction principle to the map `g : x ↦ x + f'symm (y - f x)`, as a fixed point of this map satisfies `f x = y`. When `f'symm` is a genuine linear inverse, `g` is a contracting map. In our case, since `f'symm` is nonlinear, this map is not contracting (it is not even continuous), but still the proof of the contraction theorem holds: `uₙ = gⁿ b` is a Cauchy sequence, converging exponentially fast to the desired point `x`. Instead of appealing to general results, we check this by hand. The main point is that `f (u n)` becomes exponentially close to `y`, and therefore `dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive bound on `dist (u n) b`, from which one checks that `u n` stays in the ball on which one has a control. Therefore, the bound can be checked at the next step, and so on inductively. -/ set g := λ x, x + f'symm (y - f x) with hg, set u := λ (n : ℕ), g ^[n] b with hu, have usucc : ∀ n, u (n + 1) = g (u n), by simp [hu, ← iterate_succ_apply' g _ b], -- First bound: if `f z` is close to `y`, then `g z` is close to `z` (i.e., almost a fixed point). have A : ∀ z, dist (g z) z ≤ f'symm.nnnorm * dist (f z) y, { assume z, rw [dist_eq_norm, hg, add_sub_cancel', dist_eq_norm'], exact f'symm.bound _ }, -- Second bound: if `z` and `g z` are in the set with good control, then `f (g z)` becomes closer -- to `y` than `f z` was (this uses the linear approximation property, and is the reason for the -- choice of the formula for `g`). have B : ∀ z ∈ closed_ball b ε, g z ∈ closed_ball b ε → dist (f (g z)) y ≤ c * f'symm.nnnorm * dist (f z) y, { assume z hz hgz, set v := f'symm (y - f z) with hv, calc dist (f (g z)) y = ‖f (z + v) - y‖ : by rw [dist_eq_norm] ... = ‖f (z + v) - f z - f' v + f' v - (y - f z)‖ : by { congr' 1, abel } ... = ‖f (z + v) - f z - f' ((z + v) - z)‖ : by simp only [continuous_linear_map.nonlinear_right_inverse.right_inv, add_sub_cancel', sub_add_cancel] ... ≤ c * ‖(z + v) - z‖ : hf _ (hε hgz) _ (hε hz) ... ≤ c * (f'symm.nnnorm * dist (f z) y) : begin apply mul_le_mul_of_nonneg_left _ (nnreal.coe_nonneg c), simpa [hv, dist_eq_norm'] using f'symm.bound (y - f z), end ... = c * f'symm.nnnorm * dist (f z) y : by ring }, -- Third bound: a complicated bound on `dist w b` (that will show up in the induction) is enough -- to check that `w` is in the ball on which one has controls. Will be used to check that `u n` -- belongs to this ball for all `n`. have C : ∀ (n : ℕ) (w : E), dist w b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y → w ∈ closed_ball b ε, { assume n w hw, apply hw.trans, rw [div_mul_eq_mul_div, div_le_iff], swap, { linarith }, calc (f'symm.nnnorm : ℝ) * (1 - (c * f'symm.nnnorm) ^ n) * dist (f b) y = f'symm.nnnorm * dist (f b) y * (1 - (c * f'symm.nnnorm) ^ n) : by ring ... ≤ f'symm.nnnorm * dist (f b) y * 1 : begin apply mul_le_mul_of_nonneg_left _ (mul_nonneg (nnreal.coe_nonneg _) dist_nonneg), rw [sub_le_self_iff], exact pow_nonneg (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) _, end ... ≤ f'symm.nnnorm * (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε) : by { rw [mul_one], exact mul_le_mul_of_nonneg_left (mem_closed_ball'.1 hy) (nnreal.coe_nonneg _) } ... = ε * (1 - c * f'symm.nnnorm) : by { field_simp, ring } }, /- Main inductive control: `f (u n)` becomes exponentially close to `y`, and therefore `dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive bound on `dist (u n) b`, from which one checks that `u n` remains in the ball on which we have estimates. -/ have D : ∀ (n : ℕ), dist (f (u n)) y ≤ (c * f'symm.nnnorm)^n * dist (f b) y ∧ dist (u n) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y, { assume n, induction n with n IH, { simp [hu, le_refl] }, rw usucc, have Ign : dist (g (u n)) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y := calc dist (g (u n)) b ≤ dist (g (u n)) (u n) + dist (u n) b : dist_triangle _ _ _ ... ≤ f'symm.nnnorm * dist (f (u n)) y + dist (u n) b : add_le_add (A _) le_rfl ... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) + f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y : add_le_add (mul_le_mul_of_nonneg_left IH.1 (nnreal.coe_nonneg _)) IH.2 ... = f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y : by { field_simp [Jcf'], ring_exp }, refine ⟨_, Ign⟩, calc dist (f (g (u n))) y ≤ c * f'symm.nnnorm * dist (f (u n)) y : B _ (C n _ IH.2) (C n.succ _ Ign) ... ≤ (c * f'symm.nnnorm) * ((c * f'symm.nnnorm)^n * dist (f b) y) : mul_le_mul_of_nonneg_left IH.1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) ... = (c * f'symm.nnnorm) ^ n.succ * dist (f b) y : by ring_exp }, -- Deduce from the inductive bound that `uₙ` is a Cauchy sequence, therefore converging. have : cauchy_seq u, { have : ∀ (n : ℕ), dist (u n) (u (n+1)) ≤ f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n, { assume n, calc dist (u n) (u (n+1)) = dist (g (u n)) (u n) : by rw [usucc, dist_comm] ... ≤ f'symm.nnnorm * dist (f (u n)) y : A _ ... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) : mul_le_mul_of_nonneg_left (D n).1 (nnreal.coe_nonneg _) ... = f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n : by ring }, exact cauchy_seq_of_le_geometric _ _ Icf' this }, obtain ⟨x, hx⟩ : ∃ x, tendsto u at_top (𝓝 x) := cauchy_seq_tendsto_of_complete this, -- As all the `uₙ` belong to the ball `closed_ball b ε`, so does their limit `x`. have xmem : x ∈ closed_ball b ε := is_closed_ball.mem_of_tendsto hx (eventually_of_forall (λ n, C n _ (D n).2)), refine ⟨x, xmem, _⟩, -- It remains to check that `f x = y`. This follows from continuity of `f` on `closed_ball b ε` -- and from the fact that `f uₙ` is converging to `y` by construction. have hx' : tendsto u at_top (𝓝[closed_ball b ε] x), { simp only [nhds_within, tendsto_inf, hx, true_and, ge_iff_le, tendsto_principal], exact eventually_of_forall (λ n, C n _ (D n).2) }, have T1 : tendsto (λ n, f (u n)) at_top (𝓝 (f x)) := (hf.continuous_on.mono hε x xmem).tendsto.comp hx', have T2 : tendsto (λ n, f (u n)) at_top (𝓝 y), { rw tendsto_iff_dist_tendsto_zero, refine squeeze_zero (λ n, dist_nonneg) (λ n, (D n).1) _, simpa using (tendsto_pow_at_top_nhds_0_of_lt_1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) Icf').mul tendsto_const_nhds }, exact tendsto_nhds_unique T1 T2, end lemma open_image (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) (hs : is_open s) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : is_open (f '' s) := begin cases hc with hE hc, { resetI, apply is_open_discrete }, simp only [is_open_iff_mem_nhds, nhds_basis_closed_ball.mem_iff, ball_image_iff] at hs ⊢, intros x hx, rcases hs x hx with ⟨ε, ε0, hε⟩, refine ⟨(f'symm.nnnorm⁻¹ - c) * ε, mul_pos (sub_pos.2 hc) ε0, _⟩, exact (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'symm (le_of_lt ε0) hε).mono hε (subset.refl _) end lemma image_mem_nhds (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : f '' s ∈ 𝓝 (f x) := begin obtain ⟨t, hts, ht, xt⟩ : ∃ t ⊆ s, is_open t ∧ x ∈ t := _root_.mem_nhds_iff.1 hs, have := is_open.mem_nhds ((hf.mono_set hts).open_image f'symm ht hc) (mem_image_of_mem _ xt), exact mem_of_superset this (image_subset _ hts), end lemma map_nhds_eq (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : map f (𝓝 x) = 𝓝 (f x) := begin refine le_antisymm ((hf.continuous_on x (mem_of_mem_nhds hs)).continuous_at hs) (le_map (λ t ht, _)), have : f '' (s ∩ t) ∈ 𝓝 (f x) := (hf.mono_set (inter_subset_left s t)).image_mem_nhds f'symm (inter_mem hs ht) hc, exact mem_of_superset this (image_subset _ (inter_subset_right _ _)), end end locally_onto /-! From now on we assume that `f` approximates an invertible continuous linear map `f : E ≃L[𝕜] F`. We also assume that either `E = {0}`, or `c < ‖f'⁻¹‖⁻¹`. We use `N` as an abbreviation for `‖f'⁻¹‖`. -/ variables {f' : E ≃L[𝕜] F} {s : set E} {c : ℝ≥0} local notation `N` := ‖(f'.symm : F →L[𝕜] E)‖₊ protected lemma antilipschitz (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : antilipschitz_with (N⁻¹ - c)⁻¹ (s.restrict f) := begin cases hc with hE hc, { haveI : subsingleton s := ⟨λ x y, subtype.eq $ @subsingleton.elim _ hE _ _⟩, exact antilipschitz_with.of_subsingleton }, convert (f'.antilipschitz.restrict s).add_lipschitz_with hf.lipschitz_sub hc, simp [restrict] end protected lemma injective (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : injective (s.restrict f) := (hf.antilipschitz hc).injective protected lemma inj_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : inj_on f s := inj_on_iff_injective.2 $ hf.injective hc protected lemma surjective [complete_space E] (hf : approximates_linear_on f (f' : E →L[𝕜] F) univ c) (hc : subsingleton E ∨ c < N⁻¹) : surjective f := begin cases hc with hE hc, { haveI : subsingleton F := (equiv.subsingleton_congr f'.to_linear_equiv.to_equiv).1 hE, exact surjective_to_subsingleton _ }, { apply forall_of_forall_mem_closed_ball (λ (y : F), ∃ a, f a = y) (f 0) _, have hc' : (0 : ℝ) < N⁻¹ - c, by { rw sub_pos, exact hc }, let p : ℝ → Prop := λ R, closed_ball (f 0) R ⊆ set.range f, have hp : ∀ᶠ (r:ℝ) in at_top, p ((N⁻¹ - c) * r), { have hr : ∀ᶠ (r:ℝ) in at_top, 0 ≤ r := eventually_ge_at_top 0, refine hr.mono (λ r hr, subset.trans _ (image_subset_range f (closed_ball 0 r))), refine hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse hr _, exact subset_univ _ }, refine ((tendsto_id.const_mul_at_top hc').frequently hp.frequently).mono _, exact λ R h y hy, h hy }, end /-- A map approximating a linear equivalence on a set defines a local equivalence on this set. Should not be used outside of this file, because it is superseded by `to_local_homeomorph` below. This is a first step towards the inverse function. -/ def to_local_equiv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : local_equiv E F := (hf.inj_on hc).to_local_equiv _ _ /-- The inverse function is continuous on `f '' s`. Use properties of `local_homeomorph` instead. -/ lemma inverse_continuous_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : continuous_on (hf.to_local_equiv hc).symm (f '' s) := begin apply continuous_on_iff_continuous_restrict.2, refine ((hf.antilipschitz hc).to_right_inv_on' _ (hf.to_local_equiv hc).right_inv').continuous, exact (λ x hx, (hf.to_local_equiv hc).map_target hx) end /-- The inverse function is approximated linearly on `f '' s` by `f'.symm`. -/ lemma to_inv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : approximates_linear_on (hf.to_local_equiv hc).symm (f'.symm : F →L[𝕜] E) (f '' s) (N * (N⁻¹ - c)⁻¹ * c) := begin assume x hx y hy, set A := hf.to_local_equiv hc with hA, have Af : ∀ z, A z = f z := λ z, rfl, rcases (mem_image _ _ _).1 hx with ⟨x', x's, rfl⟩, rcases (mem_image _ _ _).1 hy with ⟨y', y's, rfl⟩, rw [← Af x', ← Af y', A.left_inv x's, A.left_inv y's], calc ‖x' - y' - (f'.symm) (A x' - A y')‖ ≤ N * ‖f' (x' - y' - (f'.symm) (A x' - A y'))‖ : (f' : E →L[𝕜] F).bound_of_antilipschitz f'.antilipschitz _ ... = N * ‖A y' - A x' - f' (y' - x')‖ : begin congr' 2, simp only [continuous_linear_equiv.apply_symm_apply, continuous_linear_equiv.map_sub], abel, end ... ≤ N * (c * ‖y' - x'‖) : mul_le_mul_of_nonneg_left (hf _ y's _ x's) (nnreal.coe_nonneg _) ... ≤ N * (c * (((N⁻¹ - c)⁻¹ : ℝ≥0) * ‖A y' - A x'‖)) : begin apply_rules [mul_le_mul_of_nonneg_left, nnreal.coe_nonneg], rw [← dist_eq_norm, ← dist_eq_norm], exact (hf.antilipschitz hc).le_mul_dist ⟨y', y's⟩ ⟨x', x's⟩, end ... = (N * (N⁻¹ - c)⁻¹ * c : ℝ≥0) * ‖A x' - A y'‖ : by { simp only [norm_sub_rev, nonneg.coe_mul], ring } end include cs section variables (f s) /-- Given a function `f` that approximates a linear equivalence on an open set `s`, returns a local homeomorph with `to_fun = f` and `source = s`. -/ def to_local_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : local_homeomorph E F := { to_local_equiv := hf.to_local_equiv hc, open_source := hs, open_target := hf.open_image f'.to_nonlinear_right_inverse hs (by rwa f'.to_linear_equiv.to_equiv.subsingleton_congr at hc), continuous_to_fun := hf.continuous_on, continuous_inv_fun := hf.inverse_continuous_on hc } /-- A function `f` that approximates a linear equivalence on the whole space is a homeomorphism. -/ def to_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) univ c) (hc : subsingleton E ∨ c < N⁻¹) : E ≃ₜ F := begin refine (hf.to_local_homeomorph _ _ hc is_open_univ).to_homeomorph_of_source_eq_univ_target_eq_univ rfl _, change f '' univ = univ, rw [image_univ, range_iff_surjective], exact hf.surjective hc, end omit cs /-- In a real vector space, a function `f` that approximates a linear equivalence on a subset `s` can be extended to a homeomorphism of the whole space. -/ lemma exists_homeomorph_extension {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {s : set E} {f : E → F} {f' : E ≃L[ℝ] F} {c : ℝ≥0} (hf : approximates_linear_on f (f' : E →L[ℝ] F) s c) (hc : subsingleton E ∨ lipschitz_extension_constant F * c < (‖(f'.symm : F →L[ℝ] E)‖₊)⁻¹) : ∃ g : E ≃ₜ F, eq_on f g s := begin -- the difference `f - f'` is Lipschitz on `s`. It can be extended to a Lipschitz function `u` -- on the whole space, with a slightly worse Lipschitz constant. Then `f' + u` will be the -- desired homeomorphism. obtain ⟨u, hu, uf⟩ : ∃ (u : E → F), lipschitz_with (lipschitz_extension_constant F * c) u ∧ eq_on (f - f') u s := hf.lipschitz_on_with.extend_finite_dimension, let g : E → F := λ x, f' x + u x, have fg : eq_on f g s := λ x hx, by simp_rw [g, ← uf hx, pi.sub_apply, add_sub_cancel'_right], have hg : approximates_linear_on g (f' : E →L[ℝ] F) univ (lipschitz_extension_constant F * c), { apply lipschitz_on_with.approximates_linear_on, rw lipschitz_on_univ, convert hu, ext x, simp only [add_sub_cancel', continuous_linear_equiv.coe_coe, pi.sub_apply] }, haveI : finite_dimensional ℝ E := f'.symm.to_linear_equiv.finite_dimensional, exact ⟨hg.to_homeomorph g hc, fg⟩, end end @[simp] lemma to_local_homeomorph_coe (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs : E → F) = f := rfl @[simp] lemma to_local_homeomorph_source (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).source = s := rfl @[simp] lemma to_local_homeomorph_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).target = f '' s := rfl lemma closed_ball_subset_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : closed_ball (f b) ((N⁻¹ - c) * ε) ⊆ (hf.to_local_homeomorph f s hc hs).target := (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse ε0 hε).mono hε (subset.refl _) end approximates_linear_on /-! ### Inverse function theorem Now we prove the inverse function theorem. Let `f : E → F` be a map defined on a complete vector space `E`. Assume that `f` has an invertible derivative `f' : E ≃L[𝕜] F` at `a : E` in the strict sense. Then `f` approximates `f'` in the sense of `approximates_linear_on` on an open neighborhood of `a`, and we can apply `approximates_linear_on.to_local_homeomorph` to construct the inverse function. -/ namespace has_strict_fderiv_at /-- If `f` has derivative `f'` at `a` in the strict sense and `c > 0`, then `f` approximates `f'` with constant `c` on some neighborhood of `a`. -/ lemma approximates_deriv_on_nhds {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f f' a) {c : ℝ≥0} (hc : subsingleton E ∨ 0 < c) : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := begin cases hc with hE hc, { refine ⟨univ, is_open.mem_nhds is_open_univ trivial, λ x hx y hy, _⟩, simp [@subsingleton.elim E hE x y] }, have := hf.def hc, rw [nhds_prod_eq, filter.eventually, mem_prod_same_iff] at this, rcases this with ⟨s, has, hs⟩, exact ⟨s, has, λ x hx y hy, hs (mk_mem_prod hx hy)⟩ end lemma map_nhds_eq_of_surj [complete_space E] [complete_space F] {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) (h : linear_map.range f' = ⊤) : map f (𝓝 a) = 𝓝 (f a) := begin let f'symm := f'.nonlinear_right_inverse_of_surjective h, set c : ℝ≥0 := f'symm.nnnorm⁻¹ / 2 with hc, have f'symm_pos : 0 < f'symm.nnnorm := f'.nonlinear_right_inverse_of_surjective_nnnorm_pos h, have cpos : 0 < c, by simp [hc, half_pos, inv_pos, f'symm_pos], obtain ⟨s, s_nhds, hs⟩ : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := hf.approximates_deriv_on_nhds (or.inr cpos), apply hs.map_nhds_eq f'symm s_nhds (or.inr (nnreal.half_lt_self _)), simp [ne_of_gt f'symm_pos], end variables [cs : complete_space E] {f : E → F} {f' : E ≃L[𝕜] F} {a : E} lemma approximates_deriv_on_open_nhds (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∃ (s : set E) (hs : a ∈ s ∧ is_open s), approximates_linear_on f (f' : E →L[𝕜] F) s (‖(f'.symm : F →L[𝕜] E)‖₊⁻¹ / 2) := begin refine ((nhds_basis_opens a).exists_iff _).1 _, exact (λ s t, approximates_linear_on.mono_set), exact (hf.approximates_deriv_on_nhds $ f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', half_pos $ inv_pos.2 hf') end include cs variable (f) /-- Given a function with an invertible strict derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. This is a part of the inverse function theorem. The other part `has_strict_fderiv_at.to_local_inverse` states that the inverse function of this `local_homeomorph` has derivative `f'.symm`. -/ def to_local_homeomorph (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : local_homeomorph E F := approximates_linear_on.to_local_homeomorph f (classical.some hf.approximates_deriv_on_open_nhds) (classical.some_spec hf.approximates_deriv_on_open_nhds).snd (f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_lt_self $ ne_of_gt $ inv_pos.2 hf') (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.2 variable {f} @[simp] lemma to_local_homeomorph_coe (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : (hf.to_local_homeomorph f : E → F) = f := rfl lemma mem_to_local_homeomorph_source (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : a ∈ (hf.to_local_homeomorph f).source := (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.1 lemma image_mem_to_local_homeomorph_target (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : f a ∈ (hf.to_local_homeomorph f).target := (hf.to_local_homeomorph f).map_source hf.mem_to_local_homeomorph_source lemma map_nhds_eq_of_equiv (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : map f (𝓝 a) = 𝓝 (f a) := (hf.to_local_homeomorph f).map_nhds_eq hf.mem_to_local_homeomorph_source variables (f f' a) /-- Given a function `f` with an invertible derivative, returns a function that is locally inverse to `f`. -/ def local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : F → E := (hf.to_local_homeomorph f).symm variables {f f' a} lemma local_inverse_def (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f _ _ = (hf.to_local_homeomorph f).symm := rfl lemma eventually_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ x in 𝓝 a, hf.local_inverse f f' a (f x) = x := (hf.to_local_homeomorph f).eventually_left_inverse hf.mem_to_local_homeomorph_source @[simp] lemma local_inverse_apply_image (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f f' a (f a) = a := hf.eventually_left_inverse.self_of_nhds lemma eventually_right_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ y in 𝓝 (f a), f (hf.local_inverse f f' a y) = y := (hf.to_local_homeomorph f).eventually_right_inverse' hf.mem_to_local_homeomorph_source lemma local_inverse_continuous_at (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : continuous_at (hf.local_inverse f f' a) (f a) := (hf.to_local_homeomorph f).continuous_at_symm hf.image_mem_to_local_homeomorph_target lemma local_inverse_tendsto (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : tendsto (hf.local_inverse f f' a) (𝓝 $ f a) (𝓝 a) := (hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source lemma local_inverse_unique (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : ∀ᶠ y in 𝓝 (f a), g y = local_inverse f f' a hf y := eventually_eq_of_left_inv_of_right_inv hg hf.eventually_right_inverse $ (hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source /-- If `f` has an invertible derivative `f'` at `a` in the sense of strict differentiability `(hf)`, then the inverse function `hf.local_inverse f` has derivative `f'.symm` at `f a`. -/ theorem to_local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : has_strict_fderiv_at (hf.local_inverse f f' a) (f'.symm : F →L[𝕜] E) (f a) := (hf.to_local_homeomorph f).has_strict_fderiv_at_symm hf.image_mem_to_local_homeomorph_target $ by simpa [← local_inverse_def] using hf /-- If `f : E → F` has an invertible derivative `f'` at `a` in the sense of strict differentiability and `g (f x) = x` in a neighborhood of `a`, then `g` has derivative `f'.symm` at `f a`. For a version assuming `f (g y) = y` and continuity of `g` at `f a` but not `[complete_space E]` see `of_local_left_inverse`. -/ theorem to_local_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) (f a) := hf.to_local_inverse.congr_of_eventually_eq $ (hf.local_inverse_unique hg).mono $ λ _, eq.symm end has_strict_fderiv_at /-- If a function has an invertible strict derivative at all points, then it is an open map. -/ lemma open_map_of_strict_fderiv_equiv [complete_space E] {f : E → F} {f' : E → E ≃L[𝕜] F} (hf : ∀ x, has_strict_fderiv_at f (f' x : E →L[𝕜] F) x) : is_open_map f := is_open_map_iff_nhds_le.2 $ λ x, (hf x).map_nhds_eq_of_equiv.ge /-! ### Inverse function theorem, 1D case In this case we prove a version of the inverse function theorem for maps `f : 𝕜 → 𝕜`. We use `continuous_linear_equiv.units_equiv_aut` to translate `has_strict_deriv_at f f' a` and `f' ≠ 0` into `has_strict_fderiv_at f (_ : 𝕜 ≃L[𝕜] 𝕜) a`. -/ namespace has_strict_deriv_at variables [cs : complete_space 𝕜] {f : 𝕜 → 𝕜} {f' a : 𝕜} (hf : has_strict_deriv_at f f' a) (hf' : f' ≠ 0) include cs variables (f f' a) /-- A function that is inverse to `f` near `a`. -/ @[reducible] def local_inverse : 𝕜 → 𝕜 := (hf.has_strict_fderiv_at_equiv hf').local_inverse _ _ _ variables {f f' a} lemma map_nhds_eq : map f (𝓝 a) = 𝓝 (f a) := (hf.has_strict_fderiv_at_equiv hf').map_nhds_eq_of_equiv theorem to_local_inverse : has_strict_deriv_at (hf.local_inverse f f' a hf') f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_inverse theorem to_local_left_inverse {g : 𝕜 → 𝕜} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_deriv_at g f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_left_inverse hg end has_strict_deriv_at /-- If a function has a non-zero strict derivative at all points, then it is an open map. -/ lemma open_map_of_strict_deriv [complete_space 𝕜] {f f' : 𝕜 → 𝕜} (hf : ∀ x, has_strict_deriv_at f (f' x) x) (h0 : ∀ x, f' x ≠ 0) : is_open_map f := is_open_map_iff_nhds_le.2 $ λ x, ((hf x).map_nhds_eq (h0 x)).ge /-! ### Inverse function theorem, smooth case -/ namespace cont_diff_at variables {𝕂 : Type*} [is_R_or_C 𝕂] variables {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕂 E'] variables {F' : Type*} [normed_add_comm_group F'] [normed_space 𝕂 F'] variables [complete_space E'] (f : E' → F') {f' : E' ≃L[𝕂] F'} {a : E'} /-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. -/ def to_local_homeomorph {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : local_homeomorph E' F' := (hf.has_strict_fderiv_at' hf' hn).to_local_homeomorph f variable {f} @[simp] lemma to_local_homeomorph_coe {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : (hf.to_local_homeomorph f hf' hn : E' → F') = f := rfl lemma mem_to_local_homeomorph_source {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : a ∈ (hf.to_local_homeomorph f hf' hn).source := (hf.has_strict_fderiv_at' hf' hn).mem_to_local_homeomorph_source lemma image_mem_to_local_homeomorph_target {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : f a ∈ (hf.to_local_homeomorph f hf' hn).target := (hf.has_strict_fderiv_at' hf' hn).image_mem_to_local_homeomorph_target /-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a function that is locally inverse to `f`. -/ def local_inverse {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : F' → E' := (hf.has_strict_fderiv_at' hf' hn).local_inverse f f' a lemma local_inverse_apply_image {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : hf.local_inverse hf' hn (f a) = a := (hf.has_strict_fderiv_at' hf' hn).local_inverse_apply_image /-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, the inverse function (produced by `cont_diff.to_local_homeomorph`) is also `cont_diff`. -/ lemma to_local_inverse {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : cont_diff_at 𝕂 n (hf.local_inverse hf' hn) (f a) := begin have := hf.local_inverse_apply_image hf' hn, apply (hf.to_local_homeomorph f hf' hn).cont_diff_at_symm (image_mem_to_local_homeomorph_target hf hf' hn), { convert hf' }, { convert hf } end end cont_diff_at
7cd1ff02900231d5d54a3691b1d1e5367418c566
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/Compiler/ConstFolding.lean
99c1d88f4622f443d1cc8545a8dc27343609e3ad
[ "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
7,245
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.Expr import Lean.Compiler.Util /- Constant folding for primitives that have special runtime support. -/ namespace Lean.Compiler abbrev BinFoldFn := Bool → Expr → Expr → Option Expr abbrev UnFoldFn := Bool → Expr → Option Expr def mkUIntTypeName (nbytes : Nat) : Name := Name.mkSimple ("UInt" ++ toString nbytes) structure NumScalarTypeInfo where nbits : Nat id : Name := mkUIntTypeName nbits ofNatFn : Name := Name.mkStr id "ofNat" toNatFn : Name := Name.mkStr id "toNat" size : Nat := 2^nbits def numScalarTypes : List NumScalarTypeInfo := [{nbits := 8}, {nbits := 16}, {nbits := 32}, {nbits := 64}, {id := `USize, nbits := System.Platform.numBits}] def isOfNat (fn : Name) : Bool := numScalarTypes.any (fun info => info.ofNatFn == fn) def isToNat (fn : Name) : Bool := numScalarTypes.any (fun info => info.toNatFn == fn) def getInfoFromFn (fn : Name) : List NumScalarTypeInfo → Option NumScalarTypeInfo | [] => none | info::infos => if info.ofNatFn == fn then some info else getInfoFromFn fn infos def getInfoFromVal : Expr → Option NumScalarTypeInfo | Expr.app (Expr.const fn _ _) _ _ => getInfoFromFn fn numScalarTypes | _ => none @[export lean_get_num_lit] def getNumLit : Expr → Option Nat | Expr.lit (Literal.natVal n) _ => some n | Expr.app (Expr.const fn _ _) a _ => if isOfNat fn then getNumLit a else none | _ => none def mkUIntLit (info : NumScalarTypeInfo) (n : Nat) : Expr := mkApp (mkConst info.ofNatFn) (mkRawNatLit (n%info.size)) def mkUInt32Lit (n : Nat) : Expr := mkUIntLit {nbits := 32} n def foldBinUInt (fn : NumScalarTypeInfo → Bool → Nat → Nat → Nat) (beforeErasure : Bool) (a₁ a₂ : Expr) : Option Expr := OptionM.run do let n₁ ← getNumLit a₁ let n₂ ← getNumLit a₂ let info ← getInfoFromVal a₁ return mkUIntLit info (fn info beforeErasure n₁ n₂) def foldUIntAdd := foldBinUInt $ fun _ _ => Add.add def foldUIntMul := foldBinUInt $ fun _ _ => Mul.mul def foldUIntDiv := foldBinUInt $ fun _ _ => Div.div def foldUIntMod := foldBinUInt $ fun _ _ => Mod.mod def foldUIntSub := foldBinUInt $ fun info _ a b => (a + (info.size - b)) def preUIntBinFoldFns : List (Name × BinFoldFn) := [(`add, foldUIntAdd), (`mul, foldUIntMul), (`div, foldUIntDiv), (`mod, foldUIntMod), (`sub, foldUIntSub)] def uintBinFoldFns : List (Name × BinFoldFn) := numScalarTypes.foldl (fun r info => r ++ (preUIntBinFoldFns.map (fun ⟨suffix, fn⟩ => (info.id ++ suffix, fn)))) [] def foldNatBinOp (fn : Nat → Nat → Nat) (a₁ a₂ : Expr) : Option Expr := OptionM.run do let n₁ ← getNumLit a₁ let n₂ ← getNumLit a₂ return mkRawNatLit (fn n₁ n₂) def foldNatAdd (_ : Bool) := foldNatBinOp Add.add def foldNatMul (_ : Bool) := foldNatBinOp Mul.mul def foldNatDiv (_ : Bool) := foldNatBinOp Div.div def foldNatMod (_ : Bool) := foldNatBinOp Mod.mod -- TODO: add option for controlling the limit def natPowThreshold := 256 def foldNatPow (_ : Bool) (a₁ a₂ : Expr) : Option Expr := OptionM.run do let n₁ ← getNumLit a₁ let n₂ ← getNumLit a₂ if n₂ < natPowThreshold then return mkRawNatLit (n₁ ^ n₂) else failure def mkNatEq (a b : Expr) : Expr := mkAppN (mkConst ``Eq [levelOne]) #[(mkConst `Nat), a, b] def mkNatLt (a b : Expr) : Expr := mkAppN (mkConst ``LT.lt [levelZero]) #[mkConst `Nat, mkConst `Nat.less, a, b] def mkNatLe (a b : Expr) : Expr := mkAppN (mkConst ``LE.le [levelZero]) #[mkConst `Nat, mkConst `Nat.lessEq, a, b] def toDecidableExpr (beforeErasure : Bool) (pred : Expr) (r : Bool) : Expr := match beforeErasure, r with | false, true => mkDecIsTrue neutralExpr neutralExpr | false, false => mkDecIsFalse neutralExpr neutralExpr | true, true => mkDecIsTrue pred (mkLcProof pred) | true, false => mkDecIsFalse pred (mkLcProof pred) def foldNatBinPred (mkPred : Expr → Expr → Expr) (fn : Nat → Nat → Bool) (beforeErasure : Bool) (a₁ a₂ : Expr) : Option Expr := OptionM.run do let n₁ ← getNumLit a₁ let n₂ ← getNumLit a₂ return toDecidableExpr beforeErasure (mkPred a₁ a₂) (fn n₁ n₂) def foldNatDecEq := foldNatBinPred mkNatEq (fun a b => a = b) def foldNatDecLt := foldNatBinPred mkNatLt (fun a b => a < b) def foldNatDecLe := foldNatBinPred mkNatLe (fun a b => a ≤ b) def natFoldFns : List (Name × BinFoldFn) := [(``Nat.add, foldNatAdd), (``Nat.mul, foldNatMul), (``Nat.div, foldNatDiv), (``Nat.mod, foldNatMod), (``Nat.pow, foldNatPow), (``Nat.decEq, foldNatDecEq), (``Nat.decLt, foldNatDecLt), (``Nat.decLe, foldNatDecLe)] def getBoolLit : Expr → Option Bool | Expr.const ``Bool.true _ _ => some true | Expr.const ``Bool.false _ _ => some false | _ => none def foldStrictAnd (_ : Bool) (a₁ a₂ : Expr) : Option Expr := let v₁ := getBoolLit a₁ let v₂ := getBoolLit a₂ match v₁, v₂ with | some true, _ => a₂ | some false, _ => a₁ | _, some true => a₁ | _, some false => a₂ | _, _ => none def foldStrictOr (_ : Bool) (a₁ a₂ : Expr) : Option Expr := let v₁ := getBoolLit a₁ let v₂ := getBoolLit a₂ match v₁, v₂ with | some true, _ => a₁ | some false, _ => a₂ | _, some true => a₂ | _, some false => a₁ | _, _ => none def boolFoldFns : List (Name × BinFoldFn) := [(`strictOr, foldStrictOr), (`strictAnd, foldStrictAnd)] def binFoldFns : List (Name × BinFoldFn) := boolFoldFns ++ uintBinFoldFns ++ natFoldFns def foldNatSucc (_ : Bool) (a : Expr) : Option Expr := OptionM.run do let n ← getNumLit a return mkRawNatLit (n+1) def foldCharOfNat (beforeErasure : Bool) (a : Expr) : Option Expr := OptionM.run do guard (!beforeErasure) let n ← getNumLit a if isValidChar n.toUInt32 then return mkUInt32Lit n else return mkUInt32Lit 0 def foldToNat (_ : Bool) (a : Expr) : Option Expr := OptionM.run do let n ← getNumLit a return mkRawNatLit n def uintFoldToNatFns : List (Name × UnFoldFn) := numScalarTypes.foldl (fun r info => (info.toNatFn, foldToNat) :: r) [] def unFoldFns : List (Name × UnFoldFn) := [(``Nat.succ, foldNatSucc), (``Char.ofNat, foldCharOfNat)] ++ uintFoldToNatFns def findBinFoldFn (fn : Name) : Option BinFoldFn := binFoldFns.lookup fn def findUnFoldFn (fn : Name) : Option UnFoldFn := unFoldFns.lookup fn @[export lean_fold_bin_op] def foldBinOp (beforeErasure : Bool) (f : Expr) (a : Expr) (b : Expr) : Option Expr := OptionM.run do match f with | Expr.const fn _ _ => let foldFn ← findBinFoldFn fn foldFn beforeErasure a b | _ => failure @[export lean_fold_un_op] def foldUnOp (beforeErasure : Bool) (f : Expr) (a : Expr) : Option Expr := OptionM.run do match f with | Expr.const fn _ _ => let foldFn ← findUnFoldFn fn foldFn beforeErasure a | _ => failure end Lean.Compiler
2dd07ed6ac2bdb5a0ed83ba985b7061181f95f8b
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/new_obtains2.lean
aa623c201b620abd6ac01089ee92b0c8451062b4
[ "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
303
lean
open sigma.ops section parameter A : Type parameter C : A → Type parameter P : ∀ a, C a → Prop example (x t : A) (e : x = t) (h₁ : C x) (h₂ : P x h₁) : unit := obtain (nh₁ : C t) (nh₂ : P t nh₁), from eq.rec_on e ⟨h₁, h₂⟩, unit.star end
603e1ef8ce74e414ddecf3602dacbdd5013f250b
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/multiset/basic.lean
68c8394de42a8e06814d7c8548ad7ba28c64c25f
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
88,252
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.list.perm import algebra.group_power /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /-! ### Empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /-! ### `multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a ::ₘ l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)} {C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs], have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /-! ### `multiset.subset` -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /-! ### Partial order on `multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩ instance : canonically_ordered_add_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_add_comm_monoid } @[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card : multiset α →+ ℕ := { to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq, map_zero' := rfl, map_add' := λ s t, quotient.induction_on₂ s t length_append } @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl theorem card_add (s t : multiset α) : card (s + t) = card s + card t := card.map_add s t lemma card_smul (s : multiset α) (n : ℕ) : (n •ℕ s).card = n * s.card := by rw [card.map_nsmul s n, nat.nsmul_eq_mul] @[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a ::ₘ 0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /-! ### Singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a ::ₘ 0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a ::ₘ 0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a ::ₘ 0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a ::ₘ 0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /-! ### `multiset.repeat` -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a ::ₘ 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a ::ₘ 0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ /-! ### Erasing one copy of an element -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /-! ### `multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s $ λ l, rfl lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } theorem map_nsmul (f : α → β) (n s) : map f (n •ℕ s) = n •ℕ map f s := (add_monoid_hom.of (map f)).map_nsmul _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /-! ### `multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ attribute [norm_cast] coe_prod coe_sum @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (n •ℕ m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) theorem prod_ne_zero {R : Type*} [comm_semiring R] [no_zero_divisors R] [nontrivial R] {m : multiset R} : (∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 := multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H, by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) } lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) : multiset.prod s = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma prod_dvd_prod [comm_monoid α] {s t : multiset α} (h : s ≤ t) : s.prod ∣ t.prod := begin rcases multiset.le_iff_exists_add.1 h with ⟨z, rfl⟩, simp, end theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α] {s : multiset α} : s.prod = 0 ↔ (0 : α) ∈ s := multiset.induction_on s (by simp) $ assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt} @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod := quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod := quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) := begin apply quotient.induction_on m, simp only [quot_mk_to_coe, coe_prod, mem_coe], intros l hl₁ hl₂ x hx, apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx, end lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} : m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) := quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left ih _) lemma abs_sum_le_sum_abs [linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) @[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, a ::ₘ 0)).sum = s := multiset.induction_on s (by simp) (by simp) /-! ### Join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /-! ### `multiset.bind` -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a ::ₘ g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /-! ### Product of two `multiset`s -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a ::ₘ s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a,b) ::ₘ 0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /-! ### Sigma multiset -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a ::ₘ 0).sigma (λ a, b a ::ₘ 0) = ⟨a, b a⟩ ::ₘ 0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /-! ### Subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) := by simpa using add_union_distrib (a ::ₘ 0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /-! ### `multiset.filter` -/ section variables (p : α → Prop) [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero : filter p 0 = 0 := rfl lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ _ theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter p h).subperm variable {p} @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩ variable (p) @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter _ $ inter_le_left _ _) (filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _ _) (filter_le _ _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero : countp p 0 = 0 := rfl variable {p} @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s $ countp_cons_of_pos p @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s $ countp_cons_of_neg p variable (p) theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add _, map_zero := countp_zero _ } @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h) @[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] variable {p} theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ end /-! ### Multiplicity of an element -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le _ theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) theorem count_cons (a b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) := by by_cases h : a = b; simp [h] theorem count_singleton (a : α) : count a (a ::ₘ 0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add _ instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom _ @[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') @[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } end @[simp] lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n •ℕ s ↔ a ∈ s := begin classical, cases n, { exfalso, apply h0 rfl }, rw [← not_iff_not, ← count_eq_zero, ← count_eq_zero], simp [h0], end /-! ### Lift a relation to `multiset`s -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ @[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs) variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') := begin split, { generalize hm : a ::ₘ as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono h lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /-! ### Disjoint multisets -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a ::ₘ 0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := by { simp [disjoint, @eq_comm _ (f _) (g _)], refl } /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } variable {α} @[simp] lemma coe_subsingleton_equiv [subsingleton α] : (subsingleton_equiv α : list α → multiset α) = coe := rfl end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
15ec006049dc3b86021bedf7fb47ec18ff8eac59
ac89c256db07448984849346288e0eeffe8b20d0
/src/Init/Core.lean
b4f78e6b80c5d55a93d0a0fe89f67644912f0468
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,110
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.SizeOf universe u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /-- Thunks are "lazy" values that are evaluated when first accessed using `Thunk.get/map/bind`. The value is then stored and not recomputed for all further accesses. -/ -- NOTE: the runtime has special support for the `Thunk` type to implement this behavior structure Thunk (α : Type u) : Type u where private fn : Unit → α attribute [extern "lean_mk_thunk"] Thunk.mk /-- Store a value in a thunk. Note that the value has already been computed, so there is no laziness. -/ @[extern "lean_thunk_pure"] protected def Thunk.pure (a : α) : Thunk α := ⟨fun _ => a⟩ -- NOTE: we use `Thunk.get` instead of `Thunk.fn` as the accessor primitive as the latter has an additional `Unit` argument @[extern "lean_thunk_get_own"] protected def Thunk.get (x : @& Thunk α) : α := x.fn () @[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop where intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff inductive Sum (α : Type u) (β : Type v) where | inl (val : α) : Sum α β | inr (val : β) : Sum α β inductive PSum (α : Sort u) (β : Sort v) where | inl (val : α) : PSum α β | inr (val : β) : PSum α β structure Sigma {α : Type u} (β : α → Type v) where fst : α snd : β fst attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) where fst : α snd : β fst inductive Exists {α : Sort u} (p : α → Prop) : Prop where | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) where | done : α → ForInStep α | yield : α → ForInStep α class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β export ForIn (forIn) /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) where | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) where | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) where | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) where | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) where Equiv : α → α → Sort v infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) where emptyCollection : α notation "{" "}" => EmptyCollection.emptyCollection notation "∅" => EmptyCollection.emptyCollection /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u where pure :: (get : α) deriving Inhabited attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /- Some type that is not a scalar value in our runtime. -/ structure NonScalar where val : Nat /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u where | mk (v : Nat) : PNonScalar @[simp] theorem Nat.add_zero (n : Nat) : n + 0 = n := rfl theorem optParam_eq (α : Sort u) (default : α) : optParam α default = α := rfl /- Boolean operators -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem not_false : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variable {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem false_of_ne : a ≠ a → False := Ne.irrefl theorem ne_false_of_self : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem ne_true_of_not : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have : ¬True := h ▸ hnp this trivial theorem true_ne_false : ¬True = False := ne_false_of_self trivial end Ne section variable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := eq_of_heq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : a ≅ b) : b ≅ a := HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a) theorem heq_of_eq (h : a = a') : a ≅ a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := HEq.subst h₂ h₁ theorem heq_of_heq_of_eq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := HEq.trans h₁ (heq_of_eq h₂) theorem heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := HEq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a ≅ b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α) end theorem eqRec_heq {α : Sort u} {φ : α → Sort v} {a a' : α} : (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p | rfl, p => HEq.refl p theorem heq_of_eqRec_eq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by subst h₁ apply heq_of_eq exact h₂ theorem cast_heq {α β : Sort u} : (h : α = β) → (a : α) → cast h a ≅ a | rfl, a => HEq.refl a variable {a b c d : Prop} theorem iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) protected theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decide_true_eq_true (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decide_false_eq_false (h : Decidable False) : @decide False h = false := match h with | isFalse h => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := decide p (h := d) theorem toBoolUsing_eq_true {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := decide_eq_true (s := d) h theorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := of_decide_eq_true (s := d) h theorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := of_decide_eq_false (s := d) h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse not_false namespace Decidable variable {p q : Prop} @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem of_not_not [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem not_and_iff_or_not (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variable {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /- if-then-else expression theorems -/ theorem if_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | isTrue hc => rfl | isFalse hnc => absurd hc hnc theorem if_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | isTrue hc => absurd hc hnc | isFalse hnc => rfl theorem dif_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | isTrue hc => rfl | isFalse hnc => absurd hc hnc theorem dif_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | isTrue hc => absurd hc hnc | isFalse hnc => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem dif_eq_if (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | isTrue hc => rfl | isFalse hnc => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | isTrue hc => dT | isFalse hc => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | isTrue hc => dT hc | isFalse hc => dE hc /- Inhabited -/ instance : Inhabited Prop where default := True deriving instance Inhabited for NonScalar, PNonScalar, True, ForInStep class inductive Nonempty (α : Sort u) : Prop where | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α := ⟨arbitrary⟩ theorem nonempty_of_exists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class Subsingleton (α : Sort u) : Prop where intro :: allEq : (a b : α) → a = b protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := h.allEq protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by subst h₂ apply heq_of_eq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | isTrue t₁ => fun | isTrue t₂ => rfl | isFalse f₂ => absurd t₁ f₂ | isFalse f₁ => fun | isTrue t₂ => absurd t₂ f₁ | isFalse f₂ => rfl theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | isTrue h => h₃ h | isFalse h => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where refl : ∀ x, r x x symm : ∀ {x y}, r x y → r y x trans : ∀ {x y z}, r x y → r y z → r x z def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variable {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where default := ⟨a, h⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /- Sum -/ section variable {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where default := Sum.inl arbitrary instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where default := Sum.inr arbitrary instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | Sum.inl a, Sum.inl b => if h : a = b then isTrue (h ▸ rfl) else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h | Sum.inr a, Sum.inr b => if h : a = b then isTrue (h ▸ rfl) else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h | Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h end /- Product -/ instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (arbitrary, arbitrary) instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun (a, b) (a', b') => match decEq a a' with | isTrue e₁ => match decEq b b' with | isTrue e₂ => isTrue (e₁ ▸ e₂ ▸ rfl) | isFalse n₂ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₂' n₂ | isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₁' n₁ instance [BEq α] [BEq β] : BEq (α × β) where beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂ instance [LT α] [LT β] : LT (α × β) where lt s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance prodHasDecidableLt [LT α] [LT β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.lt_def [LT α] [LT β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl theorem Prod.ext (p : α × β) : (p.1, p.2) = p := by cases p; rfl def Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /- Dependent products -/ theorem ex_of_PSigma {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /- Universe polymorphic unit -/ theorem PUnit.subsingleton (a b : PUnit) : a = b := by cases a; cases b; exact rfl @[simp] theorem PUnit.eq_punit (a : PUnit) : a = ⟨⟩ := PUnit.subsingleton a ⟨⟩ instance : Subsingleton PUnit := Subsingleton.intro PUnit.subsingleton instance : Inhabited PUnit where default := ⟨⟩ instance : DecidableEq PUnit := fun a b => isTrue (PUnit.subsingleton a b) /- Setoid -/ class Setoid (α : Sort u) where r : α → α → Prop iseqv {} : Equivalence r instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variable {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b theorem Eq.propIntro {a b : Prop} (h₁ : a → b) (h₂ : b → a) : a = b := propext <| Iff.intro h₁ h₂ gen_injective_theorems% Prod gen_injective_theorems% PProd gen_injective_theorems% MProd gen_injective_theorems% Subtype gen_injective_theorems% Fin gen_injective_theorems% Array gen_injective_theorems% Sum gen_injective_theorems% PSum gen_injective_theorems% Nat gen_injective_theorems% Option gen_injective_theorems% List gen_injective_theorems% Except gen_injective_theorems% EStateM.Result gen_injective_theorems% Lean.Name gen_injective_theorems% Lean.Syntax /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem Iff.subst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem exists_rep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := Quot.rec f h q protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → f a ≅ f b) : motive q := Quot.recOn q f fun a b p => eq_of_heq <| have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRec_heq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q := Quot.ind protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem exists_rep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.exists_rep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (c : (a b : α) → (p : a ≈ b) → f a ≅ f b) : motive q := Quot.hrecOn q f c end section universe uA uB uC variable {α : Sort uA} {β : Sort uB} {φ : Sort uC} variable [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₃ [s₃ : Setoid φ] {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) private theorem rel_of_eq [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b := fun h => rel_of_eq h end Exact section universe uA uB uC variable {α : Sort uA} {β : Sort uB} variable [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton apply g intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s inferInstance end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂ fun a₁ a₂ => match d a₁ a₂ with | isTrue h₁ => isTrue (Quotient.sound h₁) | isFalse h₂ => isFalse fun h => absurd (Quotient.exact h) h₂ /- Function extensionality -/ namespace Function variable {α : Sort u} {β : α → Sort v} protected def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Function.Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₃ → Function.Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl symm := Equiv.symm trans := Equiv.trans } end Function section open Quotient variable {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where allEq f₁ f₂ := funext (fun a => Subsingleton.elim (f₁ a) (f₂ a)) /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => Subsingleton.elim _ _) s instance : Subsingleton (Squash α) where allEq a b := by induction a using Squash.ind induction b using Squash.ind apply Quot.sound trivial namespace Lean /- Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your developement using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ constant reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
a973501226a5bd2d50f9ae1e79ef34c8862b8bba
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/Generic/Axioms/CategoryTheory.lean
c08d7bfdd1430f40840b70e8789558bc6e6d8077
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
8,657
lean
import Structure.Generic.Axioms.Universes import Structure.Generic.Axioms.AbstractFunctors import Structure.Generic.Axioms.AbstractEquivalences import Structure.Generic.Axioms.GeneralizedProperties import Structure.Generic.Axioms.InstanceEquivalences open GeneralizedRelation set_option autoBoundImplicitLocal false --set_option pp.universes true universes u v w -- We would also like to be able to manipulate such equivalences, and we need them to behave like -- isomorphisms when doing so, with `refl` as the identity, `symm` as inverse, and `trans` as composition. -- In other words, a structure with its equivalences is a category where every morphism has an inverse (as -- guaranteed by `symm`), i.e. it is a groupoid. Since equivalences have equivalences, it is actually a -- higher groupoid. -- -- (Of course, the same type may also have a category structure with more morphisms, but since we are -- defining a generalization of an equivalence relation, not a category, we wish to ignore such extra -- structure at this point.) -- -- We add three redundant axioms to avoid unnecessary computations. (Actually, this list of axioms was -- originally inspired by the seven corresponding lemmas in `data.equiv.basic` of mathlib in Lean 3: -- `symm_symm`, `trans_refl`, etc.) -- -- Remark: Interestingly, all axioms can be regarded as simplification rules (with the simplification for -- associativity being the omission of parentheses). With the addition of the three redundant axioms, they -- enable equational reasoning by transforming all possible terms into a "flat" canonical form. Besides -- making proofs trivial, this observation also suggests an alternative formalization of the axioms in -- terms of a simplification function. -- -- Note that for actual equivalence relations, the axioms are trivially satisfied in a proof-irrelevant -- system such as Lean. -- TODO: Introduce a specification that describes all of the redundancies in axioms, so that higher -- structures can force redundant data to be equal. section Morphisms variable {α : Sort u} {V : Universe.{v}} [HasInternalFunctors V] [HasInstanceEquivalences.{v, w} V] (R : GeneralizedRelation α V) variable [HasLinearFunOp V] [HasTrans R] @[reducible] def compCompRight (a b c d : α) : R a b ⟶ R b c ⟶ R c d ⟶ R a d := HasLinearFunOp.revCompFunFun (R b c) HasTrans.trans ⊙ HasTrans.trans @[reducible] def compCompLeft (a b c d : α) : R a b ⟶ R b c ⟶ R c d ⟶ R a d := HasLinearFunOp.swapFunFun (HasLinearFunOp.compFunFunFun (R c d) (R b d) (R a d) ⊙ HasTrans.trans) ⊙ HasTrans.trans theorem compCompRight.eff [HasEquivCongrFun V] {a b c d : α} (f : R a b) (g : R b c) (h : R c d) : (compCompRight R a b c d) f g h = h • (g • f) := by simp; rfl theorem compCompLeft.eff [HasEquivCongrFun V] {a b c d : α} (f : R a b) (g : R b c) (h : R c d) : (compCompLeft R a b c d) f g h = (h • g) • f := by simp; rfl class IsCompositionRelation : Sort (max 1 u v w) where (assoc {a b c d : α} : compCompRight R a b c d ≃ compCompLeft R a b c d) variable [HasRefl R] @[reducible] def leftMulId (a b : α) : R a b ⟶ R a b := HasTrans.revTrans ⟮ident R b⟯ @[reducible] def rightMulId (a b : α) : R a b ⟶ R a b := HasTrans.trans ⟮ident R a⟯ theorem leftMulId.eff [HasEquivCongrFun V] {a b : α} (f : R a b) : (leftMulId R a b) f = ident R b • f := by simp; rfl theorem rightMulId.eff [HasEquivCongrFun V] {a b : α} (f : R a b) : (rightMulId R a b) f = f • ident R a := rfl class IsMorphismRelation extends IsCompositionRelation R : Sort (max 1 u v w) where (leftId {a b : α} : leftMulId R a b ≃ HasLinearFunOp.idFun (R a b)) (rightId {a b : α} : rightMulId R a b ≃ HasLinearFunOp.idFun (R a b)) variable [HasSubLinearFunOp V] [HasNonLinearFunOp V] [HasInternalEquivalences V] [HasSymm R] @[reducible] def leftMulInv (a b : α) : R a b ⟶ R a a := HasNonLinearFunOp.dupFun (HasTrans.revTrans ⊙ HasInternalEquivalences.toFun HasSymm.symm) @[reducible] def rightMulInv (a b : α) : R a b ⟶ R b b := HasNonLinearFunOp.dupFun (HasTrans.trans ⊙ HasInternalEquivalences.toFun HasSymm.symm) theorem leftMulInv.eff [HasEquivCongrFun V] {a b : α} (f : R a b) : (leftMulInv R a b) f = f⁻¹ • f := by simp; rfl theorem rightMulInv.eff [HasEquivCongrFun V] {a b : α} (f : R a b) : (rightMulInv R a b) f = f • f⁻¹ := by simp; rfl class IsIsomorphismRelation extends IsMorphismRelation R : Sort (max 1 u v w) where (leftInv {a b : α} : leftMulInv R a b ≃ HasSubLinearFunOp.constFun (R a b) (ident R a)) (rightInv {a b : α} : rightMulInv R a b ≃ HasSubLinearFunOp.constFun (R a b) (ident R b)) -- TODO: convert to lemmas? --(invInv {a b : α} (f : R a b) : (f⁻¹)⁻¹ ≃ f) --(compInv {a b c : α} (f : R a b) (g : R b c) : (g • f)⁻¹ ≃ f⁻¹ • g⁻¹) --(idInv (a : α) : (ident R a)⁻¹ ≃ ident R a) end Morphisms -- TODO: Rephrase trans and symm as functor composition. section Functors variable {α : Sort u} {V W : Universe} [HasInstanceEquivalences W] [HasExternalFunctors V W] (R : GeneralizedRelation α V) (S : GeneralizedRelation α W) def BaseFunctor := ∀ {a b}, R a b ⟶' S a b variable (F : BaseFunctor R S) class IsReflFunctor [hR : HasRefl R] [hS : HasRefl S] where (respectsRefl (a : α) : F (hR.refl a) ≃ hS.refl a) variable [HasInternalFunctors V] [HasInternalFunctors W] class IsTransFunctor [hR : HasTrans R] [hS : HasTrans S] where (respectsTrans {a b c : α} (f : R a b) (g : R b c) : F (hR.trans' f g) ≃ hS.trans' (F f) (F g)) class IsPreorderFunctor [IsPreorder R] [IsPreorder S] extends IsReflFunctor R S F, IsTransFunctor R S F variable [HasInternalEquivalences V] [HasInternalEquivalences W] class IsSymmFunctor [hR : HasSymm R] [hS : HasSymm S] where (respectsSymm {a b : α} (f : R a b) : F (hR.symm' f) ≃ hS.symm' (F f)) class IsEquivalenceFunctor [IsEquivalence R] [IsEquivalence S] extends IsPreorderFunctor R S F, IsSymmFunctor R S F end Functors -- TODO: If arrows have equivalences, we can specify redundancies in axioms as such equivalences. section NaturalTransformations variable {α : Sort u} {β : Sort v} {V W : Universe} [HasExternalFunctors V W] (R : GeneralizedRelation α V) (S : GeneralizedRelation β W) def MappedBaseFunctor (m : α → β) := ∀ {a b}, R a b ⟶' S (m a) (m b) variable [HasInternalFunctors W] [HasInstanceEquivalences W] [h : HasTrans S] {mF mG : α → β} (F : MappedBaseFunctor R S mF) (G : MappedBaseFunctor R S mG) class IsNatural (n : ∀ a, S (mF a) (mG a)) where (nat {a b : α} (f : R a b) : h.trans' (n a) (G f) ≃ h.trans' (F f) (n b)) -- The following definitions specify how we can treat a natural quantification as an element of `W`. -- TODO: Maybe we can replace this with a more general quantification mechanism. structure NaturalQuantification where (n : ∀ a, S (mF a) (mG a)) [isNatural : IsNatural R S F G n] class HasInternalNaturalQuantification where (Nat : W) (natEquiv : ⌈Nat⌉ ≃ NaturalQuantification R S F G) end NaturalTransformations class HasNaturalQuantification (U₁ U₂ V W : Universe) [HasExternalFunctors U₁ U₂] [HasExternalFunctors V W] [HasInternalFunctors W] [HasInstanceEquivalences W] where [hasNat {α : U₁} {β : U₂} (R : GeneralizedRelation ⌈α⌉ V) (S : GeneralizedRelation ⌈β⌉ W) [h : HasTrans S] {mF mG : α ⟶' β} (F : MappedBaseFunctor R S mF) (G : MappedBaseFunctor R S mG) : HasInternalNaturalQuantification R S F G] section Categories variable (M : Universe.{v}) [HasInternalFunctors M] [HasLinearFunOp M] [HasInstanceEquivalences.{v, w} M] (α : Sort u) class IsCategory extends HasArrows α M : Sort (max 1 u (v + 1) w) where [isMor : IsMorphismRelation Arrow] namespace IsCategory variable [h : IsCategory M α] instance hasMor : IsMorphismRelation h.Arrow := h.isMor end IsCategory variable [HasSubLinearFunOp M] [HasNonLinearFunOp M] [HasInternalEquivalences M] class IsGroupoid extends HasEquivalences α M : Sort (max 1 u (v + 1) w) where [isIso : IsIsomorphismRelation Equiv] namespace IsGroupoid variable [h : IsGroupoid M α] instance hasIso : IsIsomorphismRelation h.Equiv := h.isIso end IsGroupoid end Categories
ca5eff603c6038aeb0ddab57534618a4a4f5621c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coesec.lean
d01e213d72ce1d815c2d08dd4389b9eaa3f81d96
[ "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
207
lean
inductive func (A B : Type) := mk : (A → B) → func A B section variables {A B : Type} definition to_function (F : func A B) : A → B := func.rec (λf, f) F attribute to_function [coercion] end
456e7867fdace7437e83544f6942f06241db1c18
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/synth1.lean
5a3b1bb39fb845b886f059ab5aa41e6c77a78eae
[ "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,385
lean
import Init.Lean.Meta open Lean open Lean.Meta class HasCoerce (a b : Type) := (coerce : a → b) def coerce {a b : Type} [HasCoerce a b] : a → b := @HasCoerce.coerce a b _ instance coerceTrans {a b c : Type} [HasCoerce b c] [HasCoerce a b] : HasCoerce a c := ⟨fun x => coerce (coerce x : b)⟩ instance coerceBoolToProp : HasCoerce Bool Prop := ⟨fun y => y = true⟩ instance coerceDecidableEq (x : Bool) : Decidable (coerce x) := inferInstanceAs (Decidable (x = true)) instance coerceNatToBool : HasCoerce Nat Bool := ⟨fun x => x == 0⟩ instance coerceNatToInt : HasCoerce Nat Int := ⟨fun x => Int.ofNat x⟩ def print {α} [HasToString α] (a : α) : MetaM Unit := trace! `Meta.synthInstance (toString a) set_option trace.Meta.synthInstance true set_option trace.Meta.synthInstance.tryResolve false def tst1 : MetaM Unit := do inst ← mkAppM `HasCoerce #[mkConst `Nat, mkSort levelZero]; r ← synthInstance inst; print r #eval tst1 def tst2 : MetaM Unit := do inst ← mkAppM `HasBind #[mkConst `IO]; -- globalInstances ← getGlobalInstances; -- print (format globalInstances); -- result ← globalInstances.getUnify inst; -- print result; r ← synthInstance inst; print r; pure () #eval tst2 def tst3 : MetaM Unit := do inst ← mkAppM `HasBeq #[mkConst `Nat]; r ← synthInstance inst; print r; pure () #eval tst3
fcbaaa586c0d9db87901fce4690efe921e73832e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/int/basic.lean
7b73d2e812b09c569d876733ae46ba954b75c63c
[ "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
47,619
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /- Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : decidable_linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_lt_one := int.zero_lt_one, .. int.comm_ring, .. int.decidable_linear_order, .. int.nontrivial } instance : decidable_linear_ordered_add_comm_group int := by apply_instance theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply mul_right_cancel' h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 := to_nat_add h (zero_le_one) def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical end int
0d74378636966af7472949fbaa47d31d8e05483e
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/geometry/euclidean/triangle.lean
de58f1b6cc0ff22ba3cb79c267cf4ed78f94a0c4
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,270
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import geometry.euclidean.basic import tactic.interval_cases /-! # Triangles This file proves basic geometrical results about distances and angles in (possibly degenerate) triangles in real inner product spaces and Euclidean affine spaces. More specialized results, and results developed for simplices in general rather than just for triangles, are in separate files. Definitions and results that make sense in more general affine spaces rather than just in the Euclidean case go under `linear_algebra.affine_space`. ## Implementation notes Results in this file are generally given in a form with only those non-degeneracy conditions needed for the particular result, rather than requiring affine independence of the points of a triangle unnecessarily. ## References * https://en.wikipedia.org/wiki/Pythagorean_theorem * https://en.wikipedia.org/wiki/Law_of_cosines * https://en.wikipedia.org/wiki/Pons_asinorum * https://en.wikipedia.org/wiki/Sum_of_angles_of_a_triangle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace inner_product_geometry /-! ### Geometrical results on triangles in real inner product spaces This section develops some results on (possibly degenerate) triangles in real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- Pythagorean theorem, if-and-only-if vector angle form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ angle x y = π / 2 := begin rw norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, vector angle form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ angle x y = π / 2 := begin rw norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, subtracting vectors, vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- Law of cosines (cosine rule), vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle (x y : V) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - 2 * ∥x∥ * ∥y∥ * real.cos (angle x y) := by rw [(show 2 * ∥x∥ * ∥y∥ * real.cos (angle x y) = 2 * (real.cos (angle x y) * (∥x∥ * ∥y∥)), by ring), cos_angle_mul_norm_mul_norm, ←real_inner_self_eq_norm_sq, ←real_inner_self_eq_norm_sq, ←real_inner_self_eq_norm_sq, real_inner_sub_sub_self, sub_add_eq_add_sub] /-- Pons asinorum, vector angle form. -/ lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : angle x (x - y) = angle y (y - x) := begin refine real.inj_on_cos ⟨angle_nonneg _ _, angle_le_pi _ _⟩ ⟨angle_nonneg _ _, angle_le_pi _ _⟩ _, rw [cos_angle, cos_angle, h, ←neg_sub, norm_neg, neg_sub, inner_sub_right, inner_sub_right, real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, h, real_inner_comm x y] end /-- Converse of pons asinorum, vector angle form. -/ lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V} (h : angle x (x - y) = angle y (y - x)) (hpi : angle x y ≠ π) : ∥x∥ = ∥y∥ := begin replace h := real.arccos_inj_on (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x (x - y))) (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one y (y - x))) h, by_cases hxy : x = y, { rw hxy }, { rw [←norm_neg (y - x), neg_sub, mul_comm, mul_comm ∥y∥, div_eq_mul_inv, div_eq_mul_inv, mul_inv_rev', mul_inv_rev', ←mul_assoc, ←mul_assoc] at h, replace h := mul_right_cancel' (inv_ne_zero (λ hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h, rw [inner_sub_right, inner_sub_right, real_inner_comm x y, real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, mul_sub_right_distrib, mul_sub_right_distrib, mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub, ←mul_sub_left_distrib] at h, by_cases hx0 : x = 0, { rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h, rw [hx0, norm_zero, h] }, { by_cases hy0 : y = 0, { rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h, rw [hy0, norm_zero, h] }, { rw [inv_sub_inv (λ hz, hx0 (norm_eq_zero.1 hz)) (λ hz, hy0 (norm_eq_zero.1 hz)), ←neg_sub, ←mul_div_assoc, mul_comm, mul_div_assoc, ←mul_neg_one] at h, symmetry, by_contradiction hyx, replace h := (mul_left_cancel' (sub_ne_zero_of_ne hyx) h).symm, rw [real_inner_div_norm_mul_norm_eq_neg_one_iff, ←angle_eq_pi_iff] at h, exact hpi h } } } end /-- The cosine of the sum of two angles in a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.cos (angle x (x - y) + angle y (y - x)) = -real.cos (angle x y) := begin by_cases hxy : x = y, { rw [hxy, angle_self hy], simp }, { rw [real.cos_add, cos_angle, cos_angle, cos_angle], have hxn : ∥x∥ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)), have hyn : ∥y∥ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)), have hxyn : ∥x - y∥ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))), apply mul_right_cancel' hxn, apply mul_right_cancel' hyn, apply mul_right_cancel' hxyn, apply mul_right_cancel' hxyn, have H1 : real.sin (angle x (x - y)) * real.sin (angle y (y - x)) * ∥x∥ * ∥y∥ * ∥x - y∥ * ∥x - y∥ = (real.sin (angle x (x - y)) * (∥x∥ * ∥x - y∥)) * (real.sin (angle y (y - x)) * (∥y∥ * ∥x - y∥)), { ring }, have H2 : ⟪x, x⟫ * (inner x x - inner x y - (inner x y - inner y y)) - (inner x x - inner x y) * (inner x x - inner x y) = inner x x * inner y y - inner x y * inner x y, { ring }, have H3 : ⟪y, y⟫ * (inner y y - inner x y - (inner x y - inner x x)) - (inner y y - inner x y) * (inner y y - inner x y) = inner x x * inner y y - inner x y * inner x y, { ring }, rw [mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y, sin_angle_mul_norm_mul_norm, norm_sub_rev y x, inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H2, H3, real.mul_self_sqrt (sub_nonneg_of_le (real_inner_mul_inner_self_le x y)), real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two], field_simp [hxn, hyn, hxyn], ring } end /-- The sine of the sum of two angles in a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma sin_angle_sub_add_angle_sub_rev_eq_sin_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.sin (angle x (x - y) + angle y (y - x)) = real.sin (angle x y) := begin by_cases hxy : x = y, { rw [hxy, angle_self hy], simp }, { rw [real.sin_add, cos_angle, cos_angle], have hxn : ∥x∥ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)), have hyn : ∥y∥ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)), have hxyn : ∥x - y∥ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))), apply mul_right_cancel' hxn, apply mul_right_cancel' hyn, apply mul_right_cancel' hxyn, apply mul_right_cancel' hxyn, have H1 : real.sin (angle x (x - y)) * (⟪y, y - x⟫ / (∥y∥ * ∥y - x∥)) * ∥x∥ * ∥y∥ * ∥x - y∥ = real.sin (angle x (x - y)) * (∥x∥ * ∥x - y∥) * (⟪y, y - x⟫ / (∥y∥ * ∥y - x∥)) * ∥y∥, { ring }, have H2 : ⟪x, x - y⟫ / (∥x∥ * ∥y - x∥) * real.sin (angle y (y - x)) * ∥x∥ * ∥y∥ * ∥y - x∥ = ⟪x, x - y⟫ / (∥x∥ * ∥y - x∥) * (real.sin (angle y (y - x)) * (∥y∥ * ∥y - x∥)) * ∥x∥, { ring }, have H3 : ⟪x, x⟫ * (⟪x, x⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪y, y⟫)) - (⟪x, x⟫ - ⟪x, y⟫) * (⟪x, x⟫ - ⟪x, y⟫) = ⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring }, have H4 : ⟪y, y⟫ * (⟪y, y⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪x, x⟫)) - (⟪y, y⟫ - ⟪x, y⟫) * (⟪y, y⟫ - ⟪x, y⟫) = ⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring }, rw [right_distrib, right_distrib, right_distrib, right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y, H2, sin_angle_mul_norm_mul_norm, norm_sub_rev y x, mul_assoc (real.sin (angle x y)), sin_angle_mul_norm_mul_norm, inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H3, H4, real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two], field_simp [hxn, hyn, hxyn], ring } end /-- The cosine of the sum of the angles of a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma cos_angle_add_angle_sub_add_angle_sub_eq_neg_one {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.cos (angle x y + angle x (x - y) + angle y (y - x)) = -1 := by rw [add_assoc, real.cos_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy, sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy, ←neg_mul_eq_mul_neg, ←neg_add', add_comm, ←sq, ←sq, real.sin_sq_add_cos_sq] /-- The sine of the sum of the angles of a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma sin_angle_add_angle_sub_add_angle_sub_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.sin (angle x y + angle x (x - y) + angle y (y - x)) = 0 := begin rw [add_assoc, real.sin_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy, sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy], ring end /-- The sum of the angles of a possibly degenerate triangle (where the two given sides are nonzero), vector angle form. -/ lemma angle_add_angle_sub_add_angle_sub_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : angle x y + angle x (x - y) + angle y (y - x) = π := begin have hcos := cos_angle_add_angle_sub_add_angle_sub_eq_neg_one hx hy, have hsin := sin_angle_add_angle_sub_add_angle_sub_eq_zero hx hy, rw real.sin_eq_zero_iff at hsin, cases hsin with n hn, symmetry' at hn, have h0 : 0 ≤ angle x y + angle x (x - y) + angle y (y - x) := add_nonneg (add_nonneg (angle_nonneg _ _) (angle_nonneg _ _)) (angle_nonneg _ _), have h3 : angle x y + angle x (x - y) + angle y (y - x) ≤ π + π + π := add_le_add (add_le_add (angle_le_pi _ _) (angle_le_pi _ _)) (angle_le_pi _ _), have h3lt : angle x y + angle x (x - y) + angle y (y - x) < π + π + π, { by_contradiction hnlt, have hxy : angle x y = π, { by_contradiction hxy, exact hnlt (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le (lt_of_le_of_ne (angle_le_pi _ _) hxy) (angle_le_pi _ _)) (angle_le_pi _ _)) }, rw hxy at hnlt, rw angle_eq_pi_iff at hxy, rcases hxy with ⟨hx, ⟨r, ⟨hr, hxr⟩⟩⟩, rw [hxr, ←one_smul ℝ x, ←mul_smul, mul_one, ←sub_smul, one_smul, sub_eq_add_neg, angle_smul_right_of_pos _ _ (add_pos zero_lt_one (neg_pos_of_neg hr)), angle_self hx, add_zero] at hnlt, apply hnlt, rw add_assoc, exact add_lt_add_left (lt_of_le_of_lt (angle_le_pi _ _) (lt_add_of_pos_right π real.pi_pos)) _ }, have hn0 : 0 ≤ n, { rw [hn, mul_nonneg_iff_right_nonneg_of_pos real.pi_pos] at h0, norm_cast at h0, exact h0 }, have hn3 : n < 3, { rw [hn, (show π + π + π = 3 * π, by ring)] at h3lt, replace h3lt := lt_of_mul_lt_mul_right h3lt (le_of_lt real.pi_pos), norm_cast at h3lt, exact h3lt }, interval_cases n, { rw hn at hcos, simp at hcos, norm_num at hcos }, { rw hn, norm_num }, { rw hn at hcos, simp at hcos, norm_num at hcos }, end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on triangles in Euclidean affine spaces This section develops some geometrical definitions and results on (possible degenerate) triangles in Euclidean affine spaces. -/ open inner_product_geometry open_locale euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- **Pythagorean theorem**, if-and-only-if angle-at-point form. -/ lemma dist_sq_eq_dist_sq_add_dist_sq_iff_angle_eq_pi_div_two (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 ↔ ∠ p1 p2 p3 = π / 2 := by erw [pseudo_metric_space.dist_comm p3 p2, dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p2 p3, ←norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two, vsub_sub_vsub_cancel_right p1, ←neg_vsub_eq_vsub_rev p2 p3, norm_neg] /-- **Law of cosines** (cosine rule), angle-at-point form. -/ lemma dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 - 2 * dist p1 p2 * dist p3 p2 * real.cos (∠ p1 p2 p3) := begin rw [dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p3 p2], unfold angle, convert norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2 : V), { exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm }, { exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm } end alias dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle ← law_cos /-- **Isosceles Triangle Theorem**: Pons asinorum, angle-at-point form. -/ lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) : ∠ p1 p2 p3 = ∠ p1 p3 p2 := begin rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3] at h, unfold angle, convert angle_sub_eq_angle_sub_rev_of_norm_eq h, { exact (vsub_sub_vsub_cancel_left p3 p2 p1).symm }, { exact (vsub_sub_vsub_cancel_left p2 p3 p1).symm } end /-- Converse of pons asinorum, angle-at-point form. -/ lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = ∠ p1 p3 p2) (hpi : ∠ p2 p1 p3 ≠ π) : dist p1 p2 = dist p1 p3 := begin unfold angle at h hpi, rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3], rw [←angle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi, rw [←vsub_sub_vsub_cancel_left p3 p2 p1, ←vsub_sub_vsub_cancel_left p2 p3 p1] at h, exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi end /-- The **sum of the angles of a triangle** (possibly degenerate, where the given vertex is distinct from the others), angle-at-point. -/ lemma angle_add_angle_add_angle_eq_pi {p1 p2 p3 : P} (h2 : p2 ≠ p1) (h3 : p3 ≠ p1) : ∠ p1 p2 p3 + ∠ p2 p3 p1 + ∠ p3 p1 p2 = π := begin rw [add_assoc, add_comm, add_comm (∠ p2 p3 p1), angle_comm p2 p3 p1], unfold angle, rw [←angle_neg_neg (p1 -ᵥ p3), ←angle_neg_neg (p1 -ᵥ p2), neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, ←vsub_sub_vsub_cancel_right p3 p2 p1, ←vsub_sub_vsub_cancel_right p2 p3 p1], exact angle_add_angle_sub_add_angle_sub_eq_pi (λ he, h3 (vsub_eq_zero_iff_eq.1 he)) (λ he, h2 (vsub_eq_zero_iff_eq.1 he)) end /-- **Stewart's Theorem**. -/ theorem dist_sq_mul_dist_add_dist_sq_mul_dist (a b c p : P) (h : ∠ b p c = π) : dist a b ^ 2 * dist c p + dist a c ^ 2 * dist b p = dist b c * (dist a p ^ 2 + dist b p * dist c p) := begin rw [pow_two, pow_two, law_cos a p b, law_cos a p c, eq_sub_of_add_eq (angle_add_angle_eq_pi_of_angle_eq_pi a h), real.cos_pi_sub, dist_eq_add_dist_of_angle_eq_pi h], ring, end /-- **Apollonius's Theorem**. -/ theorem dist_sq_add_dist_sq_eq_two_mul_dist_midpoint_sq_add_half_dist_sq (a b c : P) : dist a b ^ 2 + dist a c ^ 2 = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) := begin by_cases hbc : b = c, { simp [hbc, midpoint_self, dist_self, two_mul] }, { let m := midpoint ℝ b c, have : dist b c ≠ 0 := (dist_pos.mpr hbc).ne', have hm := dist_sq_mul_dist_add_dist_sq_mul_dist a b c m (angle_midpoint_eq_pi b c hbc), simp only [dist_left_midpoint, dist_right_midpoint, real.norm_two] at hm, calc dist a b ^ 2 + dist a c ^ 2 = 2 / dist b c * (dist a b ^ 2 * (2⁻¹ * dist b c) + dist a c ^ 2 * (2⁻¹ * dist b c)) : by { field_simp, ring } ... = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) : by { rw hm, field_simp, ring } }, end lemma dist_mul_of_eq_angle_of_dist_mul (a b c a' b' c' : P) (r : ℝ) (h : ∠ a' b' c' = ∠ a b c) (hab : dist a' b' = r * dist a b) (hcb : dist c' b' = r * dist c b) : dist a' c' = r * dist a c := begin have h' : dist a' c' ^ 2 = (r * dist a c) ^ 2, calc dist a' c' ^ 2 = dist a' b' ^ 2 + dist c' b' ^ 2 - 2 * dist a' b' * dist c' b' * real.cos (∠ a' b' c') : by { simp [pow_two, law_cos a' b' c'] } ... = r ^ 2 * (dist a b ^ 2 + dist c b ^ 2 - 2 * dist a b * dist c b * real.cos (∠ a b c)) : by { rw [h, hab, hcb], ring } ... = (r * dist a c) ^ 2 : by simp [pow_two, ← law_cos a b c, mul_pow], by_cases hab₁ : a = b, { have hab'₁ : a' = b', { rw [← dist_eq_zero, hab, dist_eq_zero.mpr hab₁, mul_zero r] }, rw [hab₁, hab'₁, dist_comm b' c', dist_comm b c, hcb] }, { have h1 : 0 ≤ r * dist a b, { rw ← hab, exact dist_nonneg }, have h2 : 0 ≤ r := nonneg_of_mul_nonneg_right h1 (dist_pos.mpr hab₁), exact (sq_eq_sq dist_nonneg (mul_nonneg h2 dist_nonneg)).mp h' }, end end euclidean_geometry
a9a25fc59c233df07689e2339509de4373ed6a70
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/init/nat.lean
d01bce9545f8e399de99b9b53d9d15e6f20e71c2
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,273
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.nat Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.wf init.tactic init.num open eq.ops decidable namespace nat notation `ℕ` := nat inductive lt (a : nat) : nat → Prop := | base : lt a (succ a) | step : Π {b}, lt a b → lt a (succ b) notation a < b := lt a b definition le [reducible] (a b : nat) : Prop := a < succ b notation a ≤ b := le a b definition pred (a : nat) : nat := nat.cases_on a zero (λ a₁, a₁) protected definition is_inhabited [instance] : inhabited nat := inhabited.mk zero protected definition has_decidable_eq [instance] : ∀ x y : nat, decidable (x = y) | has_decidable_eq zero zero := inl rfl | has_decidable_eq (succ x) zero := inr (λ h, nat.no_confusion h) | has_decidable_eq zero (succ y) := inr (λ h, nat.no_confusion h) | has_decidable_eq (succ x) (succ y) := if H : x = y then inl (eq.rec_on H rfl) else inr (λ h : succ x = succ y, nat.no_confusion h (λ heq : x = y, absurd heq H)) -- less-than is well-founded definition lt.wf [instance] : well_founded lt := well_founded.intro (λn, nat.rec_on n (acc.intro zero (λ (y : nat) (hlt : y < zero), have aux : ∀ {n₁}, y < n₁ → zero = n₁ → acc lt y, from λ n₁ hlt, nat.lt.cases_on hlt (λ heq, nat.no_confusion heq) (λ b hlt heq, nat.no_confusion heq), aux hlt rfl)) (λ (n : nat) (ih : acc lt n), acc.intro (succ n) (λ (m : nat) (hlt : m < succ n), have aux : ∀ {n₁} (hlt : m < n₁), succ n = n₁ → acc lt m, from λ n₁ hlt, nat.lt.cases_on hlt (λ (heq : succ n = succ m), nat.no_confusion heq (λ (e : n = m), eq.rec_on e ih)) (λ b (hlt : m < b) (heq : succ n = succ b), nat.no_confusion heq (λ (e : n = b), acc.inv (eq.rec_on e ih) hlt)), aux hlt rfl))) definition measure {A : Type} (f : A → nat) : A → A → Prop := inv_image lt f definition measure.wf {A : Type} (f : A → nat) : well_founded (measure f) := inv_image.wf f lt.wf definition not_lt_zero (a : nat) : ¬ a < zero := have aux : ∀ {b}, a < b → b = zero → false, from λ b H, lt.cases_on H (λ heq, nat.no_confusion heq) (λ b h₁ heq, nat.no_confusion heq), λ H, aux H rfl definition zero_lt_succ (a : nat) : zero < succ a := nat.rec_on a (lt.base zero) (λ a (hlt : zero < succ a), lt.step hlt) definition lt.trans {a b c : nat} (H₁ : a < b) (H₂ : b < c) : a < c := have aux : ∀ {d}, d < c → b = d → a < b → a < c, from (λ d H, lt.rec_on H (λ h₁ h₂, lt.step (eq.rec_on h₁ h₂)) (λ b hl ih h₁ h₂, lt.step (ih h₁ h₂))), aux H₂ rfl H₁ definition succ_lt_succ {a b : nat} (H : a < b) : succ a < succ b := lt.rec_on H (lt.base (succ a)) (λ b hlt ih, lt.trans ih (lt.base (succ b))) definition lt_of_succ_lt {a b : nat} (H : succ a < b) : a < b := have aux : ∀ {a₁}, a₁ < b → succ a = a₁ → a < b, from λ a₁ H, lt.rec_on H (λ e₁, eq.rec_on e₁ (lt.step (lt.base a))) (λ d hlt ih e₁, lt.step (ih e₁)), aux H rfl definition lt_of_succ_lt_succ {a b : nat} (H : succ a < succ b) : a < b := have aux : pred (succ a) < pred (succ b), from lt.rec_on H (lt.base a) (λ (b : nat) (hlt : succ a < b) ih, show pred (succ a) < pred (succ b), from lt_of_succ_lt hlt), aux definition decidable_lt [instance] : decidable_rel lt := λ a b, nat.rec_on b (λ (a : nat), inr (not_lt_zero a)) (λ (b₁ : nat) (ih : ∀ a, decidable (a < b₁)) (a : nat), nat.cases_on a (inl !zero_lt_succ) (λ a, decidable.rec_on (ih a) (λ h_pos : a < b₁, inl (succ_lt_succ h_pos)) (λ h_neg : ¬ a < b₁, have aux : ¬ succ a < succ b₁, from λ h : succ a < succ b₁, h_neg (lt_of_succ_lt_succ h), inr aux))) a definition le.refl (a : nat) : a ≤ a := lt.base a definition le_of_lt {a b : nat} (H : a < b) : a ≤ b := lt.step H definition eq_or_lt_of_le {a b : nat} (H : a ≤ b) : a = b ∨ a < b := begin cases H with [b, hlt], apply (or.inl rfl), apply (or.inr hlt) end definition le_of_eq_or_lt {a b : nat} (H : a = b ∨ a < b) : a ≤ b := or.rec_on H (λ hl, eq.rec_on hl !le.refl) (λ hr, le_of_lt hr) definition decidable_le [instance] : decidable_rel le := λ a b, decidable_of_decidable_of_iff _ (iff.intro le_of_eq_or_lt eq_or_lt_of_le) definition le.rec_on {a : nat} {P : nat → Prop} {b : nat} (H : a ≤ b) (H₁ : P a) (H₂ : ∀ b, a < b → P b) : P b := begin cases H with [b', hlt], apply H₁, apply (H₂ b' hlt) end definition lt.irrefl (a : nat) : ¬ a < a := nat.rec_on a !not_lt_zero (λ (a : nat) (ih : ¬ a < a) (h : succ a < succ a), ih (lt_of_succ_lt_succ h)) definition lt.asymm {a b : nat} (H : a < b) : ¬ b < a := lt.rec_on H (λ h : succ a < a, !lt.irrefl (lt_of_succ_lt h)) (λ b hlt (ih : ¬ b < a) (h : succ b < a), ih (lt_of_succ_lt h)) definition lt.trichotomy (a b : nat) : a < b ∨ a = b ∨ b < a := nat.rec_on b (λa, nat.cases_on a (or.inr (or.inl rfl)) (λ a₁, or.inr (or.inr !zero_lt_succ))) (λ b₁ (ih : ∀a, a < b₁ ∨ a = b₁ ∨ b₁ < a) (a : nat), nat.cases_on a (or.inl !zero_lt_succ) (λ a, or.rec_on (ih a) (λ h : a < b₁, or.inl (succ_lt_succ h)) (λ h, or.rec_on h (λ h : a = b₁, or.inr (or.inl (eq.rec_on h rfl))) (λ h : b₁ < a, or.inr (or.inr (succ_lt_succ h)))))) a definition eq_or_lt_of_not_lt {a b : nat} (hnlt : ¬ a < b) : a = b ∨ b < a := or.rec_on (lt.trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) definition lt_succ_of_le {a b : nat} (h : a ≤ b) : a < succ b := h definition lt_of_succ_le {a b : nat} (h : succ a ≤ b) : a < b := lt_of_succ_lt_succ h definition le_succ_of_le {a b : nat} (h : a ≤ b) : a ≤ succ b := lt.step h definition succ_le_of_lt {a b : nat} (h : a < b) : succ a ≤ b := succ_lt_succ h definition le.trans {a b c : nat} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := begin cases h₁ with [b', hlt], apply h₂, apply (lt.trans hlt h₂) end definition lt_of_le_of_lt {a b c : nat} (h₁ : a ≤ b) (h₂ : b < c) : a < c := begin cases h₁ with [b', hlt], apply h₂, apply (lt.trans hlt h₂) end definition lt_of_lt_of_le {a b c : nat} (h₁ : a < b) (h₂ : b ≤ c) : a < c := begin cases h₁ with [b', hlt], apply (lt_of_succ_lt_succ h₂), apply (lt.trans hlt (lt_of_succ_lt_succ h₂)) end calc_trans lt.trans calc_trans lt_of_le_of_lt calc_trans lt_of_lt_of_le calc_trans le.trans definition max (a b : nat) : nat := if a < b then b else a definition min (a b : nat) : nat := if a < b then a else b definition max_self (a : nat) : max a a = a := eq.rec_on !if_t_t rfl definition max_eq_right {a b : nat} (H : a < b) : max a b = b := if_pos H definition max_eq_left {a b : nat} (H : ¬ a < b) : max a b = a := if_neg H definition eq_max_right {a b : nat} (H : a < b) : b = max a b := eq.rec_on (max_eq_right H) rfl definition eq_max_left {a b : nat} (H : ¬ a < b) : a = max a b := eq.rec_on (max_eq_left H) rfl definition le_max_left (a b : nat) : a ≤ max a b := by_cases (λ h : a < b, le_of_lt (eq.rec_on (eq_max_right h) h)) (λ h : ¬ a < b, eq.rec_on (eq_max_left h) !le.refl) definition le_max_right (a b : nat) : b ≤ max a b := by_cases (λ h : a < b, eq.rec_on (eq_max_right h) !le.refl) (λ h : ¬ a < b, or.rec_on (eq_or_lt_of_not_lt h) (λ heq, eq.rec_on heq (eq.rec_on (eq.symm (max_self a)) !le.refl)) (λ h : b < a, have aux : a = max a b, from eq_max_left (lt.asymm h), eq.rec_on aux (le_of_lt h))) definition gt [reducible] a b := lt b a definition decidable_gt [instance] : decidable_rel gt := _ notation a > b := gt a b definition ge [reducible] a b := le b a definition decidable_ge [instance] : decidable_rel ge := _ notation a ≥ b := ge a b -- add is defined in init.num definition sub (a b : nat) : nat := nat.rec_on b a (λ b₁ r, pred r) notation a - b := sub a b definition mul (a b : nat) : nat := nat.rec_on b zero (λ b₁ r, r + a) notation a * b := mul a b section local attribute sub [reducible] definition succ_sub_succ_eq_sub (a b : nat) : succ a - succ b = a - b := nat.induction_on b rfl (λ b₁ (ih : succ a - succ b₁ = a - b₁), eq.rec_on ih (eq.refl (pred (succ a - succ b₁)))) end definition sub_eq_succ_sub_succ (a b : nat) : a - b = succ a - succ b := eq.rec_on (succ_sub_succ_eq_sub a b) rfl definition zero_sub_eq_zero (a : nat) : zero - a = zero := nat.induction_on a rfl (λ a₁ (ih : zero - a₁ = zero), eq.rec_on ih (eq.refl (pred (zero - a₁)))) definition zero_eq_zero_sub (a : nat) : zero = zero - a := eq.rec_on (zero_sub_eq_zero a) rfl definition sub_lt {a b : nat} : zero < a → zero < b → a - b < a := have aux : Π {a}, zero < a → Π {b}, zero < b → a - b < a, from λa h₁, lt.rec_on h₁ (λb h₂, lt.cases_on h₂ (lt.base zero) (λ b₁ bpos, eq.rec_on (sub_eq_succ_sub_succ zero b₁) (eq.rec_on (zero_eq_zero_sub b₁) (lt.base zero)))) (λa₁ apos ih b h₂, lt.cases_on h₂ (lt.base a₁) (λ b₁ bpos, eq.rec_on (sub_eq_succ_sub_succ a₁ b₁) (lt.trans (@ih b₁ bpos) (lt.base a₁)))), λ h₁ h₂, aux h₁ h₂ definition pred_le (a : nat) : pred a ≤ a := nat.cases_on a (le.refl zero) (λ a₁, le_of_lt (lt.base a₁)) definition sub_le (a b : nat) : a - b ≤ a := nat.induction_on b (le.refl a) (λ b₁ ih, le.trans !pred_le ih) end nat
70198f94bcf008c33f564eee598bd70788b7fefc
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/topologie-espaces-normés/cpge_ten_04.lean
33a436b0dc4ff35d1a8f43e4a9f1ecc3c961719d
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
483
lean
import data.set.basic import topology.basic import algebra.module.basic import algebra.module.submodule import order.complete_lattice import analysis.normed_space.basic -- Soient F une partie fermée non vide d'un espace normé E et x ∈ E . Montrer -- d(x, F ) = 0 ⇐⇒ x ∈ F . theorem exo {R E: Type*} [normed_field R] [normed_group E] [normed_space R E] : forall (F: set E) (x: E), (is_closed F) -> (set.nonempty F) -> set.mem x F <-> infi (dist x) = 0 := sorry
d2e8b58b3bfadd3361efeabf11eaf3f5c14370d0
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/category/Cat.lean
0264f8b2aae6b9d9a63a2b63a1185dce551f687b
[ "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
3,587
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.concrete_category.bundled import category_theory.discrete_category import category_theory.types import category_theory.bicategory.strict /-! # Category of categories This file contains the definition of the category `Cat` of all categories. In this category objects are categories and morphisms are functors between these categories. ## Implementation notes Though `Cat` is not a concrete category, we use `bundled` to define its carrier type. -/ universes v u namespace category_theory /-- Category of categories. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def Cat := bundled category.{v u} namespace Cat instance : inhabited Cat := ⟨⟨Type u, category_theory.types⟩⟩ instance : has_coe_to_sort Cat (Type u) := ⟨bundled.α⟩ instance str (C : Cat.{v u}) : category.{v u} C := C.str /-- Construct a bundled `Cat` from the underlying type and the typeclass. -/ def of (C : Type u) [category.{v} C] : Cat.{v u} := bundled.of C /-- Bicategory structure on `Cat` -/ instance bicategory : bicategory.{(max v u) (max v u)} Cat.{v u} := { hom := λ C D, C ⥤ D, id := λ C, 𝟭 C, comp := λ C D E F G, F ⋙ G, hom_category := λ C D, functor.category C D, whisker_left := λ C D E F G H η, whisker_left F η, whisker_right := λ C D E F G η H, whisker_right η H, associator := λ A B C D, functor.associator, left_unitor := λ A B, functor.left_unitor, right_unitor := λ A B, functor.right_unitor, pentagon' := λ A B C D E, functor.pentagon, triangle' := λ A B C, functor.triangle } /-- `Cat` is a strict bicategory. -/ instance bicategory.strict : bicategory.strict Cat.{v u} := { id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- Category structure on `Cat` -/ instance category : large_category.{max v u} Cat.{v u} := strict_bicategory.category Cat.{v u} @[simp] lemma id_map {C : Cat} {X Y : C} (f : X ⟶ Y) : (𝟙 C : C ⥤ C).map f = f := functor.id_map f @[simp] lemma comp_obj {C D E : Cat} (F : C ⟶ D) (G : D ⟶ E) (X : C) : (F ≫ G).obj X = G.obj (F.obj X) := functor.comp_obj F G X @[simp] lemma comp_map {C D E : Cat} (F : C ⟶ D) (G : D ⟶ E) {X Y : C} (f : X ⟶ Y) : (F ≫ G).map f = G.map (F.map f) := functor.comp_map F G f /-- Functor that gets the set of objects of a category. It is not called `forget`, because it is not a faithful functor. -/ def objects : Cat.{v u} ⥤ Type u := { obj := λ C, C, map := λ C D F, F.obj } /-- Any isomorphism in `Cat` induces an equivalence of the underlying categories. -/ def equiv_of_iso {C D : Cat} (γ : C ≅ D) : C ≌ D := { functor := γ.hom, inverse := γ.inv, unit_iso := eq_to_iso $ eq.symm γ.hom_inv_id, counit_iso := eq_to_iso γ.inv_hom_id } end Cat /-- Embedding `Type` into `Cat` as discrete categories. This ought to be modelled as a 2-functor! -/ @[simps] def Type_to_Cat : Type u ⥤ Cat := { obj := λ X, Cat.of (discrete X), map := λ X Y f, discrete.functor f, map_id' := λ X, begin apply functor.ext, tidy, end, map_comp' := λ X Y Z f g, begin apply functor.ext, tidy, end } instance : faithful Type_to_Cat.{u} := {} instance : full Type_to_Cat.{u} := { preimage := λ X Y F, F.obj, witness' := begin intros X Y F, apply functor.ext, { intros x y f, dsimp, ext, }, { intros x, refl, } end } end category_theory
62338e86a99f9ed2b3efa63e99ca85cf27fd2b7b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/NFM2022/nfm6.lean
dfeecbaacd0baf454abdd332c5bd8e5b076b85f3
[ "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
352
lean
/- Inductive Types -/ inductive Tree (β : Type v) where | leaf | node (left : Tree β) (key : Nat) (value : β) (right : Tree β) deriving Repr #eval Tree.node .leaf 10 true .leaf -- Tree.node Tree.leaf 10 true Tree.leaf inductive Vector (α : Type u) : Nat → Type u | nil : Vector α 0 | cons : α → Vector α n → Vector α (n+1)
0753164469c887cd12fffb5726752b27e41bd694
3c693e12637d1cf47effc09ab5e21700d1278e73
/src/topology/top_space.lean
6d2d1154d50d6d3bc1f7a73f5a6007d84e164d38
[]
no_license
ImperialCollegeLondon/Example-Lean-Projects
e731664ae046980921a69ccfeb2286674080c5bb
87b27ba616eaf03f3642000829a481a1932dd08e
refs/heads/master
1,685,399,670,721
1,623,092,696,000
1,623,092,696,000
275,571,570
19
1
null
1,593,361,524,000
1,593,344,124,000
Lean
UTF-8
Lean
false
false
2,204
lean
-- topological spaces from first principles. import tactic open set class topological_space (X : Type) := (is_open : set X → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀ (U V : set X), is_open U → is_open V → is_open (U ∩ V)) (is_open_sUnion : ∀ (𝒞 : set (set X)), (∀U ∈ 𝒞, is_open U) → is_open (⋃₀ 𝒞)) namespace topological_space variables {X : Type} [topological_space X] variable {ι : Type} lemma is_open_Union {f : ι → set X} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := begin apply is_open_sUnion, intros U, intro hU, cases hU with i hi, dsimp at hi, rw ←hi, apply h, end -- remember `U : set X` means "U is a subset of X", or "U is a set of terms of X" variables (U V : set X) lemma is_open_union (h₁ : is_open U) (h₂ : is_open V) : is_open (U ∪ V) := begin let 𝒞 : set (set X) := {U, V}, have h𝒞 : ∀ U ∈ 𝒞, is_open U, { intros W hW, rcases hW with rfl | ⟨_, _⟩; assumption}, convert is_open_sUnion 𝒞 h𝒞, simp only [sUnion_singleton, sUnion_insert] end lemma is_open_empty : is_open (∅ : set X) := begin let 𝒞 : set (set X) := ∅, have h𝒞 : ∀ U ∈ 𝒞, is_open U, rintro U ⟨⟩, convert is_open_sUnion 𝒞 h𝒞, apply sUnion_empty.symm, end /-- A set is closed if its complement is open -/ def is_closed (U : set X) : Prop := is_open Uᶜ end topological_space open topological_space variables {X : Type} [topological_space X] {Y : Type} [topological_space Y] /-- A function between topological spaces is continuous if the preimage of every open set is open. -/ def continuous (f : X → Y) := ∀U, is_open U → is_open (f ⁻¹' U) theorem continuous_id : continuous (id : X → X) := begin intros U hU, -- have h1 : U = id '' U := rfl, -- fails -- have h2 : U = id ⁻¹' U := rfl, -- works exact hU, end variables {Z : Type} [topological_space Z] theorem continuous.comp {g : Y → Z} {f : X → Y} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := --λ U hU, hf (g⁻¹' U) $ hg _ hU begin intros U hU, -- change is_open (f⁻¹' (g⁻¹' U)), apply hf (g⁻¹' U), apply hg, assumption, end
14a9ced54547ab5238c05bbe522cc681d029301f
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/univ2.lean
1a67e40f894b4d34e4fbb4cbc4226a71031a7602
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
216
lean
universe M >= 1 universe U >= M + 1 universe Z >= max U+1 M+1 print environment 2 (* local env = get_environment() assert(env:get_universe_distance("Z", "U") == 1) assert(env:get_universe_distance("Z", "M") == 2) *)
fe3df34f2b435222f18aa86dc3c141e69cf51e22
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/continued_fractions/computation/approximation_corollaries.lean
df71b81f9db553f33eeccdff416c785b85edfa82
[ "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
6,994
lean
/- Copyright (c) 2021 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.approximations import algebra.continued_fractions.convergents_equiv import algebra.order.archimedean import algebra.algebra.basic import topology.order.basic /-! # Corollaries From Approximation Lemmas (`algebra.continued_fractions.computation.approximations`) ## Summary We show that the generalized_continued_fraction given by `generalized_continued_fraction.of` in fact is a (regular) continued fraction. Using the equivalence of the convergents computations (`generalized_continued_fraction.convergents` and `generalized_continued_fraction.convergents'`) for continued fractions (see `algebra.continued_fractions.convergents_equiv`), it follows that the convergents computations for `generalized_continued_fraction.of` are equivalent. Moreover, we show the convergence of the continued fractions computations, that is `(generalized_continued_fraction.of v).convergents` indeed computes `v` in the limit. ## Main Definitions - `continued_fraction.of` returns the (regular) continued fraction of a value. ## Main Theorems - `generalized_continued_fraction.of_convergents_eq_convergents'` shows that the convergents computations for `generalized_continued_fraction.of` are equivalent. - `generalized_continued_fraction.of_convergence` shows that `(generalized_continued_fraction.of v).convergents` converges to `v`. ## Tags convergence, fractions -/ variables {K : Type*} (v : K) [linear_ordered_field K] [floor_ring K] open generalized_continued_fraction (of) open generalized_continued_fraction lemma generalized_continued_fraction.of_is_simple_continued_fraction : (of v).is_simple_continued_fraction := (λ _ _ nth_part_num_eq, of_part_num_eq_one nth_part_num_eq) /-- Creates the simple continued fraction of a value. -/ def simple_continued_fraction.of : simple_continued_fraction K := ⟨of v, generalized_continued_fraction.of_is_simple_continued_fraction v⟩ lemma simple_continued_fraction.of_is_continued_fraction : (simple_continued_fraction.of v).is_continued_fraction := (λ _ denom nth_part_denom_eq, lt_of_lt_of_le zero_lt_one (of_one_le_nth_part_denom nth_part_denom_eq)) /-- Creates the continued fraction of a value. -/ def continued_fraction.of : continued_fraction K := ⟨simple_continued_fraction.of v, simple_continued_fraction.of_is_continued_fraction v⟩ namespace generalized_continued_fraction lemma of_convergents_eq_convergents' : (of v).convergents = (of v).convergents' := @continued_fraction.convergents_eq_convergents' _ _ (continued_fraction.of v) /-- The recurrence relation for the `convergents` of the continued fraction expansion of an element `v` of `K` in terms of the convergents of the inverse of its fractional part. -/ lemma convergents_succ (n : ℕ) : (of v).convergents (n + 1) = ⌊v⌋ + 1 / (of (int.fract v)⁻¹).convergents n := by rw [of_convergents_eq_convergents', convergents'_succ, of_convergents_eq_convergents'] section convergence /-! ### Convergence We next show that `(generalized_continued_fraction.of v).convergents v` converges to `v`. -/ variable [archimedean K] open nat theorem of_convergence_epsilon : ∀ (ε > (0 : K)), ∃ (N : ℕ), ∀ (n ≥ N), |v - (of v).convergents n| < ε := begin assume ε ε_pos, -- use the archimedean property to obtian a suitable N rcases (exists_nat_gt (1 / ε) : ∃ (N' : ℕ), 1 / ε < N') with ⟨N', one_div_ε_lt_N'⟩, let N := max N' 5, -- set minimum to 5 to have N ≤ fib N work existsi N, assume n n_ge_N, let g := of v, cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n, { have : v = g.convergents n, from of_correctness_of_terminated_at terminated_at_n, have : v - g.convergents n = 0, from sub_eq_zero.elim_right this, rw [this], exact_mod_cast ε_pos }, { let B := g.denominators n, let nB := g.denominators (n + 1), have abs_v_sub_conv_le : |v - g.convergents n| ≤ 1 / (B * nB), from abs_sub_convergents_le not_terminated_at_n, suffices : 1 / (B * nB) < ε, from lt_of_le_of_lt abs_v_sub_conv_le this, -- show that `0 < (B * nB)` and then multiply by `B * nB` to get rid of the division have nB_ineq : (fib (n + 2) : K) ≤ nB, by { have : ¬g.terminated_at (n + 1 - 1), from not_terminated_at_n, exact (succ_nth_fib_le_of_nth_denom (or.inr this)) }, have B_ineq : (fib (n + 1) : K) ≤ B, by { have : ¬g.terminated_at (n - 1), from mt (terminated_stable n.pred_le) not_terminated_at_n, exact (succ_nth_fib_le_of_nth_denom (or.inr this)) }, have zero_lt_B : 0 < B, by { have : (0 : K) < fib (n + 1), by exact_mod_cast fib_pos n.zero_lt_succ, exact (lt_of_lt_of_le this B_ineq) }, have zero_lt_mul_conts : 0 < B * nB, by { have : 0 < nB, by { have : (0 : K) < fib (n + 2), by exact_mod_cast fib_pos (n + 1).zero_lt_succ, exact (lt_of_lt_of_le this nB_ineq) }, solve_by_elim [mul_pos] }, suffices : 1 < ε * (B * nB), from (div_lt_iff zero_lt_mul_conts).elim_right this, -- use that `N ≥ n` was obtained from the archimedean property to show the following have one_lt_ε_mul_N : 1 < ε * n, by { have one_lt_ε_mul_N' : 1 < ε * (N' : K), from (div_lt_iff' ε_pos).elim_left one_div_ε_lt_N', have : (N' : K) ≤ N, by exact_mod_cast (le_max_left _ _), have : ε * N' ≤ ε * n, from (mul_le_mul_left ε_pos).elim_right (le_trans this (by exact_mod_cast n_ge_N)), exact (lt_of_lt_of_le one_lt_ε_mul_N' this) }, suffices : ε * n ≤ ε * (B * nB), from lt_of_lt_of_le one_lt_ε_mul_N this, -- cancel `ε` suffices : (n : K) ≤ B * nB, from (mul_le_mul_left ε_pos).elim_right this, show (n : K) ≤ B * nB, calc (n : K) ≤ fib n : by exact_mod_cast (le_fib_self $ le_trans (le_max_right N' 5) n_ge_N) ... ≤ fib (n + 1) : by exact_mod_cast fib_le_fib_succ ... ≤ fib (n + 1) * fib (n + 1) : by exact_mod_cast ((fib (n + 1)).le_mul_self) ... ≤ fib (n + 1) * fib (n + 2) : mul_le_mul_of_nonneg_left (by exact_mod_cast fib_le_fib_succ) (by exact_mod_cast (fib (n + 1)).zero_le) ... ≤ B * nB : mul_le_mul B_ineq nB_ineq (by exact_mod_cast (fib (n + 2)).zero_le) (le_of_lt zero_lt_B) } end local attribute [instance] preorder.topology theorem of_convergence [order_topology K] : filter.tendsto ((of v).convergents) filter.at_top $ nhds v := by simpa [linear_ordered_add_comm_group.tendsto_nhds, abs_sub_comm] using (of_convergence_epsilon v) end convergence end generalized_continued_fraction
80f9349f512cac829b4a937b520a8ba5716d9594
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/final.lean
f85798fef3d3f07efdc51e8f78f52d3516d7d850
[ "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
21,099
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 category_theory.punit import category_theory.structured_arrow import category_theory.is_connected import category_theory.limits.yoneda import category_theory.limits.types /-! # Final and initial functors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A functor `F : C ⥤ D` is final if for every `d : D`, the comma category of morphisms `d ⟶ F.obj c` is connected. Dually, a functor `F : C ⥤ D` is initial if for every `d : D`, the comma category of morphisms `F.obj c ⟶ d` is connected. We show that right adjoints are examples of final functors, while left adjoints are examples of initial functors. For final functors, we prove that the following three statements are equivalent: 1. `F : C ⥤ D` is final. 2. Every functor `G : D ⥤ E` has a colimit if and only if `F ⋙ G` does, and these colimits are isomorphic via `colimit.pre G F`. 3. `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit`. Starting at 1. we show (in `cocones_equiv`) that the categories of cocones over `G : D ⥤ E` and over `F ⋙ G` are equivalent. (In fact, via an equivalence which does not change the cocone point.) This readily implies 2., as `comp_has_colimit`, `has_colimit_of_comp`, and `colimit_iso`. From 2. we can specialize to `G = coyoneda.obj (op d)` to obtain 3., as `colimit_comp_coyoneda_iso`. From 3., we prove 1. directly in `cofinal_of_colimit_comp_coyoneda_iso_punit`. Dually, we prove that if a functor `F : C ⥤ D` is initial, then any functor `G : D ⥤ E` has a limit if and only if `F ⋙ G` does, and these limits are isomorphic via `limit.pre G F`. ## Naming There is some discrepancy in the literature about naming; some say 'cofinal' instead of 'final'. The explanation for this is that the 'co' prefix here is *not* the usual category-theoretic one indicating duality, but rather indicating the sense of "along with". ## Future work Dualise condition 3 above and the implications 2 ⇒ 3 and 3 ⇒ 1 to initial functors. ## References * https://stacks.math.columbia.edu/tag/09WN * https://ncatlab.org/nlab/show/final+functor * Borceux, Handbook of Categorical Algebra I, Section 2.11. (Note he reverses the roles of definition and main result relative to here!) -/ noncomputable theory universes v v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory namespace functor open opposite open category_theory.limits section arbitrary_universe variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] /-- A functor `F : C ⥤ D` is final if for every `d : D`, the comma category of morphisms `d ⟶ F.obj c` is connected. See <https://stacks.math.columbia.edu/tag/04E6> -/ class final (F : C ⥤ D) : Prop := (out (d : D) : is_connected (structured_arrow d F)) attribute [instance] final.out /-- A functor `F : C ⥤ D` is initial if for every `d : D`, the comma category of morphisms `F.obj c ⟶ d` is connected. -/ class initial (F : C ⥤ D) : Prop := (out (d : D) : is_connected (costructured_arrow F d)) attribute [instance] initial.out instance final_op_of_initial (F : C ⥤ D) [initial F] : final F.op := { out := λ d, is_connected_of_equivalent (costructured_arrow_op_equivalence F (unop d)) } instance initial_op_of_final (F : C ⥤ D) [final F] : initial F.op := { out := λ d, is_connected_of_equivalent (structured_arrow_op_equivalence F (unop d)) } lemma final_of_initial_op (F : C ⥤ D) [initial F.op] : final F := { out := λ d, @is_connected_of_is_connected_op _ _ (is_connected_of_equivalent (structured_arrow_op_equivalence F d).symm) } lemma initial_of_final_op (F : C ⥤ D) [final F.op] : initial F := { out := λ d, @is_connected_of_is_connected_op _ _ (is_connected_of_equivalent (costructured_arrow_op_equivalence F d).symm) } /-- If a functor `R : D ⥤ C` is a right adjoint, it is final. -/ lemma final_of_adjunction {L : C ⥤ D} {R : D ⥤ C} (adj : L ⊣ R) : final R := { out := λ c, let u : structured_arrow c R := structured_arrow.mk (adj.unit.app c) in @zigzag_is_connected _ _ ⟨u⟩ $ λ f g, relation.refl_trans_gen.trans (relation.refl_trans_gen.single (show zag f u, from or.inr ⟨structured_arrow.hom_mk ((adj.hom_equiv c f.right).symm f.hom) (by simp)⟩)) (relation.refl_trans_gen.single (show zag u g, from or.inl ⟨structured_arrow.hom_mk ((adj.hom_equiv c g.right).symm g.hom) (by simp)⟩)) } /-- If a functor `L : C ⥤ D` is a left adjoint, it is initial. -/ lemma initial_of_adjunction {L : C ⥤ D} {R : D ⥤ C} (adj : L ⊣ R) : initial L := { out := λ d, let u : costructured_arrow L d := costructured_arrow.mk (adj.counit.app d) in @zigzag_is_connected _ _ ⟨u⟩ $ λ f g, relation.refl_trans_gen.trans (relation.refl_trans_gen.single (show zag f u, from or.inl ⟨costructured_arrow.hom_mk (adj.hom_equiv f.left d f.hom) (by simp)⟩)) (relation.refl_trans_gen.single (show zag u g, from or.inr ⟨costructured_arrow.hom_mk (adj.hom_equiv g.left d g.hom) (by simp)⟩)) } @[priority 100] instance final_of_is_right_adjoint (F : C ⥤ D) [h : is_right_adjoint F] : final F := final_of_adjunction h.adj @[priority 100] instance initial_of_is_left_adjoint (F : C ⥤ D) [h : is_left_adjoint F] : initial F := initial_of_adjunction h.adj namespace final variables (F : C ⥤ D) [final F] instance (d : D) : nonempty (structured_arrow d F) := is_connected.is_nonempty variables {E : Type u₃} [category.{v₃} E] (G : D ⥤ E) /-- When `F : C ⥤ D` is cofinal, we denote by `lift F d` an arbitrary choice of object in `C` such that there exists a morphism `d ⟶ F.obj (lift F d)`. -/ def lift (d : D) : C := (classical.arbitrary (structured_arrow d F)).right /-- When `F : C ⥤ D` is cofinal, we denote by `hom_to_lift` an arbitrary choice of morphism `d ⟶ F.obj (lift F d)`. -/ def hom_to_lift (d : D) : d ⟶ F.obj (lift F d) := (classical.arbitrary (structured_arrow d F)).hom /-- We provide an induction principle for reasoning about `lift` and `hom_to_lift`. We want to perform some construction (usually just a proof) about the particular choices `lift F d` and `hom_to_lift F d`, it suffices to perform that construction for some other pair of choices (denoted `X₀ : C` and `k₀ : d ⟶ F.obj X₀` below), and to show how to transport such a construction *both* directions along a morphism between such choices. -/ def induction {d : D} (Z : Π (X : C) (k : d ⟶ F.obj X), Sort*) (h₁ : Π X₁ X₂ (k₁ : d ⟶ F.obj X₁) (k₂ : d ⟶ F.obj X₂) (f : X₁ ⟶ X₂), (k₁ ≫ F.map f = k₂) → Z X₁ k₁ → Z X₂ k₂) (h₂ : Π X₁ X₂ (k₁ : d ⟶ F.obj X₁) (k₂ : d ⟶ F.obj X₂) (f : X₁ ⟶ X₂), (k₁ ≫ F.map f = k₂) → Z X₂ k₂ → Z X₁ k₁) {X₀ : C} {k₀ : d ⟶ F.obj X₀} (z : Z X₀ k₀) : Z (lift F d) (hom_to_lift F d) := begin apply nonempty.some, apply @is_preconnected_induction _ _ _ (λ (Y : structured_arrow d F), Z Y.right Y.hom) _ _ (structured_arrow.mk k₀) z, { intros j₁ j₂ f a, fapply h₁ _ _ _ _ f.right _ a, convert f.w.symm, dsimp, simp, }, { intros j₁ j₂ f a, fapply h₂ _ _ _ _ f.right _ a, convert f.w.symm, dsimp, simp, }, end variables {F G} /-- Given a cocone over `F ⋙ G`, we can construct a `cocone G` with the same cocone point. -/ @[simps] def extend_cocone : cocone (F ⋙ G) ⥤ cocone G := { obj := λ c, { X := c.X, ι := { app := λ X, G.map (hom_to_lift F X) ≫ c.ι.app (lift F X), naturality' := λ X Y f, begin dsimp, simp, -- This would be true if we'd chosen `lift F X` to be `lift F Y` -- and `hom_to_lift F X` to be `f ≫ hom_to_lift F Y`. apply induction F (λ Z k, G.map f ≫ G.map (hom_to_lift F Y) ≫ c.ι.app (lift F Y) = G.map k ≫ c.ι.app Z), { intros Z₁ Z₂ k₁ k₂ g a z, rw [←a, functor.map_comp, category.assoc, ←functor.comp_map, c.w, z], }, { intros Z₁ Z₂ k₁ k₂ g a z, rw [←a, functor.map_comp, category.assoc, ←functor.comp_map, c.w] at z, rw z, }, { rw [←functor.map_comp_assoc], }, end } }, map := λ X Y f, { hom := f.hom, } } @[simp] lemma colimit_cocone_comp_aux (s : cocone (F ⋙ G)) (j : C) : G.map (hom_to_lift F (F.obj j)) ≫ s.ι.app (lift F (F.obj j)) = s.ι.app j := begin -- This point is that this would be true if we took `lift (F.obj j)` to just be `j` -- and `hom_to_lift (F.obj j)` to be `𝟙 (F.obj j)`. apply induction F (λ X k, G.map k ≫ s.ι.app X = (s.ι.app j : _)), { intros j₁ j₂ k₁ k₂ f w h, rw ←w, rw ← s.w f at h, simpa using h, }, { intros j₁ j₂ k₁ k₂ f w h, rw ←w at h, rw ← s.w f, simpa using h, }, { exact s.w (𝟙 _), }, end variables (F G) /-- If `F` is cofinal, the category of cocones on `F ⋙ G` is equivalent to the category of cocones on `G`, for any `G : D ⥤ E`. -/ @[simps] def cocones_equiv : cocone (F ⋙ G) ≌ cocone G := { functor := extend_cocone, inverse := cocones.whiskering F, unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), }. variables {G} /-- When `F : C ⥤ D` is cofinal, and `t : cocone G` for some `G : D ⥤ E`, `t.whisker F` is a colimit cocone exactly when `t` is. -/ def is_colimit_whisker_equiv (t : cocone G) : is_colimit (t.whisker F) ≃ is_colimit t := is_colimit.of_cocone_equiv (cocones_equiv F G).symm /-- When `F` is cofinal, and `t : cocone (F ⋙ G)`, `extend_cocone.obj t` is a colimit coconne exactly when `t` is. -/ def is_colimit_extend_cocone_equiv (t : cocone (F ⋙ G)) : is_colimit (extend_cocone.obj t) ≃ is_colimit t := is_colimit.of_cocone_equiv (cocones_equiv F G) /-- Given a colimit cocone over `G : D ⥤ E` we can construct a colimit cocone over `F ⋙ G`. -/ @[simps] def colimit_cocone_comp (t : colimit_cocone G) : colimit_cocone (F ⋙ G) := { cocone := _, is_colimit := (is_colimit_whisker_equiv F _).symm (t.is_colimit) } @[priority 100] instance comp_has_colimit [has_colimit G] : has_colimit (F ⋙ G) := has_colimit.mk (colimit_cocone_comp F (get_colimit_cocone G)) lemma colimit_pre_is_iso_aux {t : cocone G} (P : is_colimit t) : ((is_colimit_whisker_equiv F _).symm P).desc (t.whisker F) = 𝟙 t.X := begin dsimp [is_colimit_whisker_equiv], apply P.hom_ext, intro j, dsimp, simp, end instance colimit_pre_is_iso [has_colimit G] : is_iso (colimit.pre G F) := begin rw colimit.pre_eq (colimit_cocone_comp F (get_colimit_cocone G)) (get_colimit_cocone G), erw colimit_pre_is_iso_aux, dsimp, apply_instance, end section variables (G) /-- When `F : C ⥤ D` is cofinal, and `G : D ⥤ E` has a colimit, then `F ⋙ G` has a colimit also and `colimit (F ⋙ G) ≅ colimit G` https://stacks.math.columbia.edu/tag/04E7 -/ def colimit_iso [has_colimit G] : colimit (F ⋙ G) ≅ colimit G := as_iso (colimit.pre G F) end /-- Given a colimit cocone over `F ⋙ G` we can construct a colimit cocone over `G`. -/ @[simps] def colimit_cocone_of_comp (t : colimit_cocone (F ⋙ G)) : colimit_cocone G := { cocone := extend_cocone.obj t.cocone, is_colimit := (is_colimit_extend_cocone_equiv F _).symm (t.is_colimit), } /-- When `F` is cofinal, and `F ⋙ G` has a colimit, then `G` has a colimit also. We can't make this an instance, because `F` is not determined by the goal. (Even if this weren't a problem, it would cause a loop with `comp_has_colimit`.) -/ lemma has_colimit_of_comp [has_colimit (F ⋙ G)] : has_colimit G := has_colimit.mk (colimit_cocone_of_comp F (get_colimit_cocone (F ⋙ G))) section local attribute [instance] has_colimit_of_comp /-- When `F` is cofinal, and `F ⋙ G` has a colimit, then `G` has a colimit also and `colimit (F ⋙ G) ≅ colimit G` https://stacks.math.columbia.edu/tag/04E7 -/ def colimit_iso' [has_colimit (F ⋙ G)] : colimit (F ⋙ G) ≅ colimit G := as_iso (colimit.pre G F) end end final end arbitrary_universe namespace final variables {C : Type v} [category.{v} C] {D : Type v} [category.{v} D] (F : C ⥤ D) [final F] /-- If the universal morphism `colimit (F ⋙ coyoneda.obj (op d)) ⟶ colimit (coyoneda.obj (op d))` is an isomorphism (as it always is when `F` is cofinal), then `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit` (simply because `colimit (coyoneda.obj (op d)) ≅ punit`). -/ def colimit_comp_coyoneda_iso (d : D) [is_iso (colimit.pre (coyoneda.obj (op d)) F)] : colimit (F ⋙ coyoneda.obj (op d)) ≅ punit := as_iso (colimit.pre (coyoneda.obj (op d)) F) ≪≫ coyoneda.colimit_coyoneda_iso (op d) lemma zigzag_of_eqv_gen_quot_rel {F : C ⥤ D} {d : D} {f₁ f₂ : Σ X, d ⟶ F.obj X} (t : eqv_gen (types.quot.rel.{v v} (F ⋙ coyoneda.obj (op d))) f₁ f₂) : zigzag (structured_arrow.mk f₁.2) (structured_arrow.mk f₂.2) := begin induction t, case eqv_gen.rel : x y r { obtain ⟨f, w⟩ := r, fconstructor, swap 2, fconstructor, left, fsplit, exact structured_arrow.hom_mk f (by tidy), }, case eqv_gen.refl { fconstructor, }, case eqv_gen.symm : x y h ih { apply zigzag_symmetric, exact ih, }, case eqv_gen.trans : x y z h₁ h₂ ih₁ ih₂ { apply relation.refl_trans_gen.trans, exact ih₁, exact ih₂, } end /-- If `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit` for all `d : D`, then `F` is cofinal. -/ lemma cofinal_of_colimit_comp_coyoneda_iso_punit (I : Π d, colimit (F ⋙ coyoneda.obj (op d)) ≅ punit) : final F := ⟨λ d, begin haveI : nonempty (structured_arrow d F), { have := (I d).inv punit.star, obtain ⟨j, y, rfl⟩ := limits.types.jointly_surjective'.{v v} this, exact ⟨structured_arrow.mk y⟩, }, apply zigzag_is_connected, rintros ⟨⟨⟨⟩⟩,X₁,f₁⟩ ⟨⟨⟨⟩⟩,X₂,f₂⟩, dsimp at *, let y₁ := colimit.ι (F ⋙ coyoneda.obj (op d)) X₁ f₁, let y₂ := colimit.ι (F ⋙ coyoneda.obj (op d)) X₂ f₂, have e : y₁ = y₂, { apply (I d).to_equiv.injective, ext, }, have t := types.colimit_eq.{v v} e, clear e y₁ y₂, exact zigzag_of_eqv_gen_quot_rel t, end⟩ end final namespace initial variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (F : C ⥤ D) [initial F] instance (d : D) : nonempty (costructured_arrow F d) := is_connected.is_nonempty variables {E : Type u₃} [category.{v₃} E] (G : D ⥤ E) /-- When `F : C ⥤ D` is initial, we denote by `lift F d` an arbitrary choice of object in `C` such that there exists a morphism `F.obj (lift F d) ⟶ d`. -/ def lift (d : D) : C := (classical.arbitrary (costructured_arrow F d)).left /-- When `F : C ⥤ D` is initial, we denote by `hom_to_lift` an arbitrary choice of morphism `F.obj (lift F d) ⟶ d`. -/ def hom_to_lift (d : D) : F.obj (lift F d) ⟶ d := (classical.arbitrary (costructured_arrow F d)).hom /-- We provide an induction principle for reasoning about `lift` and `hom_to_lift`. We want to perform some construction (usually just a proof) about the particular choices `lift F d` and `hom_to_lift F d`, it suffices to perform that construction for some other pair of choices (denoted `X₀ : C` and `k₀ : F.obj X₀ ⟶ d` below), and to show how to transport such a construction *both* directions along a morphism between such choices. -/ def induction {d : D} (Z : Π (X : C) (k : F.obj X ⟶ d), Sort*) (h₁ : Π X₁ X₂ (k₁ : F.obj X₁ ⟶ d) (k₂ : F.obj X₂ ⟶ d) (f : X₁ ⟶ X₂), (F.map f ≫ k₂ = k₁) → Z X₁ k₁ → Z X₂ k₂) (h₂ : Π X₁ X₂ (k₁ : F.obj X₁ ⟶ d) (k₂ : F.obj X₂ ⟶ d) (f : X₁ ⟶ X₂), (F.map f ≫ k₂ = k₁) → Z X₂ k₂ → Z X₁ k₁) {X₀ : C} {k₀ : F.obj X₀ ⟶ d} (z : Z X₀ k₀) : Z (lift F d) (hom_to_lift F d) := begin apply nonempty.some, apply @is_preconnected_induction _ _ _ (λ Y : costructured_arrow F d, Z Y.left Y.hom) _ _ (costructured_arrow.mk k₀) z, { intros j₁ j₂ f a, fapply h₁ _ _ _ _ f.left _ a, convert f.w, dsimp, simp, }, { intros j₁ j₂ f a, fapply h₂ _ _ _ _ f.left _ a, convert f.w, dsimp, simp, }, end variables {F G} /-- Given a cone over `F ⋙ G`, we can construct a `cone G` with the same cocone point. -/ @[simps] def extend_cone : cone (F ⋙ G) ⥤ cone G := { obj := λ c, { X := c.X, π := { app := λ d, c.π.app (lift F d) ≫ G.map (hom_to_lift F d), naturality' := λ X Y f, begin dsimp, simp, -- This would be true if we'd chosen `lift F Y` to be `lift F X` -- and `hom_to_lift F Y` to be `hom_to_lift F X ≫ f`. apply induction F (λ Z k, (c.π.app Z ≫ G.map k : c.X ⟶ _) = c.π.app (lift F X) ≫ G.map (hom_to_lift F X) ≫ G.map f), { intros Z₁ Z₂ k₁ k₂ g a z, rw [←a, functor.map_comp, ←functor.comp_map, ←category.assoc, ←category.assoc, c.w] at z, rw [z, category.assoc] }, { intros Z₁ Z₂ k₁ k₂ g a z, rw [←a, functor.map_comp, ←functor.comp_map, ←category.assoc, ←category.assoc, c.w, z, category.assoc] }, { rw [←functor.map_comp], }, end } }, map := λ X Y f, { hom := f.hom, } } @[simp] lemma limit_cone_comp_aux (s : cone (F ⋙ G)) (j : C) : s.π.app (lift F (F.obj j)) ≫ G.map (hom_to_lift F (F.obj j)) = s.π.app j := begin -- This point is that this would be true if we took `lift (F.obj j)` to just be `j` -- and `hom_to_lift (F.obj j)` to be `𝟙 (F.obj j)`. apply induction F (λ X k, s.π.app X ≫ G.map k = (s.π.app j : _)), { intros j₁ j₂ k₁ k₂ f w h, rw ←s.w f, rw ←w at h, simpa using h, }, { intros j₁ j₂ k₁ k₂ f w h, rw ←s.w f at h, rw ←w, simpa using h, }, { exact s.w (𝟙 _), }, end variables (F G) /-- If `F` is initial, the category of cones on `F ⋙ G` is equivalent to the category of cones on `G`, for any `G : D ⥤ E`. -/ @[simps] def cones_equiv : cone (F ⋙ G) ≌ cone G := { functor := extend_cone, inverse := cones.whiskering F, unit_iso := nat_iso.of_components (λ c, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cones.ext (iso.refl _) (by tidy)) (by tidy), }. variables {G} /-- When `F : C ⥤ D` is initial, and `t : cone G` for some `G : D ⥤ E`, `t.whisker F` is a limit cone exactly when `t` is. -/ def is_limit_whisker_equiv (t : cone G) : is_limit (t.whisker F) ≃ is_limit t := is_limit.of_cone_equiv (cones_equiv F G).symm /-- When `F` is initial, and `t : cone (F ⋙ G)`, `extend_cone.obj t` is a limit cone exactly when `t` is. -/ def is_limit_extend_cone_equiv (t : cone (F ⋙ G)) : is_limit (extend_cone.obj t) ≃ is_limit t := is_limit.of_cone_equiv (cones_equiv F G) /-- Given a limit cone over `G : D ⥤ E` we can construct a limit cone over `F ⋙ G`. -/ @[simps] def limit_cone_comp (t : limit_cone G) : limit_cone (F ⋙ G) := { cone := _, is_limit := (is_limit_whisker_equiv F _).symm (t.is_limit) } @[priority 100] instance comp_has_limit [has_limit G] : has_limit (F ⋙ G) := has_limit.mk (limit_cone_comp F (get_limit_cone G)) lemma limit_pre_is_iso_aux {t : cone G} (P : is_limit t) : ((is_limit_whisker_equiv F _).symm P).lift (t.whisker F) = 𝟙 t.X := begin dsimp [is_limit_whisker_equiv], apply P.hom_ext, intro j, simp, end instance limit_pre_is_iso [has_limit G] : is_iso (limit.pre G F) := begin rw limit.pre_eq (limit_cone_comp F (get_limit_cone G)) (get_limit_cone G), erw limit_pre_is_iso_aux, dsimp, apply_instance, end section variables (G) /-- When `F : C ⥤ D` is initial, and `G : D ⥤ E` has a limit, then `F ⋙ G` has a limit also and `limit (F ⋙ G) ≅ limit G` https://stacks.math.columbia.edu/tag/04E7 -/ def limit_iso [has_limit G] : limit (F ⋙ G) ≅ limit G := (as_iso (limit.pre G F)).symm end /-- Given a limit cone over `F ⋙ G` we can construct a limit cone over `G`. -/ @[simps] def limit_cone_of_comp (t : limit_cone (F ⋙ G)) : limit_cone G := { cone := extend_cone.obj t.cone, is_limit := (is_limit_extend_cone_equiv F _).symm (t.is_limit), } /-- When `F` is initial, and `F ⋙ G` has a limit, then `G` has a limit also. We can't make this an instance, because `F` is not determined by the goal. (Even if this weren't a problem, it would cause a loop with `comp_has_limit`.) -/ lemma has_limit_of_comp [has_limit (F ⋙ G)] : has_limit G := has_limit.mk (limit_cone_of_comp F (get_limit_cone (F ⋙ G))) section local attribute [instance] has_limit_of_comp /-- When `F` is initial, and `F ⋙ G` has a limit, then `G` has a limit also and `limit (F ⋙ G) ≅ limit G` https://stacks.math.columbia.edu/tag/04E7 -/ def limit_iso' [has_limit (F ⋙ G)] : limit (F ⋙ G) ≅ limit G := (as_iso (limit.pre G F)).symm end end initial end functor end category_theory
fa3b04e7ffb84022592916bf1775d26f09830b8b
94e33a31faa76775069b071adea97e86e218a8ee
/test/measurability.lean
deede74ac58d0825a2233b894e69efb4f61d24f4
[ "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
3,037
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.tactic import measure_theory.function.special_functions open_locale big_operators ennreal variables {α β : Type*} [measurable_space α] [measurable_space β] {f g : α → β} {s₁ s₂ : set α} {t₁ t₂ : set β} {μ ν : measure_theory.measure α} -- Test the use of assumption example (hf : measurable f) : measurable f := by measurability -- Test that intro does not unfold `measurable` example : measurable f → measurable f := by measurability -- Test the use of apply_assumption to get (h i) from an hypothesis (h : ∀ i, ...). example {F : ℕ → α → β} (hF : ∀ i, measurable (F i)) : measurable (F 0) := by measurability example {ι} [encodable ι] {S₁ S₂ : ι → set α} (hS₁ : ∀ i, measurable_set (S₁ i)) (hS₂ : ∀ i, measurable_set (S₂ i)) : measurable_set (⋃ i, (S₁ i) ∪ (S₂ i)) := by measurability -- Tests on sets example (hs₁ : measurable_set s₁) (hs₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₁) := by measurability example {ι} [encodable ι] {S : ι → set α} (hs : ∀ i, measurable_set (S i)) : measurable_set (⋃ i, S i) := by measurability example (hf : measurable f) (hs₁ : measurable_set s₁) (ht₂ : measurable_set t₂) : measurable_set ((f ⁻¹' t₂) ∩ s₁) := by measurability -- Tests on functions example [has_mul β] [has_measurable_mul₂ β] (hf : measurable f) (c : β) : measurable (λ x, c * f x) := by measurability -- uses const_mul, not mul example [has_add β] [has_measurable_add₂ β] (hf : measurable f) (hg : measurable g) : measurable (λ x, f x + g x) := by measurability example [has_add β] [has_measurable_add₂ β] (hf : measurable f) (hg : ae_measurable g μ) : ae_measurable (λ x, f x + g x) μ := by measurability example [has_div β] [has_measurable_div₂ β] (hf : measurable f) (hg : measurable g) (ht : measurable_set t₂): measurable_set ((λ x, f x / g x) ⁻¹' t₂) := by measurability example [add_comm_monoid β] [has_measurable_add₂ β] {s : finset ℕ} {F : ℕ → α → β} (hF : ∀ i, ae_measurable (F i) μ) : ae_measurable (∑ i in s, (λ x, F (i+1) x + F i x)) μ := by measurability -- even with many assumptions, the tactic is not trapped by a bad lemma example [topological_space α] [borel_space α] [normed_group β] [borel_space β] [has_measurable_add₂ β] [has_measurable_sub₂ β] {s : finset ℕ} {F : ℕ → α → β} (hF : ∀ i, measurable (F i)) : ae_measurable (∑ i in s, (λ x, F (i+1) x - F i x)) μ := by measurability example : measurable (λ x : ℝ, real.exp (2 * inner x 3)) := by measurability /-- An older version of the tactic failed in the presence of a negated hypothesis due to an internal call to `apply_assumption`. -/ example {ι : Type*} (i k : ι) (hik : i ≠ k) : measurable (id : α → α) := by measurability
c1e9cfbeed939de6068dd6661a5e62875f701619
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/int/default.lean
398d9dd51133375d812ad1946562e1ac8a5c2a8b
[]
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
393
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.int.basic import Mathlib.Lean3Lib.init.data.int.order import Mathlib.Lean3Lib.init.data.int.comp_lemmas import Mathlib.Lean3Lib.init.data.int.bitwise namespace Mathlib
756fd47b101ed59217fe5c88e7ad59b62443cb6e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tmp/PreludeNew.lean
dff4ff49758eef2a18f596963545457d7017a507
[ "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
58,154
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude universes u v w @[inline] def id {α : Sort u} (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl @[macroInline] def cast {α β : Sort u} (h : α = β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : a ≅ a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) := (fst : α) (snd : β) attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) := (fst : α) (snd : β) /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) := (fst : α) (snd : β) structure And (a b : Prop) : Prop := intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → b = false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → b = true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) := mk {} :: (default : α) constant arbitrary (α : Sort u) [s : Inhabited α] : α := @Inhabited.default α s instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := { default := fun _ => arbitrary β } instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := { default := fun a => arbitrary (β a) } /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u := up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), up (down b) = b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : down (up a) = a := rfl /- Pointed types -/ structure PointedType := (type : Type u) (val : type) instance : Inhabited PointedType.{u} := { default := { type := PUnit.{u+1}, val := ⟨⟩ } } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) := up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), up (down b) = b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : down (up.{v} a) = a := rfl class inductive Decidable (p : Prop) | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true | _, isTrue _, _ => rfl | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false | _, isTrue h₁, h₂ => absurd h₁ h₂ | _, isFalse h, _ => rfl theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) := (beq : α → α → Bool) open BEq (beq) instance {α : Type u} [DecidableEq α] : BEq α := ⟨fun a b => decide (Eq a b)⟩ -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (And p q) := if hp : p then if hq : q then isTrue ⟨hp, hq⟩ else isFalse (fun h => hq (And.right h)) else isFalse (fun h => hp (And.left h)) @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (Or p q) := if hp : p then isTrue (Or.inl hp) else if hq : q then isTrue (Or.inr hq) else isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance {p} [Decidable p] : Decidable (Not p) := if hp : p then isFalse (absurd hp) else isTrue hp /- Boolean operators -/ @[macroInline] def cond {a : Type u} : Bool → a → a → a | true, x, y => x | false, x, y => y @[macroInline] def or : Bool → Bool → Bool | true, _ => true | false, b => b @[macroInline] def and : Bool → Bool → Bool | false, _ => false | true, b => b @[macroInline] def not : Bool → Bool | true => false | false => true inductive Nat | zero : Nat | succ (n : Nat) : Nat /- For numeric literals notation -/ class OfNat (α : Type u) := (ofNat : Nat → α) export OfNat (ofNat) instance : OfNat Nat := ⟨id⟩ instance : Inhabited Nat := { default := 0 } class HasLessEq (α : Type u) := (LessEq : α → α → Prop) class HasLess (α : Type u) := (Less : α → α → Prop) export HasLess (Less) export HasLessEq (LessEq) class Add (α : Type u) := (add : α → α → α) class Mul (α : Type u) := (mul : α → α → α) class Neg (α : Type u) := (neg : α → α) class Sub (α : Type u) := (sub : α → α → α) class Div (α : Type u) := (div : α → α → α) class Mod (α : Type u) := (mod : α → α → α) class ModN (α : Type u) := (modn : α → Nat → α) class Pow (α : Type u) (β : Type v) := (pow : α → β → α) class Append (α : Type u) := (append : α → α → α) class OrElse (α : Type u) := (orElse : α → α → α) class AndThen (α : Type u) := (andThen : α → α → α) open Add (add) open Mul (mul) open Pow (pow) open Append (append) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat := { add := Nat.add } set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat := { mul := Nat.mul } set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat := { pow := Nat.pow } set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_dec_eq"] def Nat.beq : Nat → Nat → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTt : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have Eq (beq n m) true from h have Eq n m from eqOfBeqEqTt this this ▸ rfl theorem Nat.neOfBeqEqFf : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have beq n m = false from h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFf this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (n = m) := if h : beq n m = true then isTrue (eqOfBeqEqTt h) else isFalse (neOfBeqEqFf (eqFalseOfNeTrue h)) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_dec_le"] def Nat.ble : Nat → Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := ble n m = true instance : HasLessEq Nat := ⟨Nat.le⟩ protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat := ⟨Nat.lt⟩ theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (Less n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LessEq 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h have LessEq n (succ m) from leStep this succLeSucc this protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m k from h₂ Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LessEq n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LessEq n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m n from h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.gen_matcher_code false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : Nat → Nat | 0 => 0 | succ a => a theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → { n : Nat // Or (Eq n 32) (Eq n 64) } := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) := (val : Nat) (isLt : Less val n) theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : i.val = j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) def uint8Sz : Nat := 256 structure UInt8 := (val : Fin uint8Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => if h : Eq n m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h)) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 := { default := { val := { val := 0, isLt := decide! } } } def uint16Sz : Nat := 65536 structure UInt16 := (val : Fin uint16Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => if h : Eq n m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h)) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 := { default := { val := { val := 0, isLt := decide! } } } def uint32Sz : Nat := 4294967296 structure UInt32 := (val : Fin uint32Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => if h : Eq n m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h)) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 := { default := { val := { val := 0, isLt := decide! } } } def uint64Sz : Nat := 18446744073709551616 structure UInt64 := (val : Fin uint64Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => if h : Eq n m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h)) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 := { default := { val := { val := 0, isLt := decide! } } } def usizeSz : Nat := pow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq usizeSz 4294967296) (Eq usizeSz 18446744073709551616) := show Or (Eq (pow 2 System.Platform.numBits) 4294967296) (Eq (pow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (decide! : (Eq (pow 2 32) (4294967296:Nat))) | _, Or.inr rfl => Or.inr (decide! : (Eq (pow 2 64) (18446744073709551616:Nat))) structure USize := (val : Fin usizeSz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => if h : Eq n m then isTrue (h ▸ rfl) else isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h)) instance : DecidableEq USize := USize.decEq instance : Inhabited USize := { default := { val := { val := 0, isLt := match usizeSz, usizeSzEq with | _, Or.inl rfl => decide! | _, Or.inr rfl => decide! } } } @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := { val := { val := n, isLt := match usizeSz, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (decide! : Less 4294967296 18446744073709551616) } } @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : Less n usizeSz) : USize := { val := { val := n, isLt := h } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.val.val.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char := (val : UInt32) (valid : val.isValidChar) private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n uint32Sz := match h with | Or.inl h => Nat.ltTrans h (decide! : Less 55296 uint32Sz) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (decide! : Less 1114112 uint32Sz) abbrev Char.ofNat (n : Nat) : Char := if h : n.isValidChar then { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } else { val := ⟨{ val := 0, isLt := decide! }⟩, valid := Or.inl decide! } theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) inductive Option (α : Type u) | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) := { default := none } inductive List (α : Type u) | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) := { default := List.nil } protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l structure String := (data : List Char) attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (s₁ = s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => if h : s₁ = s₂ then isTrue (congrArg _ h) else isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h)) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring := (str : String) (startPos : String.Pos) (stopPos : String.Pos) @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) := (sz : Nat) (data : Fin sz → α) attribute [extern "lean_array_mk"] Array.mk attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_sz"] Array.sz /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { sz := 0, data := fun ⟨x, h⟩ => absurd h (Nat.notLtZero x) } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.sz @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data i /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := if h : Less i a.size then a.get ⟨i, h⟩ else arbitrary α @[extern "lean_array_push"] def push {α : Type u} (a : Array α) (v : α) : Array α := { sz := Nat.succ a.sz, data := fun ⟨j, h₁⟩ => if h₂ : j = a.sz then v else a.data ⟨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc h₁) h₂⟩ } class Bind (m : Type u → Type v) := (bind : {α β : Type u} → m α → (α → m β) → m β) export Bind (bind) class Pure (f : Type u → Type v) := (pure {α : Type u} : α → f α) export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) := (map : {α β : Type u} → (α → β) → f α → f β) (mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _)) class Seq (f : Type u → Type v) : Type (max (u+1) v) := (seq : {α β : Type u} → f (α → β) → f α → f β) class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) := (seqLeft : {α : Type u} → f α → f PUnit → f α) class SeqRight (f : Type u → Type v) : Type (max (u+1) v) := (seqRight : {β : Type u} → f PUnit → f β → f β) class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f := (map := fun x y => Seq.seq (pure x) y) (seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b) (seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b) class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) := (map := fun f x => bind x (Function.comp pure f)) (seq := fun f x => bind f (fun y => Functor.map y x)) (seqLeft := fun x y => bind x (fun a => bind y (fun _ => pure a))) (seqRight := fun x y => bind x (fun _ => y)) instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) := ⟨pure⟩ instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) := ⟨pure $ arbitrary _⟩ /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) := (monadLift : {α : Type u} → m α → n α) /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) := (monadLift : {α : Type u} → m α → n α) export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLiftT m n] [MonadLift n o] : MonadLiftT m o := { monadLift := fun x => MonadLift.monadLift (m := n) (monadLift x) } instance (m) : MonadLiftT m m := { monadLift := fun x => x } /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) := (monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α) /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) := (monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α) export MonadFunctorT (monadMap) instance (m n o) [MonadFunctorT m n] [MonadFunctor n o] : MonadFunctorT m o := { monadMap := fun f => MonadFunctor.monadMap (m := n) (monadMap (m := m) f) } instance monadFunctorRefl (m) : MonadFunctorT m m := { monadMap := fun f => f } inductive Except (ε : Type u) (α : Type v) | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) := ⟨Except.error (arbitrary ε)⟩ /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) := (throw {α : Type v} : ε → m α) (tryCatch {α : Type v} : m α → (ε → m α) → m α) abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) := (throw {α : Type v} : ε → m α) (tryCatch {α : Type v} : m α → (ε → m α) → m α) export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m := { throw := throwThe ε, tryCatch := tryCatchThe ε } namespace MonadExcept variables {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) := ⟨MonadExcept.orelse⟩ end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) := ⟨fun _ => arbitrary _⟩ @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r @[reducible] def Reader (ρ : Type u) := ReaderT ρ id namespace ReaderT section variables {ρ : Type u} {m : Type u → Type v} {α : Type u} @[inline] protected def lift (a : m α) : ReaderT ρ m α := fun r => a instance : MonadLift m (ReaderT ρ m) := ⟨ReaderT.lift⟩ instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) := { throw := Function.comp ReaderT.lift (throwThe ε), tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) } end section variables {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) := { pure := ReaderT.pure, bind := ReaderT.bind, map := ReaderT.map } instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) := ⟨fun f x r => f (x r)⟩ @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) := (lift {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α) → n α) ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) := (read : m ρ) @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) := (read : m ρ) export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m := ⟨readThe ρ⟩ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadReaderOf ρ m] [MonadLift m n] : MonadReaderOf ρ n := ⟨monadLift (MonadReader.read : m ρ)⟩ instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) := ⟨ReaderT.read⟩ class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) := (withReader {α : Type u} : (ρ → ρ) → m α → m α) @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) := (withReader {α : Type u} : (ρ → ρ) → m α → m α) export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m := ⟨withTheReader ρ⟩ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadWithReaderOf ρ m] [MonadFunctor m n] : MonadWithReaderOf ρ n := ⟨fun f => monadMap (m := m) (withTheReader ρ f)⟩ instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) := ⟨fun f x ctx => x (f ctx)⟩ /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) := /- Obtain the top-most State of a Monad stack. -/ (get : m σ) /- Set the top-most State of a Monad stack. -/ (set : σ → m PUnit) /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ (modifyGet {α : Type u} : (σ → α × σ) → m α) export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → α × σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) := (get : m σ) (set : σ → m PUnit) (modifyGet {α : Type u} : (σ → α × σ) → m α) export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m := { set := MonadStateOf.set, get := getThe σ, modifyGet := fun f => MonadStateOf.modifyGet f } @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadStateOf σ m] [MonadLift m n] : MonadStateOf σ n := { get := liftM (m := m) MonadStateOf.get, set := fun s => liftM (m := m) (MonadStateOf.set s), modifyGet := fun f => monadLift (m := m) (MonadState.modifyGet f) } namespace EStateM inductive Result (ε σ α : Type u) | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variables {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) := ⟨Result.error (arbitrary _) (arbitrary _)⟩ end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variables {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) := ⟨fun s => Result.error (arbitrary ε) s⟩ @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → α × σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) := (save : σ → δ) (restore : σ → δ → σ) @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ PUnit) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) := { bind := EStateM.bind, pure := EStateM.pure, map := EStateM.map, seqRight := EStateM.seqRight } instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) := { orElse := EStateM.orElse } instance : MonadStateOf σ (EStateM ε σ) := { set := EStateM.set, get := EStateM.get, modifyGet := EStateM.modifyGet } instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) := { throw := EStateM.throw, tryCatch := EStateM.tryCatch } @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error _ _ => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ := { save := dummySave, restore := dummyRestore } end EStateM class Hashable (α : Type u) := (hash : α → USize) export Hashable (hash) @[extern "lean_usize_mix_hash"] constant mixHash (u₁ u₂ : USize) : USize @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : USize instance : Hashable String := ⟨String.hash⟩ namespace Lean /- Hierarchical names -/ inductive Name | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance : Inhabited Name := ⟨Name.anonymous⟩ protected def Name.hash : Name → USize | Name.anonymous => USize.ofNat32 1723 decide! | Name.str p s h => h | Name.num p v h => h instance : Hashable Name := ⟨Name.hash⟩ @[export lean_name_mk_string] def mkNameStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNameNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (if h : Less v usizeSz then USize.ofNatCore v h else USize.ofNat32 17 decide!)) def mkNameSimple (s : String) : Name := mkNameStr Name.anonymous s namespace Name @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => BEq.beq s₁ s₂ && Name.beq p₁ p₂ | num p₁ n₁ _, num p₂ n₂ _ => BEq.beq n₁ n₂ && Name.beq p₁ p₂ | _, _ => false instance : BEq Name := ⟨Name.beq⟩ protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => mkNameStr (Name.append n p) s | n, num p d _ => mkNameNum (Name.append n p) d instance : Append Name := ⟨Name.append⟩ end Name /- Syntax -/ /-- Source information of syntax atoms. All information is generally set for unquoted syntax and unset for syntax in syntax quotations, but syntax transformations might want to invalidate only one side to make the pretty printer reformat it. In the special case of the delaborator, we also use purely synthetic position information without whitespace information. -/ structure SourceInfo := /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ (leading : Option Substring := none) (pos : Option String.Pos := none) (trailing : Option Substring := none) instance : Inhabited SourceInfo := ⟨{}⟩ abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax := ⟨Syntax.missing⟩ /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => mkNameSimple v | Syntax.ident _ _ _ _ => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.get! i | _ => Syntax.missing -- panic! "Syntax.getArg: not a node" -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty end Syntax inductive ParserDescr | andthen : ParserDescr → ParserDescr → ParserDescr | orelse : ParserDescr → ParserDescr → ParserDescr | optional : ParserDescr → ParserDescr | lookahead : ParserDescr → ParserDescr | «try» : ParserDescr → ParserDescr | many : ParserDescr → ParserDescr | many1 : ParserDescr → ParserDescr | sepBy : ParserDescr → ParserDescr → Bool → ParserDescr | sepBy1 : ParserDescr → ParserDescr → Bool → ParserDescr | node : Name → Nat → ParserDescr → ParserDescr | trailingNode : Name → Nat → ParserDescr → ParserDescr | symbol : String → ParserDescr | nonReservedSymbol : String → Bool → ParserDescr | noWs : ParserDescr | numLit : ParserDescr | strLit : ParserDescr | charLit : ParserDescr | nameLit : ParserDescr | interpolatedStr : ParserDescr → ParserDescr -- interpolated string | ident : ParserDescr | cat : Name → Nat → ParserDescr | parser : Name → ParserDescr | notFollowedBy : ParserDescr → ParserDescr | withPosition : ParserDescr → ParserDescr | checkCol : Bool → ParserDescr instance : Inhabited ParserDescr := ⟨ParserDescr.symbol ""⟩ abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := add reservedMacroScope 1 /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). -/ class MonadQuotation (m : Type → Type) := -- Get the fresh scope of the current macro invocation (getCurrMacroScope : m MacroScope) (getMainModule : m Name) /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ (withFreshMacroScope {α : Type} : m α → m α) export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) instance {m n : Type → Type} [MonadQuotation m] [MonadLift m n] [MonadFunctorT m n] : MonadQuotation n := { getCurrMacroScope := liftM (m := m) getCurrMacroScope, getMainModule := liftM (m := m) getMainModule, withFreshMacroScope := monadMap (m := m) withFreshMacroScope } /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => if s = "_@" then p else eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => mkNameNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView := (name : Name) (imported : Name) (mainModule : Name) (scopes : List MacroScope) instance : Inhabited MacroScopesView := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _⟩⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (mkNameStr (append (append (mkNameStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl mkNameNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (mkNameStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (mkNameNum acc n) | _, acc => panic "unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => if str = "_@" then { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } else extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => if str = "_@" then { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } else extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => mkNameNum n scp | false => { view with imported := view.scopes.foldl mkNameNum (append view.imported view.mainModule), mainModule := mainModule, scopes := List.cons scp List.nil }.review | false => mkNameNum (mkNameStr (append (mkNameStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ constant MacroEnvPointed : PointedType.{0} def MacroEnv : Type := MacroEnvPointed.type instance : Inhabited MacroEnv := ⟨MacroEnvPointed.val⟩ structure Context := (macroEnv : MacroEnv) (mainModule : Name) (currMacroScope : MacroScope) (currRecDepth : Nat := 0) (maxRecDepth : Nat := defaultMaxRecDepth) inductive Exception | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) abbrev Macro := Syntax → MacroM Syntax namespace Macro def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (ref : Syntax) (msg : String) : MacroM α := throw (Exception.error ref msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s, add s 1))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => if ctx.currRecDepth = ctx.maxRecDepth then throw (Exception.error ref maxRecDepthErrorMessage) else withReader (fun ctx => { ctx with currRecDepth := add ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM := { getCurrMacroScope := fun ctx => pure ctx.currMacroScope, getMainModule := fun ctx => pure ctx.mainModule, withFreshMacroScope := Macro.withFreshMacroScope } unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv := unsafeCast expandMacro? @[implementedBy mkMacroEnvImp] constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) := throwError stx "expandMacro has not been set" def mkMacroEnvSimple : MacroEnv := mkMacroEnv expandMacroNotAvailable? unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) := bind read fun ctx => let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv) f stx /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ @[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax) end Macro export Macro (expandMacro?) end Lean syntax "foo" term : term macro_rules | `(foo $x) => x #check foo 10
cf2bc3b01a034d4ece5259bbbe8508233801ccd3
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world8/level6.lean
92faa4acc38d99b96799c73e4c244645e8ecbbef
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
792
lean
import game.world8.level5 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 6: `add_left_cancel` The theorem `add_left_cancel` is the theorem that you can cancel on the left when you're doing addition -- if `t + a = t + b` then `a = b`. There is a three-line proof which ends in `exact add_right_cancel a t b` (or even `exact add_right_cancel _ _ _`); this strategy involves changing the goal to the statement of `add_right_cancel` somehow. -/ /- Theorem On the set of natural numbers, addition has the left cancellation property. In other words, if there are natural numbers $a, b$ and $t$ such that $$ t + a = t + b, $$ then we have $a = b$. -/ theorem add_left_cancel (t a b : mynat) : t + a = t + b → a = b := begin [nat_num_game] end end mynat -- hide
41fd0c784f0f201ca594763783c7f2b910657314
947b78d97130d56365ae2ec264df196ce769371a
/src/Init/Data/Array/QSort.lean
ad5295eb720ea7baf98f6b4b063aaad529222f03
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,903
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Array.Basic namespace Array -- TODO: remove the [Inhabited α] parameters as soon as we have the tactic framework for automating proof generation and using Array.fget -- TODO: remove `partial` using well-founded recursion @[specialize] private partial def qpartitionAux {α : Type} [Inhabited α] (lt : α → α → Bool) (hi : Nat) (pivot : α) : Array α → Nat → Nat → Nat × Array α | as, i, j => if j < hi then if lt (as.get! j) pivot then let as := as.swap! i j; qpartitionAux as (i+1) (j+1) else qpartitionAux as i (j+1) else let as := as.swap! i hi; (i, as) @[inline] def qpartition {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (lo hi : Nat) : Nat × Array α := let mid := (lo + hi) / 2; let as := if lt (as.get! mid) (as.get! lo) then as.swap! lo mid else as; let as := if lt (as.get! hi) (as.get! lo) then as.swap! lo hi else as; let as := if lt (as.get! mid) (as.get! hi) then as.swap! mid hi else as; let pivot := as.get! hi; qpartitionAux lt hi pivot as lo lo @[specialize] partial def qsortAux {α : Type} [Inhabited α] (lt : α → α → Bool) : Array α → Nat → Nat → Array α | as, low, high => if low < high then let p := qpartition as lt low high; -- TODO: fix `partial` support in the equation compiler, it breaks if we use `let (mid, as) := partition as lt low high` let mid := p.1; let as := p.2; if mid >= high then as else let as := qsortAux as low mid; qsortAux as (mid+1) high else as @[inline] def qsort {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (low := 0) (high := as.size - 1) : Array α := qsortAux lt as low high end Array
a24bd0220216356cd805637e602f24f1d11d5616
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/notes/2020.01.30-notes.lean
f1fe7b77f9dc4d987fbb95929a689b05403bf828
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
1,868
lean
--Takes any nat and returns 0 #check (λ (n : nat), 0) --function takes n of type nat and returns 0 -- Takes and two nat and returns the same nat #check (λ (n:nat), n) -- Takes any two nat and returns (a+b) #check (λ (a b :nat), a+b) --Takes a, b, c type nat and returns ax^2 + bx + c #check (λ (a b c x:nat), a*x^2+b*x^2+c) #check (fun (a b c x:nat), a*x^2+b*x+c) 1 2 3 10 #eval (fun (a b c x:nat), a*x^2+b*x+c) 1 2 3 10 #eval (λ (a b :nat), a+b) 3 4 -- binding names to functions def z:= λ (n: nat), 0 /- namespace hidden def id_nat := λ(n:nat), n end hidden #check id #check hidden.id_nat -/ def id_nat:=λ(n:nat), n def add:= λ(a b:nat), a+b def quad:= λ(a b c x: nat), a*x^2 + b*x + c --function application expressions #eval z 5 #eval id_nat 5 #eval add 2 3 #eval quad 1 2 3 10 --Lean has type reference, thats how it knows some types -- C-Style def z' (n:nat) :=0 #reduce z' --By cases def z'' : nat → nat |_:=0 --By cases def id_nat'': nat→ nat | n:=n -- C style def quad'(a b c x: nat):= a*x^2 + b*x + c -- By cases def quad'': nat → nat → nat → nat → nat | a b c x:= a*x^2 + b*x + c -- Defining things with different styles -- Multiple types of arguments def if_then_else (b:bool) (n m : nat) := match b with --match b with possible constructors -- C style | tt :=n | ff := m end --Lamda style def my_ite: bool → nat → nat → nat := λ (b : bool) (n m : nat), -- argument types separated match b with | tt:=n | ff:= m end --No name, basically if then else def my_ite' : bool → nat → nat → nat | tt n m := n | ff m n := m --| _ _ m := m ->otherwise ignore the first arg and return the second /- Error message if misspelling tt to t equation compiler error, equation #2 has not been used in the compilation (possible solution: delete equation) -/
d9e485350981afd62653cab277954326fb25a5b5
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/inst/reactor.lean
bfc455a71936258a707b6ecbcb139bbdf2696a7e
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
16,630
lean
import inst.reaction import tactic open reactor open reactor.ports -- Cf. inst/primitives.lean variables (υ : Type*) [decidable_eq υ] @[ext] structure reactor := (input : ports υ) (output : ports υ) (state : state_vars υ) (priorities : finset ℕ) (reactions : ℕ → reaction υ) namespace reactor variables {υ} -- Reactions' equality is non-constructively decidable. noncomputable instance : decidable_eq (reactor υ) := classical.dec_eq _ -- A reaction is a member of a reactor if the reactor contains an ID that maps to it. instance rcn_mem : has_mem (reaction υ) (reactor υ) := {mem := λ rcn rtr, ∃ p ∈ rtr.priorities, rtr.reactions p = rcn} -- Reactors are equivalent if they are structurally the same. instance equiv : has_equiv (reactor υ) := ⟨λ rtr rtr', rtr.priorities = rtr'.priorities ∧ rtr.reactions = rtr'.reactions⟩ -- Reactor equivalence is reflexive. @[refl] lemma equiv_refl (rtr : reactor υ) : rtr ≈ rtr := by simp [(≈)] -- Reactor equivalence is symmetric. @[symm] lemma equiv_symm {rtr rtr' : reactor υ} (h : rtr ≈ rtr') : rtr' ≈ rtr := begin simp [(≈)] at ⊢ h, split, exact symm h.left, exact symm h.right end -- Reactor equivalence is transitive. @[trans] lemma equiv_trans {rtr₁ rtr₂ rtr₃ : reactor υ} (h₁₂ : rtr₁ ≈ rtr₂) (h₂₃ : rtr₂ ≈ rtr₃) : rtr₁ ≈ rtr₃ := begin simp [(≈)] at ⊢ h₁₂ h₂₃, split, exact eq.trans h₁₂.left h₂₃.left, exact eq.trans h₁₂.right h₂₃.right end -- Returns the port-list of a given role. def prts (rtr : reactor υ) : ports.role → ports υ | role.input := rtr.input | role.output := rtr.output -- Returns the value of a given port. def port (rtr : reactor υ) : ports.role → ℕ → option υ | role.input := rtr.input.nth | role.output := rtr.output.nth -- Updates a given port in the reactor, to hold a given value. def update (rtr : reactor υ) : ports.role → ℕ → option υ → reactor υ | role.input p v := {input := rtr.input.update_nth p v, ..rtr} | role.output p v := {output := rtr.output.update_nth p v, ..rtr} -- Updating a reactor's port with the value it alread has, produces the same reactor. @[simp] lemma update_self_eq (rtr : reactor υ) (r : ports.role) (p : ℕ) : rtr.update r p (rtr.port r p) = rtr := begin induction r ; { simp only [update, port, ports.nth], rw list.update_nth_same, ext ; refl } end -- All values that are not updated stay the same. @[simp] lemma update_ne (rtr : reactor υ) (r : ports.role) {p p' : ℕ} (v : option υ) (h : p ≠ p') : (rtr.update r p v).port r p' = rtr.port r p' := by cases r ; simp only [update, port, ports.nth, list.nth_update_nth_ne _ _ h] -- Updating a reactor's port produces an equivalent reactor. @[simp] lemma update_equiv (rtr : reactor υ) (r : ports.role) (p : ℕ) (v : option υ) : rtr.update r p v ≈ rtr := by induction r ; simp [(≈), update] -- Updating different ports of a reactor is commutative. lemma update_comm (rtr : reactor υ) {p p' : ℕ} (r : ports.role) (v v' : option υ) (h : p ≠ p') : (rtr.update r p v).update r p' v' = (rtr.update r p' v').update r p v := begin induction r ; { simp only [update], repeat { split }, exact list.update_nth_comm _ _ _ h } end -- Updating a reactor's port does not change the reactions. @[simp] lemma update_reactions_eq (rtr : reactor υ) (r : ports.role) (p : ℕ) (v : option υ) : (rtr.update r p v).reactions = rtr.reactions := (update_equiv rtr r p v).right -- Updating a reactor's port does not change the priorities. @[simp] lemma update_priorities_eq (rtr : reactor υ) (r : ports.role) (p : ℕ) (v : option υ) : (rtr.update r p v).priorities = rtr.priorities := (update_equiv rtr r p v).left -- Updating a reactor's port does not change the state. @[simp] lemma update_state_eq (rtr : reactor υ) (r : ports.role) (p : ℕ) (v : option υ) : (rtr.update r p v).state = rtr.state := by cases r ; simp [update] -- Updating a reactor's input/output ports does not change its output/input ports. @[simp] lemma update_ports_eq (rtr : reactor υ) (r : ports.role) (p : ℕ) (v : option υ) : (rtr.update r p v).port r.opposite = rtr.port r.opposite := begin cases r ; { simp [update, ports.role.opposite], ext, split ; simp [port] } end -- Updating the same port twice makes the first update irrelevant. @[simp] lemma update_same (rtr : reactor υ) (r : ports.role) (p : ℕ) (v v' : option υ) : (rtr.update r p v).update r p v' = rtr.update r p v' := by cases r ; simp [update, list.update_same] -- If changing on port gets us from one reactor to another, then we can also do this in reverse. lemma update_symm {rtr rtr' : reactor υ} {r : ports.role} {p : ℕ} {v : option υ} (h : rtr = rtr'.update r p v) : rtr' = rtr.update r p (rtr'.port r p) := by cases r ; simp [h, update_same, update_self_eq] -- Two reactors are equal relative to a reaction, if they only differ by the values -- of input ports which are not an input-dependency of the reaction. inductive eq_rel_to (rcn : ℕ) : reactor υ → reactor υ → Prop | single {p : ℕ} {v : option υ} {rtr rtr' : reactor υ}: (rtr' = rtr.update role.input p v) → (p ∉ (rtr.reactions rcn).deps role.input) → eq_rel_to rtr rtr' | multiple {rtr rtrₘ rtr' : reactor υ} : (eq_rel_to rtr rtrₘ) → (eq_rel_to rtrₘ rtr') → eq_rel_to rtr rtr' notation r =i= s := (eq_rel_to i r s) -- Relative reactor equality implies reactor equivalence. lemma eq_rel_to_equiv {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : rtr ≈ rtr' := begin induction h, case eq_rel_to.single { have hₑ, from update_equiv h_rtr role.input h_p h_v, rw ←h_ᾰ at hₑ, symmetry, exact hₑ }, case eq_rel_to.multiple { transitivity, exact h_ih_ᾰ, exact h_ih_ᾰ_1 } end -- Relative reactor equality is reflexive. lemma eq_rel_to_refl (rtr : reactor υ) (rcn : ℕ) : rtr =rcn= rtr := begin obtain ⟨p, hₚ⟩ := infinite.exists_not_mem_finset (rtr.reactions rcn).dᵢ, have h, from symm (update_self_eq rtr role.input p), exact eq_rel_to.single h hₚ end -- Relative reactor equality is symmetric. lemma eq_rel_to_symm {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : rtr' =rcn= rtr := begin induction h, case eq_rel_to.single { have h, from eq_rel_to.single h_ᾰ h_ᾰ_1, rw (eq_rel_to_equiv h).right at h_ᾰ_1, exact eq_rel_to.single (update_symm h_ᾰ) h_ᾰ_1 }, case eq_rel_to.multiple { exact eq_rel_to.multiple h_ih_ᾰ_1 h_ih_ᾰ } end -- Relatively equal reactors have the same state. lemma eq_rel_to_eq_state {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : rtr.state = rtr'.state := begin induction h, case eq_rel_to.single { rw [←(update_state_eq h_rtr role.input h_p h_v), h_ᾰ], }, case eq_rel_to.multiple { transitivity, exact h_ih_ᾰ, exact h_ih_ᾰ_1 } end -- Relatively equal reactors have the same output. lemma eq_rel_to_eq_output {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : rtr.output = rtr'.output := begin induction h, case eq_rel_to.single { have h', from update_ports_eq h_rtr role.input h_p h_v, rw [ports.role.opposite, ←h_ᾰ, port, port] at h', have hₗ : h_rtr.output.length = h_rtr'.output.length, by simp only [update, h_ᾰ], exact ports.ext (symm h') hₗ }, case eq_rel_to.multiple { transitivity, exact h_ih_ᾰ, exact h_ih_ᾰ_1 } end -- Relatively equal reactors must correspond on all ports that are part of the -- associated reaction's input-dependencies. lemma eq_rel_to_eq_at_dᵢ {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : rtr.input =(rtr.reactions rcn).dᵢ= rtr'.input := begin unfold ports.eq_at, intros x hₓ, induction h, case eq_rel_to.single { have hₙ, from ne_of_mem_of_not_mem hₓ h_ᾰ_1, have hₑ, from update_ne h_rtr role.input h_v (ne.symm hₙ), repeat { rw port at hₑ }, rw ←h_ᾰ at hₑ, exact symm hₑ }, case eq_rel_to.multiple { have h, from h_ih_ᾰ hₓ, rw (eq_rel_to_equiv h_ᾰ).right at hₓ, have h', from h_ih_ᾰ_1 hₓ, transitivity, exact h, exact h' } end -- For relatively equal reactors, either both or neither triggers the relevant reaction. lemma eq_rel_to_triggers_iff {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : (rtr.reactions rcn).triggers_on rtr.input ↔ (rtr'.reactions rcn).triggers_on rtr'.input := begin unfold reaction.triggers_on, have hₑ, from eq_rel_to_equiv h, have hd, from eq_rel_to_eq_at_dᵢ h, repeat { rw hₑ.right at hd ⊢ }, split, all_goals { intro h', obtain ⟨t, hₜ, v, hᵥ⟩ := h', existsi t, existsi hₜ, existsi v, unfold ports.eq_at at hd, have hd', from hd t t.property, rw hᵥ at hd' }, exact symm hd', exact hd', end -- Returns the result of merging given state and output ports into a reactor. def merge (rtr : reactor υ) (os : ports υ × state_vars υ) : reactor υ := {output := rtr.output.merge os.1, state := os.2, ..rtr} -- If the inhabited indices of a given reaction output assignment are a subset of some set `dₒ`, -- then merging that output into a reactor can only produce output-port differences at ports from `dₒ`. lemma merge_inhabited_eq_diff (rtr : reactor υ) {os : ports υ × state_vars υ} {dₒ : finset ℕ} (h : os.1.inhabited_indices ⊆ dₒ) : (rtr.output.index_diff (rtr.merge os).output) ⊆ dₒ := begin unfold merge, transitivity, exact ports.merge_index_diff_sub_inhabited rtr.output os.1, exact h end -- Merging the same data into relatively equal reactors, produces relatively equal reactors. lemma merge_eq_rel_to {rtr rtr' : reactor υ} {rcn : ℕ} {os : ports υ × state_vars υ} (h : rtr =rcn= rtr') : (rtr.merge os) =rcn= (rtr'.merge os) := begin unfold merge, rw [←eq_rel_to_eq_output h, ←(eq_rel_to_equiv h).left, ←(eq_rel_to_equiv h).right], induction h, case eq_rel_to.single { have hᵢ : h_rtr'.input = h_rtr.input.update_nth h_p h_v, by finish, rw hᵢ, exact eq_rel_to.single (refl _) h_ᾰ_1 }, case eq_rel_to.multiple { rw [←eq_rel_to_eq_output h_ᾰ, ←(eq_rel_to_equiv h_ᾰ).left, ←(eq_rel_to_equiv h_ᾰ).right] at h_ih_ᾰ_1, exact eq_rel_to.multiple h_ih_ᾰ h_ih_ᾰ_1 } end -- Merging data into a reactor produces an equivalent reactor. @[simp] lemma merge_equiv (rtr : reactor υ) (os : ports υ × state_vars υ) : rtr.merge os ≈ rtr := by simp [(≈), merge] -- Returns the reactor that we get by running a given reaction and merging its outputs into the reactor. noncomputable def run (rtr : reactor υ) (rcn : ℕ) : reactor υ := if (rtr.reactions rcn).triggers_on rtr.input then rtr.merge ((rtr.reactions rcn) rtr.input rtr.state) else rtr -- Running a reactor does not change its input. @[simp] lemma run_eq_input (rtr : reactor υ) (rcn : ℕ) : (rtr.run rcn).input = rtr.input := by { unfold run, split_ifs ; simp [merge] } -- Running the reaction relative to which two reactors are equal, produces the same output. lemma run_rcn_eq_rel_to {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : (rtr.reactions rcn) rtr.input rtr.state = (rtr'.reactions rcn) rtr'.input rtr'.state := begin rw eq_rel_to_eq_state h, have h', from (eq_rel_to_eq_at_dᵢ h), rw (eq_rel_to_equiv h).right at h' ⊢, exact (rtr'.reactions rcn).in_con _ h' end -- Running relatively equal reactors produces relatively equal reactors. theorem run_eq_rel_to {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : (rtr.run rcn) =rcn= (rtr'.run rcn) := begin unfold run, by_cases hf : (rtr.reactions rcn).triggers_on rtr.input, { rw if_pos hf, rw eq_rel_to_triggers_iff h at hf, rw [if_pos hf, run_rcn_eq_rel_to h], exact merge_eq_rel_to h }, { rw if_neg hf, rw eq_rel_to_triggers_iff h at hf, rw if_neg hf, exact h } end -- Running a reactor produces an equivalent reactor. @[simp] lemma run_equiv (rtr : reactor υ) (rcn : ℕ) : rtr.run rcn ≈ rtr := begin unfold run, by_cases hf : (rtr.reactions rcn).triggers_on rtr.input, simp [if_pos hf], simp [if_neg hf] end -- Updating an input port that is independent of a reaction can be done before or after running that reaction, -- without changing the resulting reactor. lemma run_update_input_comm {rtr : reactor υ} {rcn : ℕ} {i : ℕ} (v : option υ) (h : i ∉ (rtr.reactions rcn).deps role.input) : (rtr.run rcn).update role.input i v = (rtr.update role.input i v).run rcn := begin have hᵣ, from eq_rel_to.single (refl (rtr.update role.input i v)) h, replace hᵣ := run_eq_rel_to hᵣ, have hₑ, from equiv_trans (update_equiv (rtr.run rcn) role.input i v) (run_equiv rtr rcn), rw ←hₑ.right at h, have hₗ, from eq_rel_to.single (refl ((rtr.run rcn).update role.input i v)) h, replace hₗ := eq_rel_to_symm hₗ, have h', from eq_rel_to.multiple hₗ hᵣ, ext1, simp [update], exact eq_rel_to_eq_output h', exact eq_rel_to_eq_state h', exact (eq_rel_to_equiv h').left, exact (eq_rel_to_equiv h').right end -- Updating multiple input ports that are independent of a reaction can be done before or after running that reaction, -- without changing the resulting reactor. lemma run_update_inputs_comm {rtr rtr' : reactor υ} {rcn : ℕ} (h : rtr =rcn= rtr') : {reactor . input := rtr'.input, ..(rtr.run rcn)} = rtr'.run rcn := begin induction h, case eq_rel_to.single { rw [h_ᾰ, ←(run_eq_input _ rcn), ←(run_update_input_comm h_v h_ᾰ_1)], refl }, case eq_rel_to.multiple { cases h_rtrₘ.run rcn, injection h_ih_ᾰ, rw [←h_2, ←h_3, ←h_4, ←h_5] at h_ih_ᾰ_1, exact h_ih_ᾰ_1 } end -- Any ports that change from running a reaction in a reactor, have to be part -- of the reaction's output-dependencies. I.e. the set index-diff of the output -- has to be a subset of the reaction's `dₒ`. lemma run_out_diff_sub_dₒ (rtr : reactor υ) (rcn : ℕ) : rtr.output.index_diff (rtr.run rcn).output ⊆ (rtr.reactions rcn).deps role.output := begin unfold run, by_cases hf : (rtr.reactions rcn).triggers_on rtr.input, { rw if_pos hf, have hₛ, from reaction.outputs_sub_dₒ (rtr.reactions rcn) rtr.input rtr.state, exact merge_inhabited_eq_diff rtr hₛ, }, simp [if_neg hf, ports.index_diff_eq_ports_empty (refl rtr.output)] end -- Output ports which are not in the output dependencies of a reaction, are not affected by running that reaction @[simp] lemma run_out_not_dₒ_eq {rtr : reactor υ} {rcn : ℕ} {p : ℕ} (h : p ∉ (rtr.reactions rcn).deps role.output) : (rtr.run rcn).port role.output p = rtr.port role.output p := begin unfold run, by_cases hf : (rtr.reactions rcn).triggers_on rtr.input, { rw if_pos hf, unfold merge port, exact merge_none_eq _ ((rtr.reactions rcn).out_con rtr.input rtr.state h), }, rw if_neg hf end end reactor
be42ed1f2c79e63261f37d1a2295cf11a264e95e
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Init/System/ST.lean
4ee82168f7a4d12e565203a8b99e76db437e8c95
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,394
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 -/ prelude import Init.Classical import Init.Control.EState import Init.Control.Reader def EST (ε : Type) (σ : Type) : Type → Type := EStateM ε σ abbrev ST (σ : Type) := EST Empty σ instance (ε σ : Type) : Monad (EST ε σ) := inferInstanceAs (Monad (EStateM _ _)) instance (ε σ : Type) : MonadExceptOf ε (EST ε σ) := inferInstanceAs (MonadExceptOf ε (EStateM _ _)) instance {ε σ : Type} {α : Type} [Inhabited ε] : Inhabited (EST ε σ α) := inferInstanceAs (Inhabited (EStateM _ _ _)) instance (σ : Type) : Monad (ST σ) := inferInstanceAs (Monad (EST _ _)) -- Auxiliary class for inferring the "state" of `EST` and `ST` monads class STWorld (σ : outParam Type) (m : Type → Type) instance {σ m n} [STWorld σ m] [MonadLift m n] : STWorld σ n := ⟨⟩ instance {ε σ} : STWorld σ (EST ε σ) := ⟨⟩ @[inline] def runEST {ε α : Type} (x : forall (σ : Type), EST ε σ α) : Except ε α := match x Unit () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error ex _ => Except.error ex @[inline] def runST {α : Type} (x : forall (σ : Type), ST σ α) : α := match x Unit () with | EStateM.Result.ok a _ => a | EStateM.Result.error ex _ => nomatch ex instance {ε σ} : MonadLift (ST σ) (EST ε σ) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ namespace ST /- References -/ constant RefPointed : PointedType.{0} structure Ref (σ : Type) (α : Type) : Type := (ref : RefPointed.type) (h : Nonempty α) instance {σ α} [Inhabited α] : Inhabited (Ref σ α) := ⟨{ ref := RefPointed.val, h := Nonempty.intro $ arbitrary _}⟩ namespace Prim set_option pp.all true /- Auxiliary definition for showing that `ST σ α` is inhabited when we have a `Ref σ α` -/ private noncomputable def inhabitedFromRef {σ α} (r : Ref σ α) : ST σ α := let inh : Inhabited α := Classical.inhabitedOfNonempty r.h pure $ arbitrary α @[extern "lean_st_mk_ref"] constant mkRef {σ α} (a : α) : ST σ (Ref σ α) := pure { ref := RefPointed.val, h := Nonempty.intro a } @[extern "lean_st_ref_get"] constant Ref.get {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_set"] constant Ref.set {σ α} (r : @& Ref σ α) (a : α) : ST σ Unit @[extern "lean_st_ref_swap"] constant Ref.swap {σ α} (r : @& Ref σ α) (a : α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_take"] unsafe constant Ref.take {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_ptr_eq"] constant Ref.ptrEq {σ α} (r1 r2 : @& Ref σ α) : ST σ Bool @[inline] unsafe def Ref.modifyUnsafe {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.take r Ref.set r (f v) @[inline] unsafe def Ref.modifyGetUnsafe {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.take r let (b, a) := f v Ref.set r a pure b @[implementedBy Ref.modifyUnsafe] def Ref.modify {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.get r Ref.set r (f v) @[implementedBy Ref.modifyGetUnsafe] def Ref.modifyGet {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.get r let (b, a) := f v Ref.set r a pure b end Prim section variables {σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST σ) m] @[inline] def mkRef {α : Type} (a : α) : m (Ref σ α) := liftM $ Prim.mkRef a @[inline] def Ref.get {α : Type} (r : Ref σ α) : m α := liftM $ Prim.Ref.get r @[inline] def Ref.set {α : Type} (r : Ref σ α) (a : α) : m Unit := liftM $ Prim.Ref.set r a @[inline] def Ref.swap {α : Type} (r : Ref σ α) (a : α) : m α := liftM $ Prim.Ref.swap r a @[inline] unsafe def Ref.take {α : Type} (r : Ref σ α) : m α := liftM $ Prim.Ref.take r @[inline] def Ref.ptrEq {α : Type} (r1 r2 : Ref σ α) : m Bool := liftM $ Prim.Ref.ptrEq r1 r2 @[inline] def Ref.modify {α : Type} (r : Ref σ α) (f : α → α) : m Unit := liftM $ Prim.Ref.modify r f @[inline] def Ref.modifyGet {α : Type} {β : Type} (r : Ref σ α) (f : α → β × α) : m β := liftM $ Prim.Ref.modifyGet r f end end ST
d86be39f5b059abe116849f5c29a54e38772240b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/splitAtCode.lean
f38b01b2188e1ae3b7cc2e967202ffbada444c98
[ "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
212
lean
inductive Foo where | ctor1 (s : Nat) | ctor2 (s : String) def test (x y : Foo) : Decidable (match (x, y) with | (.ctor1 s₁, .ctor1 s₂) => ¬s₁ = s₂ | x => False) := by split <;> infer_instance
9d8d3e05f55d339e3ee75b532013f8c0ceebea57
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/localization/localization_localization.lean
901d2763d30a632fc187d7524219613d31b9e116
[ "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
13,058
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.localization.at_prime import ring_theory.localization.basic import ring_theory.localization.fraction_ring /-! # Localizations of localizations ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) {S : Type*} [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] open function open_locale big_operators namespace is_localization section localization_localization variable (M) variables (N : submonoid S) (T : Type*) [comm_ring T] [algebra R T] section variables [algebra S T] [is_scalar_tower R S T] /-- Localizing wrt `M ⊆ R` and then wrt `N ⊆ S = M⁻¹R` is equal to the localization of `R` wrt this module. See `localization_localization_is_localization`. -/ -- This should only be defined when `S` is the localization `M⁻¹R`, hence the nolint. @[nolint unused_arguments] def localization_localization_submodule : submonoid R := (N ⊔ M.map (algebra_map R S)).comap (algebra_map R S) variables {M N} @[simp] lemma mem_localization_localization_submodule {x : R} : x ∈ localization_localization_submodule M N ↔ ∃ (y : N) (z : M), algebra_map R S x = y * algebra_map R S z := begin rw [localization_localization_submodule, submonoid.mem_comap, submonoid.mem_sup], split, { rintros ⟨y, hy, _, ⟨z, hz, rfl⟩, e⟩, exact ⟨⟨y, hy⟩, ⟨z, hz⟩ ,e.symm⟩ }, { rintros ⟨y, z, e⟩, exact ⟨y, y.prop, _, ⟨z, z.prop, rfl⟩, e.symm⟩ } end variables (M N) [is_localization M S] lemma localization_localization_map_units [is_localization N T] (y : localization_localization_submodule M N) : is_unit (algebra_map R T y) := begin obtain ⟨y', z, eq⟩ := mem_localization_localization_submodule.mp y.prop, rw [is_scalar_tower.algebra_map_apply R S T, eq, ring_hom.map_mul, is_unit.mul_iff], exact ⟨is_localization.map_units T y', (is_localization.map_units _ z).map (algebra_map S T)⟩, end lemma localization_localization_surj [is_localization N T] (x : T) : ∃ (y : R × localization_localization_submodule M N), x * (algebra_map R T y.2) = algebra_map R T y.1 := begin rcases is_localization.surj N x with ⟨⟨y, s⟩, eq₁⟩, -- x = y / s rcases is_localization.surj M y with ⟨⟨z, t⟩, eq₂⟩, -- y = z / t rcases is_localization.surj M (s : S) with ⟨⟨z', t'⟩, eq₃⟩, -- s = z' / t' dsimp only at eq₁ eq₂ eq₃, use z * t', use z' * t, -- x = y / s = (z * t') / (z' * t) { rw mem_localization_localization_submodule, refine ⟨s, t * t', _⟩, rw [ring_hom.map_mul, ← eq₃, mul_assoc, ← ring_hom.map_mul, mul_comm t, submonoid.coe_mul] }, { simp only [subtype.coe_mk, ring_hom.map_mul, is_scalar_tower.algebra_map_apply R S T, ← eq₃, ← eq₂, ← eq₁], ring }, end lemma localization_localization_eq_iff_exists [is_localization N T] (x y : R) : algebra_map R T x = algebra_map R T y ↔ ∃ (c : localization_localization_submodule M N), x * c = y * c := begin rw [is_scalar_tower.algebra_map_apply R S T, is_scalar_tower.algebra_map_apply R S T, is_localization.eq_iff_exists N T], split, { rintros ⟨z, eq₁⟩, rcases is_localization.surj M (z : S) with ⟨⟨z', s⟩, eq₂⟩, dsimp only at eq₂, obtain ⟨c, eq₃ : x * z' * ↑ c = y * z' * ↑ c⟩ := (is_localization.eq_iff_exists M S).mp _, swap, { rw [ring_hom.map_mul, ring_hom.map_mul, ← eq₂, ← mul_assoc, ← mul_assoc, ← eq₁] }, use z' * c, { rw mem_localization_localization_submodule, refine ⟨z, s * c, _⟩, rw [ring_hom.map_mul, ← eq₂, mul_assoc, ← ring_hom.map_mul, submonoid.coe_mul] }, { simpa only [mul_assoc] using eq₃ } }, { rintro ⟨⟨c, hc⟩, eq₁ : x * c = y * c⟩, rw mem_localization_localization_submodule at hc, rcases hc with ⟨z₁, z, eq₂⟩, use z₁, refine (is_localization.map_units S z).mul_left_inj.mp _, rw [mul_assoc, mul_assoc, ← eq₂, ← ring_hom.map_mul, ← ring_hom.map_mul, eq₁] } end /-- Given submodules `M ⊆ R` and `N ⊆ S = M⁻¹R`, with `f : R →+* S` the localization map, we have `N ⁻¹ S = T = (f⁻¹ (N • f(M))) ⁻¹ R`. I.e., the localization of a localization is a localization. -/ lemma localization_localization_is_localization [is_localization N T] : is_localization (localization_localization_submodule M N) T := { map_units := localization_localization_map_units M N T, surj := localization_localization_surj M N T, eq_iff_exists := localization_localization_eq_iff_exists M N T } include M /-- Given submodules `M ⊆ R` and `N ⊆ S = M⁻¹R`, with `f : R →+* S` the localization map, if `N` contains all the units of `S`, then `N ⁻¹ S = T = (f⁻¹ N) ⁻¹ R`. I.e., the localization of a localization is a localization. -/ lemma localization_localization_is_localization_of_has_all_units [is_localization N T] (H : ∀ (x : S), is_unit x → x ∈ N) : is_localization (N.comap (algebra_map R S).to_monoid_hom) T := begin convert localization_localization_is_localization M N T, symmetry, rw sup_eq_left, rintros _ ⟨x, hx, rfl⟩, exact H _ (is_localization.map_units _ ⟨x, hx⟩), end /-- Given a submodule `M ⊆ R` and a prime ideal `p` of `S = M⁻¹R`, with `f : R →+* S` the localization map, then `T = Sₚ` is the localization of `R` at `f⁻¹(p)`. -/ lemma is_localization_is_localization_at_prime_is_localization (p : ideal S) [Hp : p.is_prime] [is_localization.at_prime T p] : is_localization.at_prime T (p.comap (algebra_map R S)) := begin apply localization_localization_is_localization_of_has_all_units M p.prime_compl T, intros x hx hx', exact (Hp.1 : ¬ _) (p.eq_top_of_is_unit_mem hx' hx), end instance (p : ideal (localization M)) [p.is_prime] : algebra R (localization.at_prime p) := localization.algebra instance (p : ideal (localization M)) [p.is_prime] : is_scalar_tower R (localization M) (localization.at_prime p) := is_scalar_tower.of_algebra_map_eq' rfl instance localization_localization_at_prime_is_localization (p : ideal (localization M)) [p.is_prime] : is_localization.at_prime (localization.at_prime p) (p.comap (algebra_map R _)) := is_localization_is_localization_at_prime_is_localization M _ _ /-- Given a submodule `M ⊆ R` and a prime ideal `p` of `M⁻¹R`, with `f : R →+* S` the localization map, then `(M⁻¹R)ₚ` is isomorphic (as an `R`-algebra) to the localization of `R` at `f⁻¹(p)`. -/ noncomputable def localization_localization_at_prime_iso_localization (p : ideal (localization M)) [p.is_prime] : localization.at_prime (p.comap (algebra_map R _)) ≃ₐ[R] localization.at_prime p := is_localization.alg_equiv (p.comap (algebra_map R _)).prime_compl _ _ end variables (S) /-- Given submonoids `M ≤ N` of `R`, this is the canonical algebra structure of `M⁻¹S` acting on `N⁻¹S`. -/ noncomputable def localization_algebra_of_submonoid_le (M N : submonoid R) (h : M ≤ N) [is_localization M S] [is_localization N T] : algebra S T := (is_localization.lift (λ y, (map_units T ⟨↑y, h y.prop⟩ : _)) : S →+* T).to_algebra /-- If `M ≤ N` are submonoids of `R`, then the natural map `M⁻¹S →+* N⁻¹S` commutes with the localization maps -/ lemma localization_is_scalar_tower_of_submonoid_le (M N : submonoid R) (h : M ≤ N) [is_localization M S] [is_localization N T] : @@is_scalar_tower R S T _ (localization_algebra_of_submonoid_le S T M N h).to_has_scalar _ := begin letI := localization_algebra_of_submonoid_le S T M N h, exact is_scalar_tower.of_algebra_map_eq' (is_localization.lift_comp _).symm end noncomputable instance (x : ideal R) [H : x.is_prime] [is_domain R] : algebra (localization.at_prime x) (localization (non_zero_divisors R)) := localization_algebra_of_submonoid_le _ _ x.prime_compl (non_zero_divisors R) (by { intros a ha, rw mem_non_zero_divisors_iff_ne_zero, exact λ h, ha (h.symm ▸ x.zero_mem) }) /-- If `M ≤ N` are submonoids of `R`, then `N⁻¹S` is also the localization of `M⁻¹S` at `N`. -/ lemma is_localization_of_submonoid_le (M N : submonoid R) (h : M ≤ N) [is_localization M S] [is_localization N T] [algebra S T] [is_scalar_tower R S T] : is_localization (N.map (algebra_map R S).to_monoid_hom) T := { map_units := begin rintro ⟨_, ⟨y, hy, rfl⟩⟩, convert is_localization.map_units T ⟨y, hy⟩, exact (is_scalar_tower.algebra_map_apply _ _ _ _).symm end, surj := λ y, begin obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj N y, refine ⟨⟨algebra_map _ _ x, _, _, s.prop, rfl⟩, _⟩, simpa [← is_scalar_tower.algebra_map_apply] using e end, eq_iff_exists := λ x₁ x₂, begin obtain ⟨⟨y₁, s₁⟩, e₁⟩ := is_localization.surj M x₁, obtain ⟨⟨y₂, s₂⟩, e₂⟩ := is_localization.surj M x₂, refine iff.trans _ (set.exists_image_iff (algebra_map R S) N (λ c, x₁ * c = x₂ * c)).symm, dsimp only at e₁ e₂ ⊢, suffices : algebra_map R T (y₁ * s₂) = algebra_map R T (y₂ * s₁) ↔ ∃ (a : N), algebra_map R S (a * (y₁ * s₂)) = algebra_map R S (a * (y₂ * s₁)), { have h₁ := (is_localization.map_units T ⟨_, h s₁.prop⟩).mul_left_inj, have h₂ := (is_localization.map_units T ⟨_, h s₂.prop⟩).mul_left_inj, simp only [is_scalar_tower.algebra_map_apply R S T, subtype.coe_mk] at h₁ h₂, simp only [is_scalar_tower.algebra_map_apply R S T, map_mul, ← e₁, ← e₂, ← mul_assoc, mul_right_comm _ (algebra_map R S s₂), mul_right_comm _ (algebra_map S T (algebra_map R S s₂)), (is_localization.map_units S s₁).mul_left_inj, (is_localization.map_units S s₂).mul_left_inj] at this, rw [h₂, h₁] at this, simpa only [mul_comm] using this }, simp_rw [is_localization.eq_iff_exists N T, is_localization.eq_iff_exists M S], split, { rintro ⟨a, e⟩, exact ⟨a, 1, by { convert e using 1; simp; ring }⟩ }, { rintro ⟨a, b, e⟩, exact ⟨a * (⟨_, h b.prop⟩ : N), by { convert e using 1; simp; ring }⟩ } end } /-- If `M ≤ N` are submonoids of `R` such that `∀ x : N, ∃ m : R, m * x ∈ M`, then the localization at `N` is equal to the localizaton of `M`. -/ lemma is_localization_of_is_exists_mul_mem (M N : submonoid R) [is_localization M S] (h : M ≤ N) (h' : ∀ x : N, ∃ m : R, m * x ∈ M) : is_localization N S := { map_units := λ y, begin obtain ⟨m, hm⟩ := h' y, have := is_localization.map_units S ⟨_, hm⟩, erw map_mul at this, exact (is_unit.mul_iff.mp this).2 end, surj := λ z, by { obtain ⟨⟨y, s⟩, e⟩ := is_localization.surj M z, exact ⟨⟨y, _, h s.prop⟩, e⟩ }, eq_iff_exists := λ x₁ x₂, begin rw is_localization.eq_iff_exists M, refine ⟨λ ⟨x, hx⟩, ⟨⟨_, h x.prop⟩, hx⟩, _⟩, rintros ⟨x, h⟩, obtain ⟨m, hm⟩ := h' x, refine ⟨⟨_, hm⟩, _⟩, simp [mul_comm m, ← mul_assoc, h] end } end localization_localization end is_localization namespace is_fraction_ring open is_localization variable (M) lemma is_fraction_ring_of_is_localization (S T : Type*) [comm_ring S] [comm_ring T] [algebra R S] [algebra R T] [algebra S T] [is_scalar_tower R S T] [is_localization M S] [is_fraction_ring R T] (hM : M ≤ non_zero_divisors R) : is_fraction_ring S T := begin have := is_localization_of_submonoid_le S T M (non_zero_divisors R) _, refine @@is_localization_of_is_exists_mul_mem _ _ _ _ _ _ this _ _, { exact map_non_zero_divisors_le M S }, { rintro ⟨x, hx⟩, obtain ⟨⟨y, s⟩, e⟩ := is_localization.surj M x, use algebra_map R S s, rw [mul_comm, subtype.coe_mk, e], refine set.mem_image_of_mem (algebra_map R S) _, intros z hz, apply is_localization.injective S hM, rw map_zero, apply hx, rw [← (map_units S s).mul_left_inj, mul_assoc, e, ← map_mul, hz, map_zero, zero_mul] }, { exact hM } end lemma is_fraction_ring_of_is_domain_of_is_localization [is_domain R] (S T : Type*) [comm_ring S] [comm_ring T] [algebra R S] [algebra R T] [algebra S T] [is_scalar_tower R S T] [is_localization M S] [is_fraction_ring R T] : is_fraction_ring S T := begin haveI := is_fraction_ring.nontrivial R T, haveI := (algebra_map S T).domain_nontrivial, apply is_fraction_ring_of_is_localization M S T, intros x hx, rw mem_non_zero_divisors_iff_ne_zero, intro hx', apply @zero_ne_one S, rw [← (algebra_map R S).map_one, ← @mk'_one R _ M, @comm _ eq, mk'_eq_zero_iff], exact ⟨⟨_, hx⟩, (one_mul x).symm ▸ hx'⟩, end end is_fraction_ring
93d81d115f0c6d49dfe732b4d855ff23ef0b6f25
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/limits/shapes/finite_products.lean
d4d7739c671f59a7323a20e32cff7d462671e7af
[ "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
2,672
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_limits import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal /-! # Categories with finite (co)products Typeclasses representing categories with (co)products over finite indexing types. -/ universes v u open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category has finite products if there is a chosen limit for every diagram with shape `discrete J`, where we have `[decidable_eq J]` and `[fintype J]`. -/ -- We can't simply make this an abbreviation, as we do with other `has_Xs` limits typeclasses, -- because of https://github.com/leanprover-community/lean/issues/429 class has_finite_products : Prop := (out (J : Type v) [decidable_eq J] [fintype J] : has_limits_of_shape (discrete J) C) instance has_limits_of_shape_discrete (J : Type v) [fintype J] [has_finite_products C] : has_limits_of_shape (discrete J) C := by { haveI := @has_finite_products.out C _ _ J (classical.dec_eq _), apply_instance } /-- If `C` has finite limits then it has finite products. -/ @[priority 10] instance has_finite_products_of_has_finite_limits [has_finite_limits C] : has_finite_products C := ⟨λ J 𝒥₁ 𝒥₂, by { resetI, apply_instance }⟩ /-- If a category has all products then in particular it has finite products. -/ lemma has_finite_products_of_has_products [has_products C] : has_finite_products C := ⟨by apply_instance⟩ /-- A category has finite coproducts if there is a chosen colimit for every diagram with shape `discrete J`, where we have `[decidable_eq J]` and `[fintype J]`. -/ class has_finite_coproducts : Prop := (out (J : Type v) [decidable_eq J] [fintype J] : has_colimits_of_shape (discrete J) C) attribute [class] has_finite_coproducts instance has_colimits_of_shape_discrete (J : Type v) [fintype J] [has_finite_coproducts C] : has_colimits_of_shape (discrete J) C := by { haveI := @has_finite_coproducts.out C _ _ J (classical.dec_eq _), apply_instance } /-- If `C` has finite colimits then it has finite coproducts. -/ @[priority 10] instance has_finite_coproducts_of_has_finite_colimits [has_finite_colimits C] : has_finite_coproducts C := ⟨λ J 𝒥₁ 𝒥₂, by { resetI, apply_instance }⟩ /-- If a category has all coproducts then in particular it has finite coproducts. -/ lemma has_finite_coproducts_of_has_coproducts [has_coproducts C] : has_finite_coproducts C := ⟨by apply_instance⟩ end category_theory.limits
865120688cfd53092c694ab25154ceab5d980ead
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/padics/padic_rationals.lean
5e478471c30932e439ee91c8bd2fd5305f36ea22
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
20,546
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Define the p-adic numbers (rationals) ℚ_p as the completion of ℚ wrt the p-adic norm. Show that the p-adic norm extends to ℚ_p, that ℚ is embedded in ℚ_p, and that ℚ_p is complete -/ import data.real.cau_seq_completion data.padics.padic_norm algebra.archimedean noncomputable theory local attribute [instance] classical.prop_decidable open nat padic_val padic_norm cau_seq cau_seq.completion @[reducible] def padic_seq {p : ℕ} (hp : prime p) := cau_seq _ (padic_norm hp) namespace padic_seq section variables {p : ℕ} {hp : prime p} lemma stationary {f : cau_seq ℚ (padic_norm hp)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, m ≥ N → n ≥ N → padic_norm hp (f n) = padic_norm hp (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm hp (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this in have ∃ N2, ∀ i j ≥ N2, padic_norm hp (f i - f j) < ε, from cau_seq.cauchy₂ f hε, let ⟨N2, hN2⟩ := this in ⟨ max N1 N2, λ n m hn hm, have padic_norm hp (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm hp (f n - f m) < padic_norm hp (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm hp (f n - f m) < max (padic_norm hp (f n)) (padic_norm hp (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg hp (f m) at hne, have hnam := add_eq_max_of_ne hp hne, rw [padic_norm.neg, max_comm] at hnam, rw ←hnam at this, apply _root_.lt_irrefl _ (by simp at this; exact this) end ⟩ def stationary_point {f : padic_seq hp} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq hp} (hf : ¬ f ≈ 0) : ∀ {m n}, m ≥ stationary_point hf → n ≥ stationary_point hf → padic_norm hp (f n) = padic_norm hp (f m) := classical.some_spec $ stationary hf def norm (f : padic_seq hp) : ℚ := if hf : f ≈ 0 then 0 else padic_norm hp (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq hp) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} {hp : prime p} lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq hp} (h : ∀ k, padic_norm hp (f k) = padic_norm hp (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq hp} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq hp} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm hp k ∧ k ≠ 0 := have heq : f.norm = padic_norm hp (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm hp) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm hp) q) ≈ 0 := λ h : lim_zero (const (padic_norm hp) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq hp) : f.norm ≥ 0 := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] lemma norm_mul (f g : padic_seq hp) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, let i := max (stationary_point hfg) (max (stationary_point hf) (stationary_point hg)) in have hpnfg : padic_norm hp ((f * g) (stationary_point hfg)) = padic_norm hp ((f * g) i), { apply stationary_point_spec hfg, apply le_max_left, apply le_refl }, have hpnf : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i), { apply stationary_point_spec hf, apply ge_trans, apply le_max_right, apply le_max_left, apply le_refl }, have hpng : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i), { apply stationary_point_spec hg, apply ge_trans, apply le_max_right, apply le_max_right, apply le_refl }, begin unfold norm, split_ifs, rw [hpnfg, hpnf, hpng], apply padic_norm.mul hp end lemma eq_zero_iff_equiv_zero (f : padic_seq hp) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq hp) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm hp) q) = padic_norm hp q := if hq : q = 0 then have (const (padic_norm hp) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm hp) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm hp) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_image (a : padic_seq hp) (ha : ¬ a ≈ 0) : (∃ (n : ℤ), a.norm = fpow ↑p (-n)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.image hp hk' lemma norm_one : norm (1 : padic_seq hp) = 1 := have h1 : ¬ (1 : padic_seq hp) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.gt_one] private lemma norm_eq_of_equiv_aux {f g : padic_seq hp} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm hp (f (stationary_point hf)) ≠ padic_norm hp (g (stationary_point hg))) (hgt : padic_norm hp (f (stationary_point hf)) > padic_norm hp (g (stationary_point hg))) : false := begin have hpn : padic_norm hp (f (stationary_point hf)) - padic_norm hp (g (stationary_point hg)) > 0, from sub_pos_of_lt hgt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hfi : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i), { apply stationary_point_spec hf, { apply le_trans, apply le_max_left, tactic.rotate_left 1, apply le_max_right }, { apply le_refl } }, have hgi : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i), { apply stationary_point_spec hg, { apply le_trans, apply le_max_right, tactic.rotate_left 1, apply le_max_right }, { apply le_refl } }, have hi : i ≥ N, from le_max_left _ _, have hN' := hN _ hi, simp only [hfi, hgi] at hN', have hpne : padic_norm hp (f i) ≠ padic_norm hp (-(g i)), by rwa [hfi, hgi, ←padic_norm.neg hp (g i)] at h, let hpnem := add_eq_max_of_ne hp hpne, have hpeq : padic_norm hp ((f - g) i) = max (padic_norm hp (f i)) (padic_norm hp (g i)), { rwa padic_norm.neg at hpnem }, have hfigi : padic_norm hp (g i) < padic_norm hp (f i), { rwa [hfi, hgi] at hgt }, rw [hpeq, max_eq_left_of_lt hfigi] at hN', have : padic_norm hp (f i) < padic_norm hp (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq hp} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm hp (f (stationary_point hf)) = padic_norm hp (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm hp (f (stationary_point hf)) > padic_norm hp (g (stationary_point hg)))) with hgt hngt, { exact norm_eq_of_equiv_aux hf hg hfg h hgt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hngt, apply h } end theorem norm_equiv {f g : padic_seq hp} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq hp} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := let i := max (stationary_point hfg) (max (stationary_point hf) (stationary_point hg)) in have hpnfg : padic_norm hp ((f + g) (stationary_point hfg)) = padic_norm hp ((f + g) i), { apply stationary_point_spec hfg, apply le_max_left, apply le_refl }, have hpnf : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i), { apply stationary_point_spec hf, apply ge_trans, apply le_max_right, apply le_max_left, apply le_refl }, have hpng : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i), { apply stationary_point_spec hg, apply ge_trans, apply le_max_right, apply le_max_right, apply le_refl }, begin unfold norm, split_ifs, rw [hpnfg, hpnf, hpng], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq hp) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq hp} (h : ∀ k, padic_norm hp (f k) = padic_norm hp (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq hp) : (-a).norm = a.norm := norm_eq $ by simp end embedding end padic_seq def padic {p : ℕ} (hp : prime p) := @Cauchy _ _ _ _ (padic_norm hp) _ notation `ℚ_[` hp `]` := padic hp namespace padic section completion variables {p : ℕ} {hp : prime p} instance discrete_field : discrete_field (padic hp) := cau_seq.completion.discrete_field def mk : padic_seq hp → ℚ_[hp] := quotient.mk end completion section completion variables {p : ℕ} (hp : prime p) lemma mk_eq {f g : padic_seq hp} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat : ℚ → ℚ_[hp] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat hp (x + y) = of_rat hp x + of_rat hp y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat hp (-x) = -of_rat hp x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat hp (x * y) = of_rat hp x * of_rat hp y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat hp (x - y) = of_rat hp x - of_rat hp y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat hp (x / y) = of_rat hp x / of_rat hp y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat hp 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat hp 0 = 0 := rfl @[simp] lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[hp]) = of_rat hp n := begin induction n with n ih, { refl }, { simp, ring, congr, apply ih } end @[simp] lemma cast_eq_of_rat_of_int (n : ℤ) : (↑n : ℚ_[hp]) = of_rat hp n := by induction n; simp lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[hp]) = of_rat hp q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom _, by simp [this, rat.mk_eq_div, of_rat_div] lemma const_equiv {q r : ℚ} : const (padic_norm hp) q ≈ const (padic_norm hp) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm hp) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat hp q = of_rat hp r ↔ q = r := ⟨(const_equiv hp).1 ∘ quotient.eq.1, λ h, by rw h⟩ instance : char_zero ℚ_[hp] := ⟨ λ m n, suffices of_rat hp ↑m = of_rat hp ↑n ↔ m = n, by simpa, by simp [of_rat_eq] ⟩ end completion end padic def padic_norm_e {p : ℕ} {hp : prime p} : ℚ_[hp] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} {hp : prime p} lemma defn (f : padic_seq hp) {ε : ℚ} (hε : ε > 0) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, (f - const _ (f i)).norm ≥ ε, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm hp) (f i)) ≈ 0, { intro h, unfold norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em ((stationary_point hne) ≥ N) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[hp]) : padic_norm_e q ≥ 0 := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[hp]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[hp]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[hp]) = 0 := (zero_iff _).2 rfl @[simp] protected lemma one : padic_norm_e (1 : ℚ_[hp]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[hp]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg theorem nonarchimedean (q r : ℚ_[hp]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean protected lemma add (q r : ℚ_[hp]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul (q r : ℚ_[hp]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e _ hp) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul } lemma eq_padic_norm (q : ℚ) : padic_norm_e (padic.of_rat hp q) = padic_norm hp q := norm_const _ protected theorem image {q : ℚ_[hp]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = fpow p (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_image f this lemma sub_rev (q r : ℚ_[hp]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense {p : ℕ} {hp : prime p} (q : ℚ_[hp]) {ε : ℚ} (hε : ε > 0) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm hp (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm hp) (q' N)) ≈ 0) with heq hne', { simpa only [heq, norm, dif_pos] }, { simp only [norm, dif_neg hne'], change padic_norm hp (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (N ≥ stationary_point hne') with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} {hp : prime p} (f : cau_seq _ (@padic_norm_e _ hp)) open classical private lemma cast_succ_nat_pos (n : ℕ) : (↑(n + 1) : ℚ) > 0 := nat.cast_pos.2 $ succ_pos _ private lemma div_nat_pos (n : ℕ) : (1 / ((n + 1): ℚ)) > 0 := div_pos zero_lt_one (cast_succ_nat_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - of_rat hp ((lim_seq f) i)) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense (f i) (div_nat_pos i)), rw ← cast_eq_of_rat, refine lt_of_lt_of_le h (div_le_of_le_mul (cast_succ_nat_pos _) _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact le_mul_of_div_le hε (le_trans (le_of_lt hN) (nat.cast_le.2 hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm hp) (lim_seq f) := assume ε hε, have hε3 : ε / 3 > 0, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, rw [←padic_norm_e.eq_padic_norm, padic.of_rat_sub], suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, simpa only [cast_eq_of_rat] }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { apply eq_of_mul_eq_mul_left this, simp [left_distrib, mul_div_cancel' _ this ], ring }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa, apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hj }, { apply hN2, apply le_of_max_le_right hj, apply le_max_right } } }, { rw cast_eq_of_rat, apply hN, apply le_max_left }}} end private def lim' : padic_seq hp := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[hp] := ⟦lim' f⟧ theorem complete : ∃ q : ℚ_[hp], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show ε / 2 > 0, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show ε / 2 > 0, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (2 : ℚ) ≠ 0, by norm_num, have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, apply le_of_max_le_right hi }, { rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hi } } } end ⟩ end complete end padic
1af07e8cf7687000e3d4bb83516c3dff8e66a8fa
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/compiler/expr.lean
da915526c00825608df8e903bd8fbbeeb6dc17c9
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
195
lean
import init.lean.expr open Lean def main : IO UInt32 := let e := Expr.app (Expr.const `f []) (Expr.const `a []) in IO.println e.dbgToString *> IO.println ("hash: " ++ toString e.hash) *> pure 0
deb08841e7a35a61aef16164ee3693611ae87473
d53312f14e4be505a8abcc1969b73308b038f020
/06-formalizacija-dokazov/vaje.lean
ef8f285712d709c8b30b5637f98dd70f6556946a
[]
no_license
lunar-starlight/teorija-programskih-jezikov
18ccdfaa9200c10c2b1ec14624419532dd671d25
bfdf69114a6b13b1ae5735e8749b543f722e5965
refs/heads/master
1,667,393,466,506
1,577,651,158,000
1,577,651,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,413
lean
namespace hidden universe u ------------------------------------------------------------------------------- inductive list (A:Type) : Type | Nil {} : list -- Brez {} moramo konstruktorju Nil vedno podati tip A | Cons : A -> list -> list -- Cons tip A ugotovi iz tipa prvega elementa namespace list -- Dopolnite definicije in dokažitve trditve za sezname iz vaj 3. -- Uporabljate -- lahko notacijo x :: xs, [] in ++ (namesto @), -- vendar bodite pozorni na oklepaje. notation x `::` xs := Cons x xs notation `[]` := Nil def join {A} : list A -> list A -> list A | [] ys := ys | (x::xs) ys := x :: join xs ys notation xs `++` ys := join xs ys theorem join_nil {A} (xs: list A) : xs ++ [] = xs := begin induction xs, case Nil {unfold join}, case Cons { unfold join, rewrite xs_ih, }, end def reverse {A} : list A -> list A | [] := [] | (x::xs) := (reverse xs) ++ (x::[]) theorem join_asoc {A} (xs ys zs : list A) : (xs ++ ys) ++ zs = xs ++ (ys ++ zs) := begin induction xs, all_goals {unfold join}, rewrite xs_ih, end theorem rev_join {A} (xs ys : list A) : reverse (xs ++ ys) = (reverse ys) ++ (reverse xs) := begin induction xs, case Nil {unfold reverse, unfold join, rewrite join_nil}, case Cons { unfold join, unfold reverse, rewrite xs_ih, apply join_asoc, } end theorem rev_invol {A} (xs : list A) : reverse (reverse xs) = xs := begin induction xs, unfold reverse, unfold reverse, rewrite rev_join, rewrite xs_ih, unfold reverse, unfold join, end end list ------------------------------------------------------------------------------- -- Podobno kot za sezname, napišite tip za drevesa in dokažite trditve iz -- vaj 3. Če po definiciji tipa `tree` odprete `namespace tree` lahko -- uporabljate konstruktorje brez predpone, torej `Empty` namesto -- `tree.Empty`. inductive tree (A:Type) : Type | Empty {} : tree | Node : tree -> A -> tree -> tree namespace tree def mirror {A}: tree A -> tree A | Empty := Empty | (Node lt x rt) := Node (mirror rt) x (mirror lt) theorem mirror_invol {A} (t : tree A) : mirror (mirror t) = t := begin induction t, unfold mirror, unfold mirror, rewrite [t_ih_a, t_ih_a_1], end def tree_map {A B : Type} (f : A -> B) : tree A -> tree B | Empty := Empty | (Node lt x rt) := Node (tree_map lt) (f x) (tree_map rt) theorem mirror_map_comm {A B} (t : tree A) (f : A -> B) : tree_map f (mirror t) = mirror (tree_map f t) := begin induction t, {unfold mirror, unfold tree_map, unfold mirror}, case Node { unfold mirror, unfold tree_map, rewrite [t_ih_a, t_ih_a_1], unfold mirror, } end def depth {A} (t : tree A) : tree A -> nat | Empty := 0 | (Node lt x rt) := 1 + max (depth lt) (depth rt) end tree ------------------------------------------------------------------------------- -- Definirajte nekaj konstruktov jezika IMP. inductive loc : Type | Loc : int -> loc -- Ker v IMPu ločimo med različnimi vrstami termov, definiramo tip vrst inductive of : Type | AExp | BExp | Comm namespace of -- Tip 'term' sprejme še vrsto terma. Ukazi so tako tipa `term Comm`. inductive tm : of -> Type | Int : int -> tm AExp | Plus : int -> int -> tm AExp | Bool : bool -> tm BExp | Eq : tm AExp -> tm AExp -> tm BExp | Update : loc -> tm AExp -> tm Comm theorem bullshit (t1 t2 : tm AExp) : t1 = t2 := begin cases t1, cases t2, end end of end hidden
26a6ba42e7511cb5931ba83b534e18214cc6a35f
cc4e32129597fc42f4ac133f6eef3dbfd3d16218
/Analysis/Logic.lean
63bba7bc33b8326c220719f30937532e4ea1ecbe
[]
no_license
JasonKYi/analysis_in_lean4
9791c76ab5f9408731acca075cf604ef4700b117
280d45bf2fc9c2f599b365a60a4b980bb2721c24
refs/heads/main
1,683,375,225,248
1,622,048,948,000
1,622,048,948,000
370,429,249
0
0
null
null
null
null
UTF-8
Lean
false
false
1,883
lean
theorem impNot {p q : Prop} : p → ¬ q ↔ ¬ (p ∧ q) := ⟨ λ hpq h => hpq h.1 h.2, λ h hp hq => h <| And.intro hp hq ⟩ theorem Exists.impNot {p q : α → Prop} : (∃ x, p x → ¬ q x) ↔ ∃ x, ¬ (p x ∧ q x) := by apply Iff.intro intro h cases h with | intro x hx => { exact ⟨ x, λ hs => hx hs.1 hs.2 ⟩ } intro h cases h with | intro x hx => { exact ⟨ x, λ hpx hqx => hx <| And.intro hpx hqx ⟩ } namespace Classical theorem contrapositive {p q : Prop} : (¬ q → ¬ p) → p → q := λ hqp hp => match em q with | Or.inl h => h | Or.inr h => False.elim <| hqp h hp theorem notNot {p : Prop} : ¬ ¬ p ↔ p := by apply Iff.intro { intro hp; cases em p with | inl => assumption | inr h => exact False.elim <| hp h } { exact λ hp hnp => False.elim <| hnp hp } theorem notForall {p : α → Prop} : (¬ ∀ x, p x) → ∃ x, ¬ p x := by { apply contrapositive; intro hx; rw [notNot]; intro x; cases em (p x); { assumption } { apply False.elim <| hx <| Exists.intro x _; assumption } } theorem notAnd {p q : Prop} : p ∧ ¬ q ↔ ¬ (p → q) := by apply Iff.intro { exact λ h himp => h.2 <| himp h.1 } { intro h; apply And.intro; { revert h; apply contrapositive; rw [notNot]; exact λ hnp hp => False.elim <| hnp hp } { exact λ hq => h <| λ _ => hq } } theorem Exists.notAnd {p q : α → Prop} : (∃ x, p x ∧ ¬ q x) ↔ ∃ x, ¬ (p x → q x) := by apply Iff.intro { intro h; let ⟨ x, ⟨ hp, hnq ⟩ ⟩ := h; exact Exists.intro x λ h => hnq <| h hp } { intro h; let ⟨ x, hx ⟩ := h; apply Exists.intro x; apply And.intro; { revert hx; apply contrapositive; exact λ hpx hpq => hpq λ hp => False.elim <| hpx hp } { intro foo; apply hx; intro bar; assumption; } } end Classical
ed9f20eb6eb3dfcf22ade1ad4bc28f2bf0a204da
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/control/functor.lean
d9bfdfd9ca1c7e49fa3364ac4abc2434007ec54e
[ "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,673
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.ext import tactic.lint /-! # Functors This module provides additional lemmas, definitions, and instances for `functor`s. ## Main definitions * `const α` is the functor that sends all types to `α`. * `add_const α` is `const α` but for when `α` has an additive structure. * `comp F G` for functors `F` and `G` is the functor composition of `F` and `G`. * `liftp` and `liftr` respectively lift predicates and relations on a type `α` to `F α`. Terms of `F α` are considered to, in some sense, contain values of type `α`. ## Tags functor, applicative -/ attribute [functor_norm] seq_assoc pure_seq_eq_map map_pure seq_map_assoc map_seq universe variables u v w section functor variables {F : Type u → Type v} variables {α β γ : Type u} variables [functor F] [is_lawful_functor F] lemma functor.map_id : (<$>) id = (id : F α → F α) := by apply funext; apply id_map lemma functor.map_comp_map (f : α → β) (g : β → γ) : ((<$>) g ∘ (<$>) f : F α → F γ) = (<$>) (g ∘ f) := by apply funext; intro; rw comp_map theorem functor.ext {F} : ∀ {F1 : functor F} {F2 : functor F} [@is_lawful_functor F F1] [@is_lawful_functor F F2] (H : ∀ α β (f : α → β) (x : F α), @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x), F1 = F2 | ⟨m, mc⟩ ⟨m', mc'⟩ H1 H2 H := begin cases show @m = @m', by funext α β f x; apply H, congr, funext α β, have E1 := @map_const_eq _ ⟨@m, @mc⟩ H1, have E2 := @map_const_eq _ ⟨@m, @mc'⟩ H2, exact E1.trans E2.symm end end functor /-- Introduce the `id` functor. Incidentally, this is `pure` for `id` as a `monad` and as an `applicative` functor. -/ def id.mk {α : Sort u} : α → id α := id namespace functor /-- `const α` is the constant functor, mapping every type to `α`. When `α` has a monoid structure, `const α` has an `applicative` instance. (If `α` has an additive monoid structure, see `functor.add_const`.) -/ @[nolint unused_arguments] def const (α : Type*) (β : Type*) := α /-- `const.mk` is the canonical map `α → const α β` (the identity), and it can be used as a pattern to extract this value. -/ @[pattern] def const.mk {α β} (x : α) : const α β := x /-- `const.mk'` is `const.mk` but specialized to map `α` to `const α punit`, where `punit` is the terminal object in `Type*`. -/ def const.mk' {α} (x : α) : const α punit := x /-- Extract the element of `α` from the `const` functor. -/ def const.run {α β} (x : const α β) : α := x namespace const protected lemma ext {α β} {x y : const α β} (h : x.run = y.run) : x = y := h /-- The map operation of the `const γ` functor. -/ @[nolint unused_arguments] protected def map {γ α β} (f : α → β) (x : const γ β) : const γ α := x instance {γ} : functor (const γ) := { map := @const.map γ } instance {γ} : is_lawful_functor (const γ) := by constructor; intros; refl instance {α β} [inhabited α] : inhabited (const α β) := ⟨(default _ : α)⟩ end const /-- `add_const α` is a synonym for constant functor `const α`, mapping every type to `α`. When `α` has a additive monoid structure, `add_const α` has an `applicative` instance. (If `α` has a multiplicative monoid structure, see `functor.const`.) -/ def add_const (α : Type*) := const α /-- `add_const.mk` is the canonical map `α → add_const α β`, which is the identity, where `add_const α β = const α β`. It can be used as a pattern to extract this value. -/ @[pattern] def add_const.mk {α β} (x : α) : add_const α β := x /-- Extract the element of `α` from the constant functor. -/ def add_const.run {α β} : add_const α β → α := id instance add_const.functor {γ} : functor (add_const γ) := @const.functor γ instance add_const.is_lawful_functor {γ} : is_lawful_functor (add_const γ) := @const.is_lawful_functor γ instance {α β} [inhabited α] : inhabited (add_const α β) := ⟨(default _ : α)⟩ /-- `functor.comp` is a wrapper around `function.comp` for types. It prevents Lean's type class resolution mechanism from trying a `functor (comp F id)` when `functor F` would do. -/ def comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w := F $ G α /-- Construct a term of `comp F G α` from a term of `F (G α)`, which is the same type. Can be used as a pattern to extract a term of `F (G α)`. -/ @[pattern] def comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : comp F G α := x /-- Extract a term of `F (G α)` from a term of `comp F G α`, which is the same type. -/ def comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : comp F G α) : F (G α) := x namespace comp variables {F : Type u → Type w} {G : Type v → Type u} protected lemma ext {α} {x y : comp F G α} : x.run = y.run → x = y := id instance {α} [inhabited (F (G α))] : inhabited (comp F G α) := ⟨(default _ : F (G α))⟩ variables [functor F] [functor G] /-- The map operation for the composition `comp F G` of functors `F` and `G`. -/ protected def map {α β : Type v} (h : α → β) : comp F G α → comp F G β | (comp.mk x) := comp.mk ((<$>) h <$> x) instance : functor (comp F G) := { map := @comp.map F G _ _ } @[functor_norm] lemma map_mk {α β} (h : α → β) (x : F (G α)) : h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl @[simp] protected lemma run_map {α β} (h : α → β) (x : comp F G α) : (h <$> x).run = (<$>) h <$> x.run := rfl variables [is_lawful_functor F] [is_lawful_functor G] variables {α β γ : Type v} protected lemma id_map : ∀ (x : comp F G α), comp.map id x = x | (comp.mk x) := by simp [comp.map, functor.map_id] protected lemma comp_map (g' : α → β) (h : β → γ) : ∀ (x : comp F G α), comp.map (h ∘ g') x = comp.map h (comp.map g' x) | (comp.mk x) := by simp [comp.map, functor.map_comp_map g' h] with functor_norm instance : is_lawful_functor (comp F G) := { id_map := @comp.id_map F G _ _ _ _, comp_map := @comp.comp_map F G _ _ _ _ } theorem functor_comp_id {F} [AF : functor F] [is_lawful_functor F] : @comp.functor F id _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor F id _ _ _ _) _ (λ α β f x, rfl) theorem functor_id_comp {F} [AF : functor F] [is_lawful_functor F] : @comp.functor id F _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor id F _ _ _ _) _ (λ α β f x, rfl) end comp namespace comp open function (hiding comp) open functor variables {F : Type u → Type w} {G : Type v → Type u} variables [applicative F] [applicative G] /-- The `<*>` operation for the composition of applicative functors. -/ protected def seq {α β : Type v} : comp F G (α → β) → comp F G α → comp F G β | (comp.mk f) (comp.mk x) := comp.mk $ (<*>) <$> f <*> x instance : has_pure (comp F G) := ⟨λ _ x, comp.mk $ pure $ pure x⟩ instance : has_seq (comp F G) := ⟨λ _ _ f x, comp.seq f x⟩ @[simp] protected lemma run_pure {α : Type v} : ∀ x : α, (pure x : comp F G α).run = pure (pure x) | _ := rfl @[simp] protected lemma run_seq {α β : Type v} (f : comp F G (α → β)) (x : comp F G α) : (f <*> x).run = (<*>) <$> f.run <*> x.run := rfl instance : applicative (comp F G) := { map := @comp.map F G _ _, seq := @comp.seq F G _ _, ..comp.has_pure } end comp variables {F : Type u → Type u} [functor F] /-- If we consider `x : F α` to, in some sense, contain values of type `α`, predicate `liftp p x` holds iff every value contained by `x` satisfies `p`. -/ def liftp {α : Type u} (p : α → Prop) (x : F α) : Prop := ∃ u : F (subtype p), subtype.val <$> u = x /-- If we consider `x : F α` to, in some sense, contain values of type `α`, then `liftr r x y` relates `x` and `y` iff (1) `x` and `y` have the same shape and (2) we can pair values `a` from `x` and `b` from `y` so that `r a b` holds. -/ def liftr {α : Type u} (r : α → α → Prop) (x y : F α) : Prop := ∃ u : F {p : α × α // r p.fst p.snd}, (λ t : {p : α × α // r p.fst p.snd}, t.val.fst) <$> u = x ∧ (λ t : {p : α × α // r p.fst p.snd}, t.val.snd) <$> u = y /-- If we consider `x : F α` to, in some sense, contain values of type `α`, then `supp x` is the set of values of type `α` that `x` contains. -/ def supp {α : Type u} (x : F α) : set α := { y : α | ∀ ⦃p⦄, liftp p x → p y } theorem of_mem_supp {α : Type u} {x : F α} {p : α → Prop} (h : liftp p x) : ∀ y ∈ supp x, p y := λ y hy, hy h end functor
ad23f0e199a3751c498b60d0cd1dab758c74b7ca
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/array1.lean
c6544ffb80f84d53a33b0c3053cd68c878ab371f
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,257
lean
#check @Array.mk def v : Array Nat := Array.mk [1, 2, 3, 4] def w : Array Nat := (mkArray 9 1).push 3 #check @Array.casesOn def f : Fin w.size → Nat := w.get def arraySum (a : Array Nat) : Nat := a.foldl Nat.add 0 #eval mkArray 4 1 #eval Array.map (fun x => x+10) v #eval f ⟨1, sorry⟩ #eval f ⟨9, sorry⟩ #eval (((mkArray 1 1).push 2).push 3).foldl (fun x y => x + y) 0 #eval arraySum (mkArray 10 1) axiom axLt {a b : Nat} : a < b #eval #[1, 2, 3].insertAt 0 10 #eval #[1, 2, 3].insertAt 1 10 #eval #[1, 2, 3].insertAt 2 10 #eval #[1, 2, 3].insertAt 3 10 #eval #[].insertAt 0 10 def tst1 : IO Unit := #[1, 2, 3, 4].forRevM IO.println #eval tst1 #eval #[1, 2].extract 0 1 #eval #[1, 2].extract 0 0 #eval #[1, 2].extract 0 2 #eval #[1, 2, 3, 4].filterMap fun x => if x % 2 == 0 then some (x + 10) else none def tst : IO (List Nat) := [1, 2, 3, 4].filterMapM fun x => do IO.println x; (if x % 2 == 0 then pure $ some (x + 10) else pure none) #eval tst #eval #[1, 3, 6, 2].getMax? (fun a b => a < b) #eval #[].getMax? (fun (a b : Nat) => a < b) #eval #[1, 8].getMax? (fun a b => a < b) #eval #[8, 1].getMax? (fun a b => a < b) #eval #[1, 6, 5, 3, 8, 2, 0].partition fun x => x % 2 == 0 def check (b : Bool) : IO Unit := «unless» b $ throw $ IO.userError "check failed" #eval check $ #[].isPrefixOf #[2, 3] #eval check $ (#[] : Array Nat).isPrefixOf #[] #eval check $ #[2, 3].isPrefixOf #[2, 3] #eval check $ #[2, 3].isPrefixOf #[2, 3, 4, 5] #eval check $ ! #[2, 4].isPrefixOf #[2, 3] #eval check $ ! #[2, 3, 4].isPrefixOf #[2, 3] #eval check $ ! #[2].isPrefixOf #[] #eval check $ ! #[4, 3].isPrefixOf #[2, 3, 4, 5] #eval check $ #[1, 2, 3].allDiff #eval check $ !#[1, 2, 1, 3].allDiff #eval check $ #[1, 2, 4, 3].allDiff #eval check $ (#[] : Array Nat).allDiff #eval check $ !#[1, 1].allDiff #eval check $ !#[1, 2, 3, 4, 5, 1].allDiff #eval check $ #[1, 2, 3, 4, 5].allDiff #eval check $ !#[1, 2, 3, 4, 5, 5].allDiff #eval check $ !#[1, 3, 3, 4, 5].allDiff #eval check $ !#[1, 2, 3, 4, 5, 3].allDiff #eval check $ !#[1, 2, 3, 4, 5, 4].allDiff #eval check $ #[1, 2, 3, 4, 5, 6].allDiff #eval check $ Array.zip #[1, 2] #[3, 4, 6] == #[(1, 3), (2, 4)] theorem ex1 (a b c : Nat) : #[a, b].push c = #[a, 0, c].set! 1 b := rfl
2369c994a8839e326d9d406033ea5fb30e4325d9
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/functorial.lean
c2016e7ca6ae04aa61b50c478ad16631a4004365
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
2,295
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.functor /-! # Unbundled functors, as a typeclass decorating the object-level function. -/ namespace category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- A unbundled functor. -/ -- Perhaps in the future we could redefine `functor` in terms of this, but that isn't the -- immediate plan. class functorial (F : C → D) : Type (max v₁ v₂ u₁ u₂) := (map : Π {X Y : C}, (X ⟶ Y) → ((F X) ⟶ (F Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (F X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) restate_axiom functorial.map_id' attribute [simp] functorial.map_id restate_axiom functorial.map_comp' attribute [simp] functorial.map_comp /-- If `F : C → D` (just a function) has `[functorial F]`, we can write `map F f : F X ⟶ F Y` for the action of `F` on a morphism `f : X ⟶ Y`. -/ def map (F : C → D) [functorial.{v₁ v₂} F] {X Y : C} (f : X ⟶ Y) : F X ⟶ F Y := functorial.map.{v₁ v₂} F f namespace functor /-- Bundle a functorial function as a functor. -/ def of (F : C → D) [I : functorial.{v₁ v₂} F] : C ⥤ D := { obj := F, ..I } end functor instance (F : C ⥤ D) : functorial.{v₁ v₂} (F.obj) := { .. F } @[simp] lemma map_functorial_obj (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : map F.obj f = F.map f := rfl section omit 𝒟 instance functorial_id : functorial.{v₁ v₁} (id : C → C) := { map := λ X Y f, f } end section variables {E : Type u₃} [ℰ : category.{v₃} E] include ℰ /-- `G ∘ F` is a functorial if both `F` and `G` are. -/ -- This is no longer viable as an instance in Lean 3.7, -- #lint reports an instance loop -- Will this be a problem? def functorial_comp (F : C → D) [functorial.{v₁ v₂} F] (G : D → E) [functorial.{v₂ v₃} G] : functorial.{v₁ v₃} (G ∘ F) := { ..(functor.of F ⋙ functor.of G) } end end category_theory
83d12121e9d9330a46abff87152deb39b1d4906e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Common.lean
21a7315bdebe1709096ee286976470fbb4620d4b
[ "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,977
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Build.Monad import Lake.Build.Actions open System namespace Lake /-! # General Utilities -/ @[inline] def inputFile (path : FilePath) : SchedulerM (BuildJob FilePath) := Job.async <| (path, ·) <$> computeTrace path @[inline] def buildUnlessUpToDate [CheckExists ι] [GetMTime ι] (info : ι) (depTrace : BuildTrace) (traceFile : FilePath) (build : JobM PUnit) : JobM PUnit := do let isOldMode ← getIsOldMode let upToDate ← if isOldMode then depTrace.checkAgainstTime info else depTrace.checkAgainstFile info traceFile unless upToDate do build unless isOldMode do depTrace.writeToFile traceFile @[inline] def buildFileUnlessUpToDate (file : FilePath) (depTrace : BuildTrace) (build : BuildM PUnit) : BuildM BuildTrace := do let traceFile := FilePath.mk <| file.toString ++ ".trace" buildUnlessUpToDate file depTrace traceFile build computeTrace file @[inline] def buildFileAfterDep (file : FilePath) (dep : BuildJob α) (build : α → BuildM PUnit) (extraDepTrace : BuildM _ := pure BuildTrace.nil) : SchedulerM (BuildJob FilePath) := dep.bindSync fun depInfo depTrace => do let depTrace := depTrace.mix (← extraDepTrace) let trace ← buildFileUnlessUpToDate file depTrace <| build depInfo return (file, trace) @[inline] def buildFileAfterDepList (file : FilePath) (deps : List (BuildJob α)) (build : List α → BuildM PUnit) (extraDepTrace : BuildM _ := pure BuildTrace.nil) : SchedulerM (BuildJob FilePath) := do buildFileAfterDep file (← BuildJob.collectList deps) build extraDepTrace @[inline] def buildFileAfterDepArray (file : FilePath) (deps : Array (BuildJob α)) (build : Array α → BuildM PUnit) (extraDepTrace : BuildM _ := pure BuildTrace.nil) : SchedulerM (BuildJob FilePath) := do buildFileAfterDep file (← BuildJob.collectArray deps) build extraDepTrace /-! # Common Builds -/ def buildO (name : String) (oFile : FilePath) (srcJob : BuildJob FilePath) (args : Array String := #[]) (compiler : FilePath := "cc") : SchedulerM (BuildJob FilePath) := buildFileAfterDep oFile srcJob (extraDepTrace := computeHash args) fun srcFile => do compileO name oFile srcFile args compiler def buildLeanO (name : String) (oFile : FilePath) (srcJob : BuildJob FilePath) (args : Array String := #[]) : SchedulerM (BuildJob FilePath) := buildFileAfterDep oFile srcJob (extraDepTrace := computeHash args) fun srcFile => do compileO name oFile srcFile args (← getLeanc) def buildStaticLib (libFile : FilePath) (oFileJobs : Array (BuildJob FilePath)) : SchedulerM (BuildJob FilePath) := let name := libFile.fileName.getD libFile.toString buildFileAfterDepArray libFile oFileJobs fun oFiles => do compileStaticLib name libFile oFiles (← getLeanAr) def buildLeanSharedLib (libFile : FilePath) (linkJobs : Array (BuildJob FilePath)) (linkArgs : Array String := #[]) : SchedulerM (BuildJob FilePath) := let name := libFile.fileName.getD libFile.toString buildFileAfterDepArray libFile linkJobs (extraDepTrace := computeHash linkArgs) fun links => do compileSharedLib name libFile (links.map toString ++ linkArgs) (← getLeanc) def buildLeanExe (exeFile : FilePath) (linkJobs : Array (BuildJob FilePath)) (linkArgs : Array String := #[]) : SchedulerM (BuildJob FilePath) := let name := exeFile.fileName.getD exeFile.toString buildFileAfterDepArray exeFile linkJobs (extraDepTrace := computeHash linkArgs) fun links => do compileExe name exeFile links linkArgs (← getLeanc) def buildLeanSharedLibOfStatic (staticLibJob : BuildJob FilePath) (linkArgs : Array String := #[]) : SchedulerM (BuildJob FilePath) := staticLibJob.bindSync fun staticLib staticTrace => do let dynlib := staticLib.withExtension sharedLibExt let baseArgs := if System.Platform.isOSX then #[s!"-Wl,-force_load,{staticLib}"] else #["-Wl,--whole-archive", staticLib.toString, "-Wl,--no-whole-archive"] let args := baseArgs ++ linkArgs let depTrace := staticTrace.mix (← computeHash args) let trace ← buildFileUnlessUpToDate dynlib depTrace do let name := dynlib.fileName.getD dynlib.toString compileSharedLib name dynlib args (← getLeanc) return (dynlib, trace) def computeDynlibOfShared (sharedLibTarget : BuildJob FilePath) : SchedulerM (BuildJob Dynlib) := sharedLibTarget.bindSync fun sharedLib trace => do if let some stem := sharedLib.fileStem then if Platform.isWindows then return ({path := sharedLib, name := stem}, trace) else if stem.startsWith "lib" then return ({path := sharedLib, name := stem.drop 3}, trace) else error s!"shared library `{sharedLib}` does not start with `lib`; this is not supported on Unix" else error s!"shared library `{sharedLib}` has no file name"
6b0f6aecfccba0ff39891acfe2161cb2cbaa3a48
a44280b79dc85615010e3fbda46abf82c6730fa3
/tests/playground/task_test2.lean
a7ed482ef93367f8d8b9162d4d0933ec6e02c413
[ "Apache-2.0" ]
permissive
kodyvajjha/lean4
8e1c613248b531d47367ca6e8d97ee1046645aa1
c8a045d69fac152fd5e3a577f718615cecb9c53d
refs/heads/master
1,589,684,450,102
1,555,200,447,000
1,556,139,945,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
429
lean
def run1 (i : Nat) (n : Nat) (xs : List Nat) : Nat := n.repeat (λ _ r, dbgTrace (">> [" ++ toString i ++ "] " ++ toString r) $ λ _, xs.foldl (+) r) 0 def main (xs : List String) : IO UInt32 := let ys := (List.repeat 1 xs.head.toNat) in let ts : List (Task Nat) := (List.iota 10).map (λ i, Task.mk $ λ _, run1 (i+1) xs.head.toNat ys) in let ns : List Nat := ts.map Task.get in IO.println (">> " ++ toString ns) *> pure 0
74d0db72aaf3e560ad409249158a3751d5c995e5
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Std/Data/HashSet.lean
16f03f7bcf5b173746ddbe3250c5b40bfebe83f2
[ "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
6,065
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Std universes u v w def HashSetBucket (α : Type u) := { b : Array (List α) // b.size > 0 } def HashSetBucket.update {α : Type u} (data : HashSetBucket α) (i : USize) (d : List α) (h : i.toNat < data.val.size) : HashSetBucket α := ⟨ data.val.uset i d h, by erw [Array.sizeSetEq]; exact data.property ⟩ structure HashSetImp (α : Type u) := (size : Nat) (buckets : HashSetBucket α) def mkHashSetImp {α : Type u} (nbuckets := 8) : HashSetImp α := let n := if nbuckets = 0 then 8 else nbuckets { size := 0, buckets := ⟨ mkArray n [], by rw [Array.sizeMkArrayEq]; cases nbuckets; decide!; apply Nat.zeroLtSucc ⟩ } namespace HashSetImp variables {α : Type u} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u %ₙ n, USize.modnLt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashSetBucket α) (a : α) : HashSetBucket α := let ⟨i, h⟩ := mkIdx data.property (hashFn a) data.update i (a :: data.val.uget i h) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashSetBucket α) (d : δ) (f : δ → α → m δ) : m δ := data.val.foldlM (init := d) fun d as => as.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashSetBucket α) (d : δ) (f : δ → α → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (d : δ) (h : HashSetImp α) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → δ) (d : δ) (m : HashSetImp α) : δ := foldBuckets m.buckets d f def find? [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Option α := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).find? (fun a' => a == a') def contains [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (List α)) (target : HashSetBucket α) : HashSetBucket α := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : List α := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx [] let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashSetBucket α) : HashSetImp α := let nbuckets := buckets.val.size * 2 have nbuckets > 0 from Nat.mulPos buckets.property (decide! : 2 > 0) let new_buckets : HashSetBucket α := ⟨mkArray nbuckets [], by rw [Array.sizeMkArrayEq]; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a a) h⟩ else let size' := size + 1 let buckets' := buckets.update i (a :: bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashSetImp α → Prop := | mkWff : ∀ n, WellFormed (mkHashSetImp n) | insertWff : ∀ m a, WellFormed m → WellFormed (insert m a) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashSetImp def HashSet (α : Type u) [BEq α] [Hashable α] := { m : HashSetImp α // m.WellFormed } open HashSetImp def mkHashSet {α : Type u} [BEq α] [Hashable α] (nbuckets := 8) : HashSet α := ⟨ mkHashSetImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashSet variables {α : Type u} [BEq α] [Hashable α] instance : Inhabited (HashSet α) := ⟨mkHashSet⟩ instance : EmptyCollection (HashSet α) := ⟨mkHashSet⟩ @[inline] def insert (m : HashSet α) (a : α) : HashSet α := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a, WellFormed.insertWff m a hw ⟩ @[inline] def erase (m : HashSet α) (a : α) : HashSet α := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def find? (m : HashSet α) (a : α) : Option α := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def contains (m : HashSet α) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (init : δ) (h : HashSet α) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → δ) (init : δ) (m : HashSet α) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def size (m : HashSet α) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashSet α) : Bool := m.size = 0 @[inline] def empty : HashSet α := mkHashSet def toList (m : HashSet α) : List α := m.fold (init := []) fun r a => a::r def toArray (m : HashSet α) : Array α := m.fold (init := #[]) fun r a => r.push a def numBuckets (m : HashSet α) : Nat := m.val.buckets.val.size end HashSet end Std
b4f6f650f08bba83f673ee3283bb90a8553caaba
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Std/Data/PersistentHashMap.lean
aa377d1c2cfdc849d9a778abdd9466f1f2ace5e5
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,368
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 -/ namespace Std universes u v w w' namespace PersistentHashMap inductive Entry (α : Type u) (β : Type v) (σ : Type w) where | entry (key : α) (val : β) : Entry α β σ | ref (node : σ) : Entry α β σ | null : Entry α β σ instance {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩ inductive Node (α : Type u) (β : Type v) : Type (max u v) where | entries (es : Array (Entry α β (Node α β))) : Node α β | collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node α β instance {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩ abbrev shift : USize := 5 abbrev branching : USize := USize.ofNat (2 ^ shift.toNat) abbrev maxDepth : USize := 7 abbrev maxCollisions : Nat := 4 def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) := (Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null) end PersistentHashMap structure PersistentHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray size : Nat := 0 abbrev PHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := PersistentHashMap α β namespace PersistentHashMap variable {α : Type u} {β : Type v} def empty [BEq α] [Hashable α] : PersistentHashMap α β := {} def isEmpty [BEq α] [Hashable α] (m : PersistentHashMap α β) : Bool := m.size == 0 instance [BEq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩ def mkEmptyEntries {α β} : Node α β := Node.entries mkEmptyEntriesArray abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) inductive IsCollisionNode : Node α β → Prop where | mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h) abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n } inductive IsEntriesNode : Node α β → Prop where | mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries) abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n } private theorem setSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β) : (ks.set i k).size = (vs.set j v).size := by rw [Array.sizeSetEq, Array.sizeSetEq vs, h] private theorem pushSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := by rw [Array.sizePushEq, Array.sizePushEq, h] partial def insertAtCollisionNodeAux [BEq α] : CollisionNode α β → Nat → α → β → CollisionNode α β | n@⟨Node.collision keys vals heq, _⟩, i, k, v => if h : i < keys.size then let idx : Fin keys.size := ⟨i, h⟩; let k' := keys.get idx; if k == k' then let j : Fin vals.size := ⟨i, by rw [←heq]; assumption⟩ ⟨Node.collision (keys.set idx k) (vals.set j v) (setSizeEq heq idx j k v), IsCollisionNode.mk _ _ _⟩ else insertAtCollisionNodeAux n (i+1) k v else ⟨Node.collision (keys.push k) (vals.push v) (pushSizeEq heq k v), IsCollisionNode.mk _ _ _⟩ | ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h) def insertAtCollisionNode [BEq α] : CollisionNode α β → α → β → CollisionNode α β := fun n k v => insertAtCollisionNodeAux n 0 k v def getCollisionNodeSize : CollisionNode α β → Nat | ⟨Node.collision keys _ _, _⟩ => keys.size | ⟨Node.entries _, h⟩ => False.elim (nomatch h) def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β := let ks : Array α := Array.mkEmpty maxCollisions let ks := (ks.push k₁).push k₂ let vs : Array β := Array.mkEmpty maxCollisions let vs := (vs.push v₁).push v₂ Node.collision ks vs rfl partial def insertAux [BEq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β | Node.collision keys vals heq, _, depth, k, v => let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val else match newNode with | ⟨Node.entries _, h⟩ => False.elim (nomatch h) | ⟨Node.collision keys vals heq, _⟩ => let rec traverse (i : Nat) (entries : Node α β) : Node α β := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ let h := hash k let h := div2Shift h (shift * (depth - 1)) traverse (i+1) (insertAux entries h depth k v) else entries traverse 0 mkEmptyEntries | Node.entries entries, h, depth, k, v => let j := (mod2Shift h shift).toNat Node.entries $ entries.modify j fun entry => match entry with | Entry.null => Entry.entry k v | Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v | Entry.entry k' v' => if k == k' then Entry.entry k v else Entry.ref $ mkCollisionNode k' v' k v def insert [BEq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β | { root := n, size := sz }, k, v => { root := insertAux n (hash k) 1 k v, size := sz + 1 } partial def findAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option β := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (vals.get ⟨i, by rw [←heq]; assumption⟩) else findAtAux keys vals heq (i+1) k else none partial def findAux [BEq α] : Node α β → USize → α → Option β | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some v else none | Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k def find? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option β | { root := n, .. }, k => findAux n (hash k) k @[inline] def getOp [BEq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β := self.find? idx @[inline] def findD [BEq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [BEq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" partial def findEntryAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option (α × β) := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (k', vals.get ⟨i, by rw [←heq]; assumption⟩) else findEntryAtAux keys vals heq (i+1) k else none partial def findEntryAux [BEq α] : Node α β → USize → α → Option (α × β) | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findEntryAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some (k', v) else none | Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k def findEntry? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β) | { root := n, .. }, k => findEntryAux n (hash k) k partial def containsAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Bool := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then true else containsAtAux keys vals heq (i+1) k else false partial def containsAux [BEq α] : Node α β → USize → α → Bool | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => false | Entry.ref node => containsAux node (div2Shift h shift) k | Entry.entry k' v => k == k' | Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k def contains [BEq α] [Hashable α] : PersistentHashMap α β → α → Bool | { root := n, .. }, k => containsAux n (hash k) k partial def isUnaryEntries (a : Array (Entry α β (Node α β))) (i : Nat) (acc : Option (α × β)) : Option (α × β) := if h : i < a.size then match a.get ⟨i, h⟩ with | Entry.null => isUnaryEntries a (i+1) acc | Entry.ref _ => none | Entry.entry k v => match acc with | none => isUnaryEntries a (i+1) (some (k, v)) | some _ => none else acc def isUnaryNode : Node α β → Option (α × β) | Node.entries entries => isUnaryEntries entries 0 none | Node.collision keys vals heq => if h : 1 = keys.size then have 0 < keys.size by rw [←h]; decide! some (keys.get ⟨0, this⟩, vals.get ⟨0, by rw [←heq]; assumption⟩) else none partial def eraseAux [BEq α] : Node α β → USize → α → Node α β × Bool | n@(Node.collision keys vals heq), _, k => match keys.indexOf? k with | some idx => let ⟨keys', keq⟩ := keys.eraseIdx' idx let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.ndrec idx heq) have keys.size - 1 = vals.size - 1 by rw [heq] (Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true) | none => (n, false) | n@(Node.entries entries), h, k => let j := (mod2Shift h shift).toNat let entry := entries.get! j match entry with | Entry.null => (n, false) | Entry.entry k' v => if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false) | Entry.ref node => let entries := entries.set! j Entry.null let (newNode, deleted) := eraseAux node (div2Shift h shift) k if !deleted then (n, false) else match isUnaryNode newNode with | none => (Node.entries (entries.set! j (Entry.ref newNode)), true) | some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true) def erase [BEq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β | { root := n, size := sz }, k => let h := hash k let (n, del) := eraseAux n h k { root := n, size := if del then sz - 1 else sz } section variable {m : Type w → Type w'} [Monad m] variable {σ : Type w} @[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ | Node.collision keys vals heq, acc => let rec traverse (i : Nat) (acc : σ) : m σ := do if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ traverse (i+1) (← f acc k v) else pure acc traverse 0 acc | Node.entries entries, acc => entries.foldlM (fun acc entry => match entry with | Entry.null => pure acc | Entry.entry k v => f acc k v | Entry.ref node => foldlMAux f node acc) acc @[specialize] def foldlM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (init : σ) : m σ := foldlMAux f map.root init @[specialize] def forM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit := map.foldlM (fun _ => f) ⟨⟩ @[specialize] def foldl [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (init : σ) : σ := Id.run $ map.foldlM f init end def toList [BEq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) := m.foldl (init := []) fun ps k v => (k, v) :: ps structure Stats where numNodes : Nat := 0 numNull : Nat := 0 numCollisions : Nat := 0 maxDepth : Nat := 0 partial def collectStats : Node α β → Stats → Nat → Stats | Node.collision keys _ _, stats, depth => { stats with numNodes := stats.numNodes + 1, numCollisions := stats.numCollisions + keys.size - 1, maxDepth := Nat.max stats.maxDepth depth } | Node.entries entries, stats, depth => let stats := { stats with numNodes := stats.numNodes + 1, maxDepth := Nat.max stats.maxDepth depth } entries.foldl (fun stats entry => match entry with | Entry.null => { stats with numNull := stats.numNull + 1 } | Entry.ref node => collectStats node stats (depth + 1) | Entry.entry _ _ => stats) stats def stats [BEq α] [Hashable α] (m : PersistentHashMap α β) : Stats := collectStats m.root {} 1 def Stats.toString (s : Stats) : String := s!"\{ nodes := {s.numNodes}, null := {s.numNull}, collisions := {s.numCollisions}, depth := {s.maxDepth}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentHashMap end Std
6585c946502a9f1ed914bad77de80bae0365c3b8
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/float.lean
697985e9f44e9559277f79ee9b170da72c1573a3
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
6,169
lean
/- Authors: E.W.Ayers -/ prelude import init.data namespace native meta constant float : Type namespace float -- fixed values based on the underlying C++ float implementation. namespace specification /-- The base. Either 2 or 10. -/ meta constant radix : nat /-- The length of the mantissa. -/ meta constant precision : nat /-- The maximum exponent. -/ meta constant emax : nat /-- The minimum exponent. `= 1 - emax` -/ meta constant emin : int end specification open specification /-- Returns the difference between 1.0 and the next representable value of the given floating-point type. Reference: https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon -/ meta constant epsilon : float /-- returns the maximum rounding error -/ meta constant round_error : float /-- Positive infinity. -/ meta constant infinity : float /-- Quiet NaN. -/ meta constant qNaN : float /-- Signalling NaN. -/ meta constant sNaN : float /-- Returns true when the value is positive or negative infinity.-/ meta constant is_infinite : float → bool meta constant is_finite : float → bool /-- Returns true when the value is qNaN or sNaN-/ meta constant is_nan : float → bool /-- Reference: https://en.cppreference.com/w/cpp/numeric/math/isnormal https://stackoverflow.com/questions/8341395/what-is-a-subnormal-floating-point-number -/ meta constant is_normal : float → bool /-- The sign `s` of the float. `tt` if negative. -/ meta constant sign : float → bool /-- The exponent `e` of the float in the base given by `radix`. `emin ≤ e ≤ emax`. Returns none if the number is not finite. -/ meta constant exponent : float → option int /-- Decompose the number `f` in to `(s,e)` where `0.5 ≤ s < 1.0` and `emin ≤ e ≤ emax` such that `f = s * 2 ^ e`. -/ meta constant frexp : float → float × int /-- Decompose in to integer `fst` and fractional `snd` parts. -/ meta constant modf : float → float × float /-- `mantissa f` returns a number `s` where `0.5 ≤ s < 1.0` such that there exists an integer `e` such that `f = s * 2 ^ e` -/ meta def mantissa : float → float := prod.fst ∘ frexp -- [TODO] -- /-- List of digits in the mantissa of the float. `d₀.d₁d₂d₃ ⋯` -- The length is `precision` and `0 ≤ dᵢ < radix` for each digit `dᵢ`. -- The head of the list is the most significant digit. -- -/ -- meta constant mantissa_digits : float → array precision nat meta constant add : float → float → float meta instance : has_add float := ⟨add⟩ meta constant sub : float → float → float meta instance : has_sub float := ⟨sub⟩ meta constant neg : float → float meta instance : has_neg float := ⟨neg⟩ meta constant mul : float → float → float meta instance : has_mul float := ⟨mul⟩ meta constant div : float → float → float meta instance : has_div float := ⟨div⟩ /-- remainder of the floating point division operation. -/ meta constant fmod : float → float → float /-- signed remainder of the division operation. -/ meta constant remainder : float → float → float meta constant max : float → float → float meta constant min : float → float → float meta constant pow : float → float → float meta instance has_float_pow : has_pow float float := ⟨pow⟩ /-- Square root. -/ meta constant sqrt : float → float /-- Cube root. -/ meta constant cbrt : float → float /-- Computes `sqrt(x^2 + y^2)`. -/ meta constant hypot : float → float → float /-- Exponential function. -/ meta constant exp : float → float /-- 2 raised to the given power. -/ meta constant exp2 : float → float /-- Natural logarithm. -/ meta constant log : float → float meta constant log2 : float → float meta constant log10 : float → float meta constant pi : float meta constant sin : float → float meta constant cos : float → float meta constant tan : float → float meta constant asin : float → float meta constant acos : float → float meta constant atan : float → float /-- `atan2 y x` finds the angle anticlockwise from the x-axis to the point `[x,y]`.-/ meta constant atan2 : float → float → float meta constant sinh : float → float meta constant cosh : float → float meta constant tanh : float → float meta constant asinh : float → float meta constant acosh : float → float meta constant atanh : float → float meta constant abs : float → float /-- Nearest integer not less than the given value. Returns 0 if the input is not finite. -/ meta constant ceil : float → int /-- Nearest integer not greater than the given value. Returns 0 if the input is not finite. -/ meta constant floor : float → int /-- Nearest integer not greater in magnitude than the given value. Returns 0 if the input is not finite. -/ meta constant trunc : float → int /-- Round to the nearest integer, rounding away from zero in halfway cases. Returns 0 if the input is not finite. -/ meta constant round : float → int meta constant lt : float → float → bool meta instance : has_lt float := ⟨λ x y, lt x y⟩ meta instance decidable_lt : decidable_rel (float.has_lt.lt) := by apply_instance meta constant le : float → float → bool meta instance : has_le float := ⟨λ x y, le x y⟩ meta instance decidable_le : decidable_rel (float.has_le.le) := by apply_instance meta constant dec_eq : decidable_eq float attribute [instance] dec_eq meta constant of_nat : nat → float meta constant of_int : int → float meta instance of_nat_coe : has_coe nat float := ⟨of_nat⟩ meta instance of_int_coe : has_coe int float := ⟨of_int⟩ protected meta def zero : float := of_nat 0 protected meta def one : float := of_nat 1 meta instance : has_zero float := ⟨float.zero⟩ meta instance : has_one float := ⟨float.one⟩ meta constant to_repr : float → string meta instance : has_repr float := ⟨to_repr⟩ meta instance : has_to_string float := ⟨to_repr⟩ meta instance : has_to_format float := ⟨format.of_string ∘ to_string⟩ meta constant of_string : string → option float meta instance has_nat_pow : has_pow float nat := ⟨λ a b, native.float.pow a (float.of_nat b)⟩ end float end native
7408abc7fa4d98ae0fec308909b5033896c58047
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/mv_polynomial/basic.lean
605228dcf655e4cde7a0741097226f2f92e29334
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
37,210
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, Johan Commelin, Mario Carneiro -/ import data.polynomial.eval import data.finsupp.antidiagonal /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring section instances instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] : decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩ instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] : distrib_mul_action R (mv_polynomial σ S₁) := add_monoid_algebra.distrib_mul_action instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) := add_monoid_algebra.module instance [monoid R] [monoid S₁] [comm_semiring S₂] [has_scalar R S₁] [distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [is_scalar_tower R S₁ S₂] : is_scalar_tower R S₁ (mv_polynomial σ S₂) := add_monoid_algebra.is_scalar_tower instance [monoid R] [monoid S₁][comm_semiring S₂] [distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [smul_comm_class R S₁ S₂] : smul_comm_class R S₁ (mv_polynomial σ S₂) := add_monoid_algebra.smul_comm_class instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) := add_monoid_algebra.algebra end instances variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R} /-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/ def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* mv_polynomial σ R := { to_fun := monomial 0, ..single_zero_ring_hom } variables (R σ) theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl variables {R σ} /-- `X n` is the degree `1` monomial $X_n$. -/ def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1 lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial] @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C_apply, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n := by induction n; simp [pow_succ, *] lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] : function.injective (C : R → mv_polynomial σ R) := finsupp.single_injective _ lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) [is_empty σ] : function.surjective (C : R → mv_polynomial σ R) := begin refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩, simpa [(finsupp.ext is_empty_elim : a = 0), C_apply, monomial], end @[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) : (C r : mv_polynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] : infinite (mv_polynomial σ R) := infinite.of_injective C (C_injective _ _) instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R] [nontrivial R] : infinite (mv_polynomial σ R) := infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $ function.injective.comp (λ m n, (finsupp.single_left_inj one_ne_zero).mp) (finsupp.single_injective _) lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n := by induction n; simp [nat.succ_eq_add_one, *] theorem C_mul' : mv_polynomial.C a * p = a • p := (algebra.smul_def a p).symm lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_eq_C_mul_X {s : σ} {a : R} {n : ℕ} : monomial (single s n) a = C a * (X s)^n := by rw [← zero_add (single s n), monomial_add_single, C_apply] @[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} : monomial s a + monomial s b = monomial s (a + b) := single_add.symm @[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := add_monoid_algebra.single_mul_single @[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 := single_zero @[simp] lemma sum_monomial_eq {A : Type*} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := sum_single_index w @[simp] lemma sum_C {A : Type*} [add_comm_monoid A] {b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) : sum (C a) b = b 0 a := by simp [C_apply, w] lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) := begin apply @finsupp.induction σ ℕ _ _ s, { simp only [C_apply, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm], { simp only [pow_zero], }, { intro a, simp only [pow_zero], }, { intros, rw pow_add, }, } end @[recursor 5] lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [add_comm, monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) attribute [elab_as_eliminator] theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this, show P (monomial 0 0), from h1 0 0) (λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf) @[ext] lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A} (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := by { ext, exacts [hC _, hX _] } lemma hom_eq_hom [semiring S₂] (f g : mv_polynomial σ R →+* S₂) (hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) : f p = g p := ring_hom.congr_fun (ring_hom_ext hC hX) p lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) : f p = p := hom_eq_hom f (ring_hom.id _) hC hX p @[ext] lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A] {f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := by { ext, exact hf _ } @[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) : f (C r) = C r := f.commutes r section support /-- The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient. -/ def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) := p.support lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} := by convert rfl lemma support_monomial_subset : (monomial s a).support ⊆ {s} := support_single_subset lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} := by rw [X, support_monomial, if_neg]; exact one_ne_zero end support section coeff /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := @coe_fn _ (monoid_algebra.has_coe_to_fun _ _) p m @[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} : m ∈ p.support ↔ p.coeff m ≠ 0 := by simp [support, coeff] lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} : m ∉ p.support ↔ p.coeff m = 0 := by simp lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} : p.sum b = ∑ m in p.support, b m (p.coeff m) := by simp [support, finsupp.sum, coeff] lemma support_mul (p q : mv_polynomial σ R) : (p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) := by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl @[ext] lemma ext (p q : mv_polynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ R) : p = q ↔ (∀ m, coeff m p = coeff m q) := ⟨ λ h m, by rw h, ext p q⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply p q m @[simp] lemma coeff_smul {S₁ : Type*} [monoid S₁] [distrib_mul_action S₁ R] (m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) : coeff m (c • p) = c • coeff m p := smul_apply c p m @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ R) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) /-- `mv_polynomial.coeff m` but promoted to an `add_monoid_hom`. -/ @[simps] def coeff_add_monoid_hom (m : σ →₀ ℕ) : mv_polynomial σ R →+ R := { to_fun := coeff m, map_zero' := coeff_zero m, map_add' := coeff_add m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) := (coeff_add_monoid_hom _).map_sum _ s lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) := by simp [monomial_eq] @[simp] lemma coeff_monomial [decidable_eq σ] (m n) (a) : coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 := single_apply @[simp] lemma coeff_C [decidable_eq σ] (m) (a) : coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 := single_apply lemma coeff_one [decidable_eq σ] (m) : coeff m (1 : mv_polynomial σ R) = if 0 = m then 1 else 0 := coeff_C m 1 @[simp] lemma coeff_zero_C (a) : coeff 0 (C a : mv_polynomial σ R) = a := single_eq_same @[simp] lemma coeff_zero_one : coeff 0 (1 : mv_polynomial σ R) = 1 := coeff_zero_C 1 lemma coeff_X_pow [decidable_eq σ] (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:R), rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' [decidable_eq σ] (i : σ) (m) : coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ R) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def, sum_C], { simp [sum_def, coeff_sum] {contextual := tt} }, simp end lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x in antidiagonal n, coeff x.1 p * coeff x.2 q := begin rw mul_def, -- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`, -- so we need to turn both sides into a sum over a product. have := @finset.sum_product R (σ →₀ ℕ) _ _ p.support q.support (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only }, exact single_apply }, symmetry, -- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`. apply finset.sum_bij_ne_zero (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)) _ _, (x.1, x.2)), { intros x hx hx', simp only [mem_antidiagonal, eq_self_iff_true, if_false, forall_true_iff], contrapose! hx', rw [if_neg hx'] }, { rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl', simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro }, { rintros ⟨i, j⟩ hij hij', refine ⟨⟨i, j⟩, _, _⟩, { simp only [mem_support_iff, finset.mem_product], contrapose! hij', exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' }, { rw [mem_antidiagonal] at hij, simp only [exists_prop, true_and, ne.def, if_pos hij, hij', not_false_iff] } }, { intros x hx hx', simp only [ne.def] at hx' ⊢, split_ifs with H, { refl }, { rw if_neg H at hx', contradiction } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal := mem_antidiagonal.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin nontriviality R, split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' with t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa finsupp.mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H, rcases H with ⟨j, hj, i', hi', H⟩, rw [support_X, finset.mem_singleton] at hi', subst i', rw finset.mem_singleton at H, subst m, rw [finsupp.mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 } end lemma eq_zero_iff {p : mv_polynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by { rw ext_iff, simp only [coeff_zero], } lemma ne_zero_iff {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by { rw [ne.def, eq_zero_iff], push_neg, } lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0, let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i), use ψ, apply mv_polynomial.ext, intro i, simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'], split_ifs with hi hi, { rw hc }, { rw not_mem_support_iff at hi, rwa mul_zero } }, end end coeff section constant_coeff /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff : mv_polynomial σ R →+* R := { to_fun := coeff 0, map_one' := by simp [coeff, add_monoid_algebra.one_def], map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero], map_zero' := coeff_zero _, map_add' := coeff_add _ } lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl @[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r := by simp [constant_coeff_eq] @[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 := by simp [constant_coeff_eq] lemma constant_coeff_monomial [decidable_eq σ] (d : σ →₀ ℕ) (r : R) : constant_coeff (monomial d r) = if d = 0 then r else 0 := by rw [constant_coeff_eq, coeff_monomial] variables (σ R) @[simp] lemma constant_coeff_comp_C : constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R := by { ext, apply constant_coeff_C } @[simp] lemma constant_coeff_comp_algebra_map : constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R := constant_coeff_comp_C _ _ end constant_coeff section as_sum @[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) : ∑ v in p.support, monomial v (coeff v p) = p := finsupp.sum_single p lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end as_sum section eval₂ variables (f : R →+* S₁) (g : σ → S₁) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ R) : S₁ := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i := rfl lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i := by { simp only [eval₂_eq, ← finsupp.prod_pow], refl } @[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 := finsupp.sum_zero_index section @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [f.map_zero]) (by simp [add_mul, f.map_add]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [f.map_zero]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 := (eval₂_C _ _ _).trans f.map_one @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, f.map_one, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, f.map_mul] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by rw [monomial_single_add, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, f.map_one, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_polynomial.induction_on q, { simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] }, { simp [mul_add, eval₂_add] {contextual := tt} }, { simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end @[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ } | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := { to_fun := eval₂ f g, map_one' := eval₂_one _ _, map_mul' := λ p q, eval₂_mul _ _, map_zero' := eval₂_zero _ _, map_add' := λ p q, eval₂_add _ _ } @[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := by rintros rfl rfl rfl; refl end @[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) : eval₂_hom f g (C r) = f r := eval₂_C f g r @[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) : eval₂_hom f g (X i) = g i := eval₂_X f g i @[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) := begin apply mv_polynomial.ring_hom_ext, { intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] }, { intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] } end lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) := by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X'] section lemma eval₂_comp_left {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, k.map_add, eval₂_mul, k.map_mul] {contextual := tt} end @[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end @[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) := (eval₂_hom f g).map_prod _ s @[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) := (eval₂_hom f g).map_sum _ s attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := begin show _ = eval₂_hom f g (eval₂ C q p), rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp, end end eval₂ section eval variables {f : σ → R} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i := rfl lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i := eval₂_eq' (ring_hom.id R) x f lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _ @[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p := by rw [smul_eq_C_mul, (eval x).map_mul, eval_C] lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) := (eval g).map_sum _ _ @[to_additive] lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) := (eval g).map_prod _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : eval (eval g ∘ f) p = eval g (eval₂ C f p) := begin rw eval₂_comp_left (eval g), unfold eval, simp only [coe_eval₂_hom], congr' with a, simp end end eval section map variables (f : R →+* S₁) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _ theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta theorem map_map [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : map g (map f p) = map (g.comp f) p := (eval₂_comp_left (map g) (C.comp f) X p).trans $ begin congr, { ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], }, { ext1 n, simp only [map_X, comp_app], } end theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) : p.eval₂ f g = eval g (map f p) := begin unfold map eval, simp only [coe_eval₂_hom], have h := eval₂_comp_left (eval₂_hom _ g), dsimp at h, rw h, congr, { ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], }, { ext1 n, simp only [comp_app, eval₂_X], }, end lemma eval₂_comp_right {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero }, { intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add }, { intros p i hp m, simp only [hp, (map f).map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw f.map_zero } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) := begin intros p q h, simp only [ext_iff, coeff_map] at h ⊢, intro m, exact hf (h m), end @[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval g (map f p) = eval₂ f g p := by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } } @[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (map f p) = eval₂ (φ.comp f) g p := by { rw [← eval_map, ← eval_map, map_map], } @[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p := eval₂_map f g φ p @[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) : constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) := coeff_map f φ 0 lemma constant_coeff_comp_map (f : R →+* S₁) : (constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff := by { ext; simp } lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support := begin intro x, simp only [mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f end lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) : (map f p).support = p.support := begin apply finset.subset.antisymm, { exact mv_polynomial.support_map_subset _ _ }, intros x hx, rw mem_support_iff, contrapose! hx, simp only [not_not, mem_support_iff], change (map f p).coeff x = 0 at hx, rw [coeff_map, ← f.map_zero] at hx, exact hf hx end lemma C_dvd_iff_map_hom_eq_zero (q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r') (φ : mv_polynomial σ R) : C r ∣ φ ↔ map q φ = 0 := begin rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff], simp only [coeff_map, coeff_zero, hr], end lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) : map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ := begin rw mv_polynomial.ext_iff, apply forall_congr, intro m, rw [coeff_map], apply eq_iff_eq_cancel_right.mpr, refl end end map section aeval /-! ### The algebra of multivariate polynomials -/ variables (f : σ → S₁) variables [algebra R S₁] [comm_semiring S₂] /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval : mv_polynomial σ R →ₐ[R] S₁ := { commutes' := λ r, eval₂_C _ _ _ .. eval₂_hom (algebra_map R S₁) f } theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) : aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl @[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _ @[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _ theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) : φ = aeval (φ ∘ X) := by { ext i, simp } lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B] (φ : S₁ →ₐ[R] B) : φ.comp (aeval f) = aeval (λ i, φ (f i)) := by { ext i, simp } @[simp] lemma map_aeval {B : Type*} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } @[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) := begin suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff, from ring_hom.congr_fun this p, ext; simp end @[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) := eval₂_hom_zero f p @[simp] lemma aeval_zero (p : mv_polynomial σ R) : aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := eval₂_hom_zero (algebra_map R S₁) p @[simp] lemma aeval_zero' (p : mv_polynomial σ R) : aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := aeval_zero p lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) := eval₂_hom_monomial _ _ _ _ lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) : eval₂_hom f g φ = 0 := begin rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero], intros d hd, obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd), rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hgi, zero_pow], rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff] end lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) : aeval f φ = 0 := eval₂_hom_eq_zero _ _ _ h end aeval end comm_semiring end mv_polynomial
8861869513dc3fec0b70601fb019250272a6d491
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Init/Util.lean
ac5bc55663b7f2d56dce5424429f1b0a43ebea79
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,225
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.String.Basic import Init.Data.ToString universes u v /- debugging helper functions -/ @[neverExtract, extern "lean_dbg_trace"] def dbgTrace {α : Type u} (s : String) (f : Unit → α) : α := f () def dbgTraceVal {α : Type u} [HasToString α] (a : α) : α := dbgTrace (toString a) (fun _ => a) /- Display the given message if `a` is shared, that is, RC(a) > 1 -/ @[neverExtract, extern "lean_dbg_trace_if_shared"] def dbgTraceIfShared {α : Type u} (s : String) (a : α) : α := a @[extern "lean_dbg_sleep"] def dbgSleep {α : Type u} (ms : UInt32) (f : Unit → α) : α := f () @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α := arbitrary _ @[noinline] private def mkPanicMessage (modName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPos {α : Type u} [Inhabited α] (modName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessage modName line col msg) -- TODO: should be a macro @[neverExtract, noinline, nospecialize] def unreachable! {α : Type u} [Inhabited α] : α := panic! "unreachable" @[extern "lean_ptr_addr"] unsafe def ptrAddrUnsafe {α : Type u} (a : @& α) : USize := 0 @[inline] unsafe def withPtrAddrUnsafe {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k (ptrAddrUnsafe a) @[inline] unsafe def withPtrEqUnsafe {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := if ptrAddrUnsafe a == ptrAddrUnsafe b then true else k () inductive PtrEqResult {α : Type u} (x y : α) : Type | unknown : PtrEqResult | yesEqual (h : x = y) : PtrEqResult @[inline] unsafe def withPtrEqResultUnsafe {α : Type u} {β : Type v} [Subsingleton β] (a b : α) (k : PtrEqResult a b → β) : β := if ptrAddrUnsafe a == ptrAddrUnsafe b then k (PtrEqResult.yesEqual lcProof) else k PtrEqResult.unknown @[implementedBy withPtrEqUnsafe] def withPtrEq {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := k () /-- `withPtrEq` for `DecidableEq` -/ @[inline] def withPtrEqDecEq {α : Type u} (a b : α) (k : Unit → Decidable (a = b)) : Decidable (a = b) := let b := withPtrEq a b (fun _ => toBoolUsing (k ())) (toBoolUsingEqTrue (k ())); condEq b (fun h => isTrue (ofBoolUsingEqTrue h)) (fun h => isFalse (ofBoolUsingEqFalse h)) /-- Similar to `withPtrEq`, but executes the continuation `k` with the "result" of the pointer equality test. -/ @[implementedBy withPtrEqResultUnsafe] def withPtrEqResult {α : Type u} {β : Type v} [Subsingleton β] (a b : α) (k : PtrEqResult a b → β) : β := k PtrEqResult.unknown @[implementedBy withPtrAddrUnsafe] def withPtrAddr {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k 0
7aeab257fb6b5893c34f0e44392d12f054af40d1
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/expr.lean
673b7d813242f7f634221b3319ee71f9eab4c519
[ "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
5,665
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level inductive binder_info | default | implicit | strict_implicit | inst_implicit | other meta_constant macro_def : Type /- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/ inductive expr | var : unsigned → expr | sort : level → expr | const : name → list level → expr | meta : name → expr → expr | local_const : name → name → binder_info → expr → expr | app : expr → expr → expr | lam : name → binder_info → expr → expr → expr | pi : name → binder_info → expr → expr → expr | elet : name → expr → expr → expr → expr | macro : macro_def → ∀ n : unsigned, (fin (unsigned.to_nat n) → expr) → expr attribute [instance] definition expr.is_inhabited : inhabited expr := inhabited.mk (expr.sort level.zero) meta_constant expr.mk_macro (d : macro_def) : list expr → expr meta_definition expr.mk_var (n : nat) : expr := expr.var (unsigned.of_nat n) meta_constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq meta_constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt meta_constant expr.to_string : expr → string attribute [instance] meta_definition expr.has_to_string : has_to_string expr := has_to_string.mk expr.to_string meta_constant expr.hash : expr → nat meta_constant expr.lt : expr → expr → bool meta_constant expr.lex_lt : expr → expr → bool meta_definition expr.cmp (a b : expr) : ordering := if expr.lt a b = bool.tt then ordering.lt else if a = b then ordering.eq else ordering.gt meta_constant expr.fold {A : Type} : expr → A → (expr → unsigned → A → A) → A meta_constant expr.abstract_local : expr → name → expr meta_constant expr.abstract_locals : expr → list name → expr meta_constant expr.instantiate_var : expr → expr → expr meta_constant expr.instantiate_vars : expr → list expr → expr meta_constant expr.has_var : expr → bool meta_constant expr.has_var_idx : expr → nat → bool meta_constant expr.has_local : expr → bool meta_constant expr.has_meta_var : expr → bool meta_constant expr.lift_vars : expr → nat → nat → expr meta_constant expr.lower_vars : expr → nat → nat → expr namespace expr open decidable meta_definition app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (expr.app f p) ps meta_definition is_app : expr → bool | (app f a) := tt | e := ff meta_definition app_fn : expr → expr | (app f a) := f | a := a meta_definition app_arg : expr → expr | (app f a) := a | a := a meta_definition get_app_fn : expr → expr | (app f a) := get_app_fn f | a := a meta_definition get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta_definition get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta_definition get_app_args : expr → list expr := get_app_args_aux [] meta_definition const_name : expr → name | (const n ls) := n | e := name.anonymous meta_definition is_constant : expr → bool | (const n ls) := tt | e := ff meta_definition is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta_definition local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta_definition local_pp_name : expr → name | (local_const x n bi t) := n | e := name.anonymous meta_definition is_constant_of : expr → name → bool | (const n₁ ls) n₂ := to_bool (n₁ = n₂) | e n := ff meta_definition is_app_of (e : expr) (n : name) : bool := is_app e && is_constant_of (get_app_fn e) n meta_definition is_false (e : expr) : bool := is_constant_of e `false meta_definition is_not : expr → option expr | (app f a) := if is_constant_of f `not = tt then some a else none | (pi n bi a b) := if is_false b = tt then some a else none | e := none meta_definition is_eq (e : expr) : option (expr × expr) := if is_app_of e `eq = tt ∧ get_app_num_args e = 3 then some (app_arg (app_fn e), app_arg e) else none meta_definition is_ne (e : expr) : option (expr × expr) := if is_app_of e `ne = tt ∧ get_app_num_args e = 3 then some (app_arg (app_fn e), app_arg e) else none meta_definition is_heq (e : expr) : option (expr × expr × expr × expr) := if is_app_of e `heq = tt ∧ get_app_num_args e = 4 then some (app_arg (app_fn (app_fn (app_fn e))), app_arg (app_fn (app_fn e)), app_arg (app_fn e), app_arg e) else none meta_definition is_pi : expr → bool | (pi n bi d b) := tt | e := ff meta_definition is_let : expr → bool | (elet n t v b) := tt | e := ff meta_definition binding_name : expr → name | (pi n m d b) := n | (lam n m d b) := n | e := name.anonymous meta_definition binding_info : expr → binder_info | (pi n bi d b) := bi | (lam n bi d b) := bi | e := binder_info.default meta_definition binding_domain : expr → expr | (pi n bi d b) := d | (lam n bi d b) := d | e := e meta_definition binding_body : expr → expr | (pi n bi d b) := b | (lam n bi d b) := b | e := e meta_definition prop : expr := expr.sort level.zero end expr
d35c700e5c5aa939b991cf5938d262d2cbc48864
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/finset/powerset.lean
7a3a1962ee3134b1a96bd4cb3e18c1fa4a0021dc
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
6,386
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.finset.lattice /-! # The powerset of a finset -/ namespace finset open multiset variables {α : Type*} /-! ### powerset -/ section powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] lemma powerset_empty : finset.powerset (∅ : finset α) = {∅} := rfl @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) lemma not_mem_of_mem_powerset_of_not_mem {s t : finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by { apply mt _ h, apply mem_powerset.1 ht } lemma powerset_insert [decidable_eq α] (s : finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := begin ext t, simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff], by_cases h : a ∈ t, { split, { exact λH, or.inr ⟨_, H, insert_erase h⟩ }, { intros H, cases H, { exact subset.trans (erase_subset a t) H }, { rcases H with ⟨u, hu⟩, rw ← hu.2, exact subset.trans (erase_insert_subset a u) hu.1 } } }, { have : ¬ ∃ (u : finset α), u ⊆ s ∧ insert a u = t, by simp [ne.symm (ne_insert_of_not_mem _ _ h)], simp [finset.erase_eq_of_not_mem h, this] } end end powerset section powerset_len /-- Given an integer `n` and a finset `s`, then `powerset_len n s` is the finset of subsets of `s` of cardinality `n`. -/ def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) @[simp] lemma powerset_len_zero (s : finset α) : finset.powerset_len 0 s = {∅} := begin ext, rw [mem_powerset_len, mem_singleton, card_eq_zero], refine ⟨λ h, h.2, λ h, by { rw h, exact ⟨empty_subset s, rfl⟩ }⟩, end @[simp] theorem powerset_len_empty (n : ℕ) {s : finset α} (h : s.card < n) : powerset_len n s = ∅ := finset.card_eq_zero.mp (by rw [card_powerset_len, nat.choose_eq_zero_of_lt h]) theorem powerset_len_eq_filter {n} {s : finset α} : powerset_len n s = (powerset s).filter (λ x, x.card = n) := by { ext, simp [mem_powerset_len] } lemma powerset_len_succ_insert [decidable_eq α] {x : α} {s : finset α} (h : x ∉ s) (n : ℕ) : powerset_len n.succ (insert x s) = powerset_len n.succ s ∪ (powerset_len n s).image (insert x) := begin rw [powerset_len_eq_filter, powerset_insert, filter_union, ←powerset_len_eq_filter], congr, rw [powerset_len_eq_filter, image_filter], congr' 1, ext t, simp only [mem_powerset, mem_filter, function.comp_app, and.congr_right_iff], intro ht, have : x ∉ t := λ H, h (ht H), simp [card_insert_of_not_mem this, nat.succ_inj'] end lemma powerset_len_nonempty {n : ℕ} {s : finset α} (h : n < s.card) : (powerset_len n s).nonempty := begin classical, induction s using finset.induction_on with x s hx IH generalizing n, { simpa using h }, { cases n, { simp }, { rw [card_insert_of_not_mem hx, nat.succ_lt_succ_iff] at h, rw powerset_len_succ_insert hx, refine nonempty.mono _ ((IH h).image (insert x)), convert (subset_union_right _ _) } } end @[simp] lemma powerset_len_self (s : finset α) : powerset_len s.card s = {s} := begin ext, rw [mem_powerset_len, mem_singleton], split, { exact λ ⟨hs, hc⟩, eq_of_subset_of_card_le hs hc.ge }, { rintro rfl, simp } end lemma powerset_card_bUnion [decidable_eq (finset α)] (s : finset α) : finset.powerset s = (range (s.card + 1)).bUnion (λ i, powerset_len i s) := begin refine ext (λ a, ⟨λ ha, _, λ ha, _ ⟩), { rw mem_bUnion, exact ⟨a.card, mem_range.mpr (nat.lt_succ_of_le (card_le_of_subset (mem_powerset.mp ha))), mem_powerset_len.mpr ⟨mem_powerset.mp ha, rfl⟩⟩ }, { rcases mem_bUnion.mp ha with ⟨i, hi, ha⟩, exact mem_powerset.mpr (mem_powerset_len.mp ha).1, } end lemma powerset_len_sup [decidable_eq α] (u : finset α) (n : ℕ) (hn : n < u.card) : (powerset_len n.succ u).sup id = u := begin apply le_antisymm, { simp_rw [sup_le_iff, mem_powerset_len], rintros x ⟨h, -⟩, exact h }, { rw [sup_eq_bUnion, le_iff_subset, subset_iff], cases (nat.succ_le_of_lt hn).eq_or_lt with h' h', { simp [h'] }, { intros x hx, simp only [mem_bUnion, exists_prop, id.def], obtain ⟨t, ht⟩ : ∃ t, t ∈ powerset_len n (u.erase x) := powerset_len_nonempty _, { refine ⟨insert x t, _, mem_insert_self _ _⟩, rw [←insert_erase hx, powerset_len_succ_insert (not_mem_erase _ _)], exact mem_union_right _ (mem_image_of_mem _ ht) }, { rwa [card_erase_of_mem hx, nat.lt_pred_iff] } } } end end powerset_len end finset
0bae595d8f82b8f8da0b84bb9b7119cf74947fbc
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/probability_theory/stopping.lean
b681032ddf6cbb262d54034928ab853c077d425d
[ "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
18,615
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.constructions.borel_space import measure_theory.function.l1_space /-! # Filtration and stopping time This file defines some standard definition from the theory of stochastic processes including filtrations and stopping times. These definitions are used to model the amount of information at a specific time and is the first step in formalizing stochastic processes. ## Main definitions * `measure_theory.filtration`: a filtration on a measurable space * `measure_theory.adapted`: a sequence of functions `u` is said to be adapted to a filtration `f` if at each point in time `i`, `u i` is `f i`-measurable * `measure_theory.filtration.natural`: the natural filtration with respect to a sequence of measurable functions is the smallest filtration to which it is adapted to * `measure_theory.is_stopping_time`: a stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is `f i`-measurable * `measure_theory.is_stopping_time.measurable_space`: the σ-algebra associated with a stopping time ## Tags filtration, stopping time, stochastic process -/ noncomputable theory open_locale classical measure_theory nnreal ennreal topological_space big_operators namespace measure_theory /-- A `filtration` on measurable space `α` with σ-algebra `m` is a monotone sequence of of sub-σ-algebras of `m`. -/ structure filtration {α : Type*} (ι : Type*) [preorder ι] (m : measurable_space α) := (seq : ι → measurable_space α) (mono : monotone seq) (le : ∀ i : ι, seq i ≤ m) variables {α β ι : Type*} {m : measurable_space α} open topological_space section preorder variables [preorder ι] instance : has_coe_to_fun (filtration ι m) (λ _, ι → measurable_space α) := ⟨λ f, f.seq⟩ /-- The constant filtration which is equal to `m` for all `i : ι`. -/ def const_filtration (m : measurable_space α) : filtration ι m := ⟨λ _, m, monotone_const, λ _, le_rfl⟩ instance : inhabited (filtration ι m) := ⟨const_filtration m⟩ lemma measurable_set_of_filtration {f : filtration ι m} {s : set α} {i : ι} (hs : measurable_set[f i] s) : measurable_set[m] s := f.le i s hs /-- A measure is σ-finite with respect to filtration if it is σ-finite with respect to all the sub-σ-algebra of the filtration. -/ class sigma_finite_filtration (μ : measure α) (f : filtration ι m) : Prop := (sigma_finite : ∀ i : ι, sigma_finite (μ.trim (f.le i))) instance sigma_finite_of_sigma_finite_filtration (μ : measure α) (f : filtration ι m) [hf : sigma_finite_filtration μ f] (i : ι) : sigma_finite (μ.trim (f.le i)) := by apply hf.sigma_finite -- can't exact here variable [measurable_space β] /-- A sequence of functions `u` is adapted to a filtration `f` if for all `i`, `u i` is `f i`-measurable. -/ def adapted (f : filtration ι m) (u : ι → α → β) : Prop := ∀ i : ι, measurable[f i] (u i) namespace adapted lemma add [has_add β] [has_measurable_add₂ β] {u v : ι → α → β} {f : filtration ι m} (hu : adapted f u) (hv : adapted f v) : adapted f (u + v) := λ i, @measurable.add _ _ _ _ (f i) _ _ _ (hu i) (hv i) lemma neg [has_neg β] [has_measurable_neg β] {u : ι → α → β} {f : filtration ι m} (hu : adapted f u) : adapted f (-u) := λ i, @measurable.neg _ α _ _ _ (f i) _ (hu i) lemma smul [has_scalar ℝ β] [has_measurable_smul ℝ β] {u : ι → α → β} {f : filtration ι m} (c : ℝ) (hu : adapted f u) : adapted f (c • u) := λ i, @measurable.const_smul ℝ β α _ _ _ (f i) _ _ (hu i) c end adapted variable (β) lemma adapted_zero [has_zero β] (f : filtration ι m) : adapted f (0 : ι → α → β) := λ i, @measurable_zero β α (f i) _ _ variable {β} namespace filtration /-- Given a sequence of functions, the natural filtration is the smallest sequence of σ-algebras such that that sequence of functions is measurable with respect to the filtration. -/ def natural (u : ι → α → β) (hum : ∀ i, measurable (u i)) : filtration ι m := { seq := λ i, ⨆ j ≤ i, measurable_space.comap (u j) infer_instance, mono := λ i j hij, bsupr_le_bsupr' $ λ k hk, le_trans hk hij, le := λ i, bsupr_le (λ j hj s hs, let ⟨t, ht, ht'⟩ := hs in ht' ▸ hum j ht) } lemma adapted_natural {u : ι → α → β} (hum : ∀ i, measurable[m] (u i)) : adapted (natural u hum) u := λ i, measurable.le (le_bsupr_of_le i (le_refl i) le_rfl) (λ s hs, ⟨s, hs, rfl⟩) end filtration /-- A stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is measurable with respect to `f i`. Intuitively, the stopping time `τ` describes some stopping rule such that at time `i`, we may determine it with the information we have at time `i`. -/ def is_stopping_time (f : filtration ι m) (τ : α → ι) := ∀ i : ι, measurable_set[f i] $ {x | τ x ≤ i} variables {f : filtration ℕ m} {τ : α → ℕ} lemma is_stopping_time.measurable_set_le (hτ : is_stopping_time f τ) (i : ℕ) : measurable_set[f i] {x | τ x ≤ i} := hτ i lemma is_stopping_time.measurable_set_eq (hτ : is_stopping_time f τ) (i : ℕ) : measurable_set[f i] {x | τ x = i} := begin cases i, { convert (hτ 0), simp only [set.set_of_eq_eq_singleton, le_zero_iff] }, { rw (_ : {x | τ x = i + 1} = {x | τ x ≤ i + 1} \ {x | τ x ≤ i}), { exact (hτ (i + 1)).diff (f.mono (nat.le_succ _) _ (hτ i)) }, { ext, simp only [set.mem_diff, not_le, set.mem_set_of_eq], split, { intro h, simp [h] }, { rintro ⟨h₁, h₂⟩, linarith } } } end lemma is_stopping_time.measurable_set_ge (hτ : is_stopping_time f τ) (i : ℕ) : measurable_set[f i] {x | i ≤ τ x} := begin have : {a : α | i ≤ τ a} = (set.univ \ {a | τ a ≤ i}) ∪ {a | τ a = i}, { ext1 a, simp only [true_and, set.mem_univ, set.mem_diff, not_le, set.mem_union_eq, set.mem_set_of_eq], rw le_iff_lt_or_eq, by_cases h : τ a = i, { simp [h], }, { simp only [h, ne.symm h, or_false, or_iff_left_iff_imp], }, }, rw this, exact (measurable_set.univ.diff (hτ i)).union (hτ.measurable_set_eq i), end lemma is_stopping_time.measurable_set_eq_le {f : filtration ℕ m} {τ : α → ℕ} (hτ : is_stopping_time f τ) {i j : ℕ} (hle : i ≤ j) : measurable_set[f j] {x | τ x = i} := f.mono hle _ $ hτ.measurable_set_eq i lemma is_stopping_time.measurable_set_lt (hτ : is_stopping_time f τ) (i : ℕ) : measurable_set[f i] {x | τ x < i} := begin convert (hτ i).diff (hτ.measurable_set_eq i), ext, change τ x < i ↔ τ x ≤ i ∧ τ x ≠ i, rw lt_iff_le_and_ne, end lemma is_stopping_time.measurable_set_lt_le (hτ : is_stopping_time f τ) {i j : ℕ} (hle : i ≤ j) : measurable_set[f j] {x | τ x < i} := f.mono hle _ $ hτ.measurable_set_lt i lemma is_stopping_time_of_measurable_set_eq {f : filtration ℕ m} {τ : α → ℕ} (hτ : ∀ i, measurable_set[f i] {x | τ x = i}) : is_stopping_time f τ := begin intro i, rw show {x | τ x ≤ i} = ⋃ k ≤ i, {x | τ x = k}, by { ext, simp }, refine measurable_set.bUnion (set.countable_encodable _) (λ k hk, _), exact f.mono hk _ (hτ k), end lemma is_stopping_time_const {f : filtration ι m} (i : ι) : is_stopping_time f (λ x, i) := λ j, by simp end preorder namespace is_stopping_time lemma max [linear_order ι] {f : filtration ι m} {τ π : α → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ x, max (τ x) (π x)) := begin intro i, simp_rw [max_le_iff, set.set_of_and], exact (hτ i).inter (hπ i), end lemma min [linear_order ι] {f : filtration ι m} {τ π : α → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ x, min (τ x) (π x)) := begin intro i, simp_rw [min_le_iff, set.set_of_or], exact (hτ i).union (hπ i), end lemma add_const [add_group ι] [preorder ι] [covariant_class ι ι (function.swap (+)) (≤)] [covariant_class ι ι (+) (≤)] {f : filtration ι m} {τ : α → ι} (hτ : is_stopping_time f τ) {i : ι} (hi : 0 ≤ i) : is_stopping_time f (λ x, τ x + i) := begin intro j, simp_rw [← le_sub_iff_add_le], exact f.mono (sub_le_self j hi) _ (hτ (j - i)), end section preorder variables [preorder ι] {f : filtration ι m} /-- The associated σ-algebra with a stopping time. -/ protected def measurable_space {τ : α → ι} (hτ : is_stopping_time f τ) : measurable_space α := { measurable_set' := λ s, ∀ i : ι, measurable_set[f i] (s ∩ {x | τ x ≤ i}), measurable_set_empty := λ i, (set.empty_inter {x | τ x ≤ i}).symm ▸ @measurable_set.empty _ (f i), measurable_set_compl := λ s hs i, begin rw (_ : sᶜ ∩ {x | τ x ≤ i} = (sᶜ ∪ {x | τ x ≤ i}ᶜ) ∩ {x | τ x ≤ i}), { refine measurable_set.inter _ _, { rw ← set.compl_inter, exact (hs i).compl }, { exact hτ i} }, { rw set.union_inter_distrib_right, simp only [set.compl_inter_self, set.union_empty] } end, measurable_set_Union := λ s hs i, begin rw forall_swap at hs, rw set.Union_inter, exact measurable_set.Union (hs i), end } @[protected] lemma measurable_set {τ : α → ι} (hτ : is_stopping_time f τ) (s : set α) : measurable_set[hτ.measurable_space] s ↔ ∀ i : ι, measurable_set[f i] (s ∩ {x | τ x ≤ i}) := iff.rfl lemma measurable_space_mono {τ π : α → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (hle : τ ≤ π) : hτ.measurable_space ≤ hπ.measurable_space := begin intros s hs i, rw (_ : s ∩ {x | π x ≤ i} = s ∩ {x | τ x ≤ i} ∩ {x | π x ≤ i}), { exact (hs i).inter (hπ i) }, { ext, simp only [set.mem_inter_eq, iff_self_and, and.congr_left_iff, set.mem_set_of_eq], intros hle' _, exact le_trans (hle _) hle' }, end lemma measurable_space_le [encodable ι] {τ : α → ι} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {x | τ x ≤ i}) at hs, rw (_ : s = ⋃ i, s ∩ {x | τ x ≤ i}), { exact measurable_set.Union (λ i, f.le i _ (hs i)) }, { ext x, split; rw set.mem_Union, { exact λ hx, ⟨τ x, hx, le_rfl⟩ }, { rintro ⟨_, hx, _⟩, exact hx } } end section nat lemma measurable_set_eq_const {f : filtration ℕ m} {τ : α → ℕ} (hτ : is_stopping_time f τ) (i : ℕ) : measurable_set[hτ.measurable_space] {x | τ x = i} := begin rw hτ.measurable_set, intro j, by_cases i ≤ j, { rw (_ : {x | τ x = i} ∩ {x | τ x ≤ j} = {x | τ x = i}), { exact hτ.measurable_set_eq_le h }, { ext, simp only [set.mem_inter_eq, and_iff_left_iff_imp, set.mem_set_of_eq], rintro rfl, assumption } }, { rw (_ : {x | τ x = i} ∩ {x | τ x ≤ j} = ∅), { exact @measurable_set.empty _ (f j) }, { ext, simp only [set.mem_empty_eq, set.mem_inter_eq, not_and, not_le, set.mem_set_of_eq, iff_false], rintro rfl, rwa not_le at h } } end end nat end preorder section linear_order variable [linear_order ι] lemma measurable [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] {f : filtration ι m} {τ : α → ι} (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] τ := begin refine @measurable_of_Iic ι α _ _ _ hτ.measurable_space _ _ _ _ _, simp_rw [hτ.measurable_set, set.preimage, set.mem_Iic], intros i j, rw (_ : {x | τ x ≤ i} ∩ {x | τ x ≤ j} = {x | τ x ≤ linear_order.min i j}), { exact f.mono (min_le_right i j) _ (hτ (linear_order.min i j)) }, { ext, simp only [set.mem_inter_eq, iff_self, le_min_iff, set.mem_set_of_eq] } end end linear_order end is_stopping_time section linear_order /-- Given a map `u : ι → α → E`, its stopped value with respect to the stopping time `τ` is the map `x ↦ u (τ x) x`. -/ def stopped_value (u : ι → α → β) (τ : α → ι) : α → β := λ x, u (τ x) x variable [linear_order ι] /-- Given a map `u : ι → α → E`, the stopped process with respect to `τ` is `u i x` if `i ≤ τ x`, and `u (τ x) x` otherwise. Intuitively, the stopped process stops evolving once the stopping time has occured. -/ def stopped_process (u : ι → α → β) (τ : α → ι) : ι → α → β := λ i x, u (linear_order.min i (τ x)) x lemma stopped_process_eq_of_le {u : ι → α → β} {τ : α → ι} {i : ι} {x : α} (h : i ≤ τ x) : stopped_process u τ i x = u i x := by simp [stopped_process, min_eq_left h] lemma stopped_process_eq_of_ge {u : ι → α → β} {τ : α → ι} {i : ι} {x : α} (h : τ x ≤ i) : stopped_process u τ i x = u (τ x) x := by simp [stopped_process, min_eq_right h] -- We will need cadlag to generalize the following to continuous processes section nat open filtration variables {f : filtration ℕ m} {u : ℕ → α → β} {τ π : α → ℕ} lemma stopped_value_sub_eq_sum [add_comm_group β] (hle : τ ≤ π) : stopped_value u π - stopped_value u τ = λ x, (∑ i in finset.Ico (τ x) (π x), (u (i + 1) - u i)) x := begin ext x, rw [finset.sum_Ico_eq_sub _ (hle x), finset.sum_range_sub, finset.sum_range_sub], simp [stopped_value], end lemma stopped_value_sub_eq_sum' [add_comm_group β] (hle : τ ≤ π) {N : ℕ} (hbdd : ∀ x, π x ≤ N) : stopped_value u π - stopped_value u τ = λ x, (∑ i in finset.range (N + 1), set.indicator {x | τ x ≤ i ∧ i < π x} (u (i + 1) - u i)) x := begin rw stopped_value_sub_eq_sum hle, ext x, simp only [finset.sum_apply, finset.sum_indicator_eq_sum_filter], refine finset.sum_congr _ (λ _ _, rfl), ext i, simp only [finset.mem_filter, set.mem_set_of_eq, finset.mem_range, finset.mem_Ico], exact ⟨λ h, ⟨lt_trans h.2 (nat.lt_succ_iff.2 $ hbdd _), h⟩, λ h, h.2⟩ end section add_comm_monoid variables [add_comm_monoid β] lemma stopped_value_eq {N : ℕ} (hbdd : ∀ x, τ x ≤ N) : stopped_value u τ = λ x, (∑ i in finset.range (N + 1), set.indicator {x | τ x = i} (u i)) x := begin ext y, rw [stopped_value, finset.sum_apply, finset.sum_eq_single (τ y)], { rw set.indicator_of_mem, exact rfl }, { exact λ i hi hneq, set.indicator_of_not_mem hneq.symm _ }, { intro hy, rw set.indicator_of_not_mem, exact λ _, hy (finset.mem_range.2 $ lt_of_le_of_lt (hbdd _) (nat.lt_succ_self _)) } end lemma stopped_process_eq (n : ℕ) : stopped_process u τ n = set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.range n, set.indicator {a | τ a = i} (u i) := begin ext x, rw [pi.add_apply, finset.sum_apply], cases le_or_lt n (τ x), { rw [stopped_process_eq_of_le h, set.indicator_of_mem, finset.sum_eq_zero, add_zero], { intros m hm, rw finset.mem_range at hm, exact set.indicator_of_not_mem ((lt_of_lt_of_le hm h).ne.symm) _ }, { exact h } }, { rw [stopped_process_eq_of_ge (le_of_lt h), finset.sum_eq_single_of_mem (τ x)], { rw [set.indicator_of_not_mem, zero_add, set.indicator_of_mem], { exact rfl }, -- refl does not work { exact not_le.2 h } }, { rwa [finset.mem_range] }, { intros b hb hneq, rw set.indicator_of_not_mem, exact hneq.symm } }, end lemma adapted.stopped_process [measurable_space β] [has_measurable_add₂ β] (hu : adapted f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := begin intro i, rw stopped_process_eq, refine @measurable.add _ _ _ _ (f i) _ _ _ _ _, { refine (hu i).indicator _, convert measurable_set.union (hτ i).compl (hτ.measurable_set_eq i), ext x, change i ≤ τ x ↔ ¬ τ x ≤ i ∨ τ x = i, rw [not_le, le_iff_lt_or_eq, eq_comm] }, { refine @finset.measurable_sum' _ _ _ _ _ _ (f i) _ _ _, refine λ j hij, measurable.indicator _ _, { rw finset.mem_range at hij, exact measurable.le (f.mono hij.le) (hu j) }, { rw finset.mem_range at hij, refine f.mono hij.le _ _, convert hτ.measurable_set_eq j, } } end end add_comm_monoid section normed_group variables [measurable_space β] [normed_group β] [has_measurable_add₂ β] lemma measurable_stopped_process (hτ : is_stopping_time f τ) (hu : adapted f u) (n : ℕ) : measurable (stopped_process u τ n) := (hu.stopped_process hτ n).le (f.le _) lemma mem_ℒp_stopped_process {p : ℝ≥0∞} [borel_space β] {μ : measure α} (hτ : is_stopping_time f τ) (hu : ∀ n, mem_ℒp (u n) p μ) (n : ℕ) : mem_ℒp (stopped_process u τ n) p μ := begin rw stopped_process_eq, refine mem_ℒp.add _ _, { exact mem_ℒp.indicator (f.le n {a : α | n ≤ τ a} (hτ.measurable_set_ge n)) (hu n) }, { suffices : mem_ℒp (λ x, ∑ (i : ℕ) in finset.range n, {a : α | τ a = i}.indicator (u i) x) p μ, { convert this, ext1 x, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact f.le i {a : α | τ a = i} (hτ.measurable_set_eq i) }, end lemma integrable_stopped_process [borel_space β] {μ : measure α} (hτ : is_stopping_time f τ) (hu : ∀ n, integrable (u n) μ) (n : ℕ) : integrable (stopped_process u τ n) μ := begin simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_process hτ hu n, end lemma mem_ℒp_stopped_value {p : ℝ≥0∞} [borel_space β] {μ : measure α} (hτ : is_stopping_time f τ) (hu : ∀ n, mem_ℒp (u n) p μ) {N : ℕ} (hbdd : ∀ x, τ x ≤ N) : mem_ℒp (stopped_value u τ) p μ := begin rw stopped_value_eq hbdd, suffices : mem_ℒp (λ x, ∑ (i : ℕ) in finset.range (N + 1), {a : α | τ a = i}.indicator (u i) x) p μ, { convert this, ext1 x, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact f.le i {a : α | τ a = i} (hτ.measurable_set_eq i) end lemma integrable_stopped_value [borel_space β] {μ : measure α} (hτ : is_stopping_time f τ) (hu : ∀ n, integrable (u n) μ) {N : ℕ} (hbdd : ∀ x, τ x ≤ N) : integrable (stopped_value u τ) μ := begin simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_value hτ hu hbdd, end end normed_group end nat end linear_order end measure_theory
83ad0f9956bbbe84877c140c44ff310b4fc0882f
11e28114d9553ecd984ac4819661ffce3068bafe
/src/rule_table.lean
1f06b27066fd20986a701a562d0e63775f1e93ed
[ "MIT" ]
permissive
EdAyers/lean-subtask
9a26eb81f0c8576effed4ca94342ae1281445c59
04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b
refs/heads/master
1,586,516,665,621
1,558,701,948,000
1,558,701,948,000
160,983,035
4
1
null
null
null
null
UTF-8
Lean
false
false
7,777
lean
/- Author: E.W.Ayers © 2019 -/ import .table .rule_app .expr_zipper open tactic expr namespace robot /-- A __submatch__ is a rule `r` and a zipper on `r.lhs`. They represent fragments of the LHS to match against some given term. -/ @[derive decidable_eq] meta structure submatch := (r : rule) -- the original rule (z : expr.zipper) -- a zipper on `r.rhs` namespace submatch open tactic /-- [HACK] run_app does the same thing as `run` except that sometimes the unifier doesn't try to unify the function and argument separately. -/ meta def run_app : expr → submatch → tactic rule_app | e ⟨r,z⟩ := do (expr.app f a) ← pure e, (mrule, ms) ← rule_app.of_rule r, if ¬z.ctxt.empty then fail "not implemented when z contains bound variables" else do current@(expr.app f₂ a₂) ← pure $ expr.instantiate_vars z.current $ ms.reverse, -- current ← instantiate_mvars current, -- tactic.trace_m "submatch.run_app: " $ (e, z), -- wrap in a 'hypothetically'' to keep the old assignment table. -- this means that any mvars in `e` are never assigned. tactic.hypothetically' (do unify f₂ f, unify a₂ a, -- not allowed any typeclass instances or problems ← ms.mfilter (λ m, do y ← infer_type m, iscl ← is_class y, isprop ← is_prop y, pure $ if iscl || isprop then tt else ff ), tactic.set_goals problems, -- trace_state, all_goals (apply_instance <|> assumption), n ← num_goals, guard (n = 0), mrule.instantiate_mvars ) --trace_state, /--`run e s` attempts to unify `e` with the subterm of `s` and then returns a rule depending on fresh metavariables.-/ meta def run : expr → submatch → tactic rule_app | e ⟨r,z⟩ := do --e ← instantiate_mvars e, (ra, ms) ← rule_app.of_rule r, if ¬z.ctxt.empty then fail "not implemented when z contains bound variables" else do let current := expr.instantiate_vars z.current $ ms.reverse, current ← instantiate_mvars current, -- tactic.trace_m "submatch.run: " $ current, -- [FIXME] duplicate code with `run_app`. tactic.hypothetically' (do unify current e, -- [HACK] for some reason this can't unify `A ?m_1` and `?m_2 ?m_3`? Current fix is `run_app`. --trace_state, ra.instantiate_mvars ) meta def to_rule_app : submatch → tactic rule_app |⟨r,z⟩ := do ⟨ra,_⟩ ← rule_app.of_rule r, rule_app.head_rewrite ra z meta instance : has_to_tactic_format (submatch) := ⟨λ ⟨r,z⟩, pure (λ pr pz, "{" ++ pr ++ "," ++ format.line ++ pz ++ " }") <*> tactic.pp r <*> tactic.pp z⟩ end submatch meta structure rule_table := (head_table : tabledict name rule) (submatch_table : listdict name submatch) namespace rule_table meta def empty : rule_table := {head_table := ∅, submatch_table := ∅} meta def get_key : expr → name |(expr.app f a) := if f.is_var || expr.is_mvar f || f.is_local_constant then `rule_table.app else get_key f |(expr.const n _) := n |(expr.var n) := `rule_table.wildcard |e := `rule_table.default meta def map_head_table (f : tabledict name rule → tabledict name rule) : rule_table → rule_table |rt := {rt with head_table := f rt.head_table} meta def insert : rule → rule_table → tactic rule_table | r {head_table:=ht, submatch_table := st} := do ppr ← pp r, st ← zipper.traverse_proper (λ st z, pure $ listdict.insert (get_key z.current) (submatch.mk r z) st) st $ zipper.zip r.rhs, pure { head_table := tabledict.insert (get_key r.lhs) r ht , submatch_table := st } /-- Take each rule in r₁ and insert to r₂. -/ meta def join (r₁ r₂ : rule_table) : tactic rule_table := tabledict.mfold (λ rt _ r, insert r rt) r₂ $ head_table $ r₁ meta def joins (l : list rule_table) :tactic rule_table := list.mfoldl (λ acc rt, join rt acc) (rule_table.empty) l meta def of_rules : list rule → tactic rule_table := list.mfoldl (function.swap insert) empty meta def rules : rule_table → list rule := tabledict.to_list ∘ rule_table.head_table meta def of_names (ns : list name) : tactic rule_table := do rs ← ns.mmap rule.of_name, revs ← list.mchoose (λ r, do ic ← rule.is_commuter r, if ic then failure else rule.flip r) rs, of_rules $ rs ++ revs private meta def get_head_rewrites : name → rule_table → table rule | k {head_table := ht, ..} := ht.get k meta structure rewrites_config := (wilds := ff) -- setting wilds causes inclusion of rules such as `?x = ?x * 1` where the lhs can be anything. -- This slows things down substantially -- [TODO] these 'wild' rules are handled by their own system. -- [TODO] optimise so that there are some type/typeclass checks on it. -- (annihilators := ff) [TODO] meta def head_rewrites (lhs : expr) (rt : rule_table) (cfg : rewrites_config := {}) : (tactic $ list rule_app) := do let k := get_key lhs, let wilds := if cfg.wilds then get_head_rewrites `rule_table.wildcard rt else ∅, let keyed := get_head_rewrites k rt, let t := wilds ∪ keyed, -- kpp ← pp k, tpp ← pp t, -- trace $ ("getting key ":format) ++ kpp ++ " with rules " ++ tpp, t.mfold (λ acc r, (do ppr ← to_string <$> pp r, -- tactic.trace_m "hr: " $ ppr, ra ← rule_app.rule_rewrite r lhs, pure $ ra :: acc ) <|> pure acc ) [] -- meta def head_rewrites_rhs (rhs : expr) (rt : rule_table) (cfg : rewrites_config := {}) : (tactic $ list rule) := do -- head_rewrites rhs rt >>= list.mmap rule.flip private meta def rewrites_aux (rt : rule_table) (cfg : rewrites_config) : zipper → list rule_app → tactic (list rule_app) |z acc := do ppz ← to_string <$> pp z, hrs ← -- timetac ("head_rewrites: " ++ ppz) $ head_rewrites z.current rt cfg, -- tactic.trace_m "rewrites_aux: " $ hrs, hrs ← list.mchoose (λ rw, rule_app.head_rewrite rw z) hrs, acc ← pure $ hrs ++ acc, ⟨f,children⟩ ← z.down_proper, acc ← children.mfoldl (λ acc z, rewrites_aux z acc) acc, pure acc -- [TODO] wildcard moves should have their own section, since one is constructed for each node in the tree. -- [TODO] similarly, anti-annihilator moves (moves which have metas after matching) should be put in their own section. meta def rewrites (lhs : expr) (rt : rule_table) (cfg : rewrites_config := {}) : (tactic $ list rule_app) := rewrites_aux rt cfg (zipper.zip lhs) [] meta instance : has_to_tactic_format rule_table := ⟨tactic.pp ∘ head_table⟩ /--`submatch e rt` finds rules such that the rhs of the rule contains `e`-/ meta def submatch : expr → rule_table → tactic (list rule_app) | e rt := do let key := get_key e, let submatches := rt.submatch_table.get key, -- tactic.trace_m "submatch: " $ submatches, if (key = `rule_table.app) then list.mchoose (robot.submatch.run_app e) submatches else list.mchoose (robot.submatch.run e) submatches meta def submatch_lhs : expr → rule_table → tactic(list rule_app) | lhs rt := do rs ← submatch lhs rt, pure rs -- rs.mmap rule_app.flip end rule_table end robot
462eff8bedaf071a258a9c0a029e09e6e6704f98
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/limits/opposites.lean
bf8da886991a3626c7b5a9497700947d0e7ddc66
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
4,525
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Floris van Doorn -/ import category_theory.limits.shapes.products import category_theory.discrete_category universes v u open category_theory open category_theory.functor open opposite namespace category_theory.limits variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] variable (F : J ⥤ Cᵒᵖ) /-- If `F.left_op : Jᵒᵖ ⥤ C` has a chosen colimit, we can construct a chosen limit for `F : J ⥤ Cᵒᵖ`. -/ def has_limit_of_has_colimit_left_op [has_colimit F.left_op] : has_limit F := { cone := cone_of_cocone_left_op (colimit.cocone F.left_op), is_limit := { lift := λ s, (colimit.desc F.left_op (cocone_left_op_of_cone s)).op, fac' := λ s j, begin rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, ←op_comp, colimit.ι_desc, cocone_left_op_of_cone_ι_app, has_hom.hom.op_unop], refl, end, uniq' := λ s m w, begin -- It's a pity we can't do this automatically. -- Usually something like this would work by limit.hom_ext, -- but the opposites get in the way of this firing. have u := (colimit.is_colimit F.left_op).uniq (cocone_left_op_of_cone s) (m.unop), convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u, intro j, rw [cocone_left_op_of_cone_ι_app, colimit.cocone_ι], convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w, rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, has_hom.hom.unop_op], refl, end } } /-- If `C` has chosen colimits of shape `Jᵒᵖ`, we can construct chosen limits in `Cᵒᵖ` of shape `J`. -/ def has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jᵒᵖ C] : has_limits_of_shape J Cᵒᵖ := { has_limit := λ F, has_limit_of_has_colimit_left_op F } local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape /-- If `C` has chosen colimits, we can construct chosen limits for `Cᵒᵖ`. -/ def has_limits_op_of_has_colimits [has_colimits C] : has_limits Cᵒᵖ := { has_limits_of_shape := λ J 𝒥, by { resetI, apply_instance } } /-- If `F.left_op : Jᵒᵖ ⥤ C` has a chosen limit, we can construct a chosen colimit for `F : J ⥤ Cᵒᵖ`. -/ def has_colimit_of_has_limit_left_op [has_limit F.left_op] : has_colimit F := { cocone := cocone_of_cone_left_op (limit.cone F.left_op), is_colimit := { desc := λ s, (limit.lift F.left_op (cone_left_op_of_cocone s)).op, fac' := λ s j, begin rw [cocone_of_cone_left_op_ι_app, limit.cone_π, ←op_comp, limit.lift_π, cone_left_op_of_cocone_π_app, has_hom.hom.op_unop], refl, end, uniq' := λ s m w, begin have u := (limit.is_limit F.left_op).uniq (cone_left_op_of_cocone s) (m.unop), convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u, intro j, rw [cone_left_op_of_cocone_π_app, limit.cone_π], convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w, rw [cocone_of_cone_left_op_ι_app, limit.cone_π, has_hom.hom.unop_op], refl, end } } /-- If `C` has chosen colimits of shape `Jᵒᵖ`, we can construct chosen limits in `Cᵒᵖ` of shape `J`. -/ def has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jᵒᵖ C] : has_colimits_of_shape J Cᵒᵖ := { has_colimit := λ F, has_colimit_of_has_limit_left_op F } local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape /-- If `C` has chosen limits, we can construct chosen colimits for `Cᵒᵖ`. -/ def has_colimits_op_of_has_limits [has_limits C] : has_colimits Cᵒᵖ := { has_colimits_of_shape := λ J 𝒥, by { resetI, apply_instance } } variables (X : Type v) /-- If `C` has products indexed by `X`, then `Cᵒᵖ` has coproducts indexed by `X`. -/ def has_coproducts_opposite [has_products_of_shape X C] : has_coproducts_of_shape X Cᵒᵖ := begin haveI : has_limits_of_shape (discrete X)ᵒᵖ C := has_limits_of_shape_of_equivalence (discrete.opposite X).symm, apply_instance end /-- If `C` has coproducts indexed by `X`, then `Cᵒᵖ` has products indexed by `X`. -/ def has_products_opposite [has_coproducts_of_shape X C] : has_products_of_shape X Cᵒᵖ := begin haveI : has_colimits_of_shape (discrete X)ᵒᵖ C := has_colimits_of_shape_of_equivalence (discrete.opposite X).symm, apply_instance end end category_theory.limits
8395e1a172e95abd85d758a275c1ecc915d6e796
d4df7c538bbc0b06771d7b7a6f46fbadebb8c5eb
/src/monad_transformers/monad_trans.lean
c88e6615ff55249bed5b8e68fdaac8bc3cc6919c
[]
no_license
breakerzirconia/LeanTransformers
11bb924b59ac589d0c6b39586d27cccc8f9e939c
3c52441b8990bab7d8cf1817df6e04f657a14e1c
refs/heads/main
1,682,610,526,027
1,620,477,129,000
1,620,477,129,000
365,507,838
0
0
null
null
null
null
UTF-8
Lean
false
false
124
lean
class monad_trans (t : (Type → Type) → Type → Type) := (lift {m : Type → Type} [monad m] {a : Type} : m a → t m a)
f0bfddc7ceba54df0ba0570f95d030349afbfc4c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/multiset/nodup.lean
6bc678fa92323115a87d10911b3d96ddab875f8f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
9,523
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.multiset.powerset import data.multiset.range /-! # The `nodup` predicate for multisets without duplicate elements. -/ namespace multiset open list variables {α β γ : Type*} /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext p.nodup_iff) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm lemma nodup_iff_ne_cons_cons {s : multiset α} : s.nodup ↔ ∀ a t, s ≠ a :: a :: t := nodup_iff_le.trans ⟨λ h a t s_eq, h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))), λ h a le, let ⟨t, s_eq⟩ := le_iff_exists_add.mp le in h a t (by rwa [cons_add, cons_add, zero_add] at s_eq )⟩ theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma nodup_iff_pairwise {α} {s : multiset α} : nodup s ↔ pairwise (≠) s := quotient.induction_on s $ λ l, (pairwise_coe_iff_pairwise (by exact λ a b, ne.symm)).symm lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (nodup_ext ht (nodup_map (show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy)) (nodup_attach.2 hs))).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _) end multiset
10cbb43476eaa7b15f18327dde305a0752853d15
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0314.lean
14fa0d36dc8af9233731557ceb674f2c6d6a80c0
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
115
lean
variables p q : Prop example (hpq : p → q) (hnq: ¬q) : ¬p := assume hp : p, show false, from hnq (hpq hp)
544eadd3861968b5728452488c293d84ce89aa6b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1218.lean
67a132460d7c967ed16969e6ae4e0174a9128bb7
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
88
lean
example (h : false) : "hello" = "goodbye" := begin try {reflexivity}, contradiction end
e60f66f5761b5fa592962a9dd884423b73e27cd4
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Message.lean
d363ef89bddebaaace74b33af1cad757fbed1884
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,113
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Message Type used by the Lean frontend -/ import Lean.Data.Position import Lean.Data.OpenDecl import Lean.Syntax import Lean.MetavarContext import Lean.Environment import Lean.Util.PPExt namespace Lean def mkErrorStringWithPos (fileName : String) (pos : Position) (msg : String) (endPos : Option Position := none) : String := let endPos := match endPos with | some endPos => s!"-{endPos.line}:{endPos.column}" | none => "" s!"{fileName}:{pos.line}:{pos.column}{endPos}: {msg}" inductive MessageSeverity where | information | warning | error deriving Inhabited, BEq structure MessageDataContext where env : Environment mctx : MetavarContext lctx : LocalContext opts : Options structure NamingContext where currNamespace : Name openDecls : List OpenDecl /- Structure message data. We use it for reporting errors, trace messages, etc. -/ inductive MessageData where | ofFormat : Format → MessageData | ofSyntax : Syntax → MessageData | ofExpr : Expr → MessageData | ofLevel : Level → MessageData | ofName : Name → MessageData | ofGoal : MVarId → MessageData /- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/ | withContext : MessageDataContext → MessageData → MessageData | withNamingContext : NamingContext → MessageData → MessageData /- Lifted `Format.nest` -/ | nest : Nat → MessageData → MessageData /- Lifted `Format.group` -/ | group : MessageData → MessageData /- Lifted `Format.compose` -/ | compose : MessageData → MessageData → MessageData /- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions. Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/ | tagged : Name → MessageData → MessageData | node : Array MessageData → MessageData deriving Inhabited namespace MessageData def nil : MessageData := ofFormat Format.nil def isNil : MessageData → Bool | ofFormat Format.nil => true | _ => false def isNest : MessageData → Bool | nest _ _ => true | _ => false def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := { env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts, currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls } partial def formatAux : NamingContext → Option MessageDataContext → MessageData → IO Format | _, _, ofFormat fmt => pure fmt | _, _, ofLevel u => pure $ fmt u | _, _, ofName n => pure $ fmt n | nCtx, some ctx, ofSyntax s => ppTerm (mkPPContext nCtx ctx) s -- HACK: might not be a term | _, none, ofSyntax s => pure $ s.formatStx | _, none, ofExpr e => pure $ format (toString e) | nCtx, some ctx, ofExpr e => ppExpr (mkPPContext nCtx ctx) e | _, none, ofGoal mvarId => pure $ "goal " ++ format (mkMVar mvarId) | nCtx, some ctx, ofGoal mvarId => ppGoal (mkPPContext nCtx ctx) mvarId | nCtx, _, withContext ctx d => formatAux nCtx ctx d | _, ctx, withNamingContext nCtx d => formatAux nCtx ctx d | nCtx, ctx, tagged cls d => do let d ← formatAux nCtx ctx d; pure $ Format.sbracket (format cls) ++ " " ++ d | nCtx, ctx, nest n d => Format.nest n <$> formatAux nCtx ctx d | nCtx, ctx, compose d₁ d₂ => do let d₁ ← formatAux nCtx ctx d₁; let d₂ ← formatAux nCtx ctx d₂; pure $ d₁ ++ d₂ | nCtx, ctx, group d => Format.group <$> formatAux nCtx ctx d | nCtx, ctx, node ds => Format.nest 2 <$> ds.foldlM (fun r d => do let d ← formatAux nCtx ctx d; pure $ r ++ Format.line ++ d) Format.nil protected def format (msgData : MessageData) : IO Format := formatAux { currNamespace := Name.anonymous, openDecls := [] } none msgData protected def toString (msgData : MessageData) : IO String := do let fmt ← msgData.format pure $ toString fmt instance : Append MessageData := ⟨compose⟩ instance : Coe String MessageData := ⟨ofFormat ∘ format⟩ instance : Coe Format MessageData := ⟨ofFormat⟩ instance : Coe Level MessageData := ⟨ofLevel⟩ instance : Coe Expr MessageData := ⟨ofExpr⟩ instance : Coe Name MessageData := ⟨ofName⟩ instance : Coe Syntax MessageData := ⟨ofSyntax⟩ instance : Coe (Option Expr) MessageData := ⟨fun o => match o with | none => "none" | some e => ofExpr e⟩ partial def arrayExpr.toMessageData (es : Array Expr) (i : Nat) (acc : MessageData) : MessageData := if h : i < es.size then let e := es.get ⟨i, h⟩; let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e; toMessageData es (i+1) acc else acc ++ "]" instance : Coe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩ def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length $ l ++ f ++ r) def paren (f : MessageData) : MessageData := bracket "(" f ")" def sbracket (f : MessageData) : MessageData := bracket "[" f "]" def joinSep : List MessageData → MessageData → MessageData | [], sep => Format.nil | [a], sep => a | a::as, sep => a ++ sep ++ joinSep as sep def ofList: List MessageData → MessageData | [] => "[]" | xs => sbracket $ joinSep xs (ofFormat "," ++ Format.line) def ofArray (msgs : Array MessageData) : MessageData := ofList msgs.toList instance : Coe (List MessageData) MessageData := ⟨ofList⟩ instance : Coe (List Expr) MessageData := ⟨fun es => ofList $ es.map ofExpr⟩ end MessageData structure Message where fileName : String pos : Position endPos : Option Position := none severity : MessageSeverity := MessageSeverity.error caption : String := "" data : MessageData deriving Inhabited namespace Message protected def toString (msg : Message) (includeEndPos := false) : IO String := do let mut str ← msg.data.toString let endPos := if includeEndPos then msg.endPos else none unless msg.caption == "" do str := msg.caption ++ ":\n" ++ str match msg.severity with | MessageSeverity.information => pure () | MessageSeverity.warning => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "warning: " ++ str | MessageSeverity.error => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "error: " ++ str if str.isEmpty || str.back != '\n' then str := str ++ "\n" return str end Message structure MessageLog where msgs : Std.PersistentArray Message := {} deriving Inhabited namespace MessageLog def empty : MessageLog := ⟨{}⟩ def isEmpty (log : MessageLog) : Bool := log.msgs.isEmpty def add (msg : Message) (log : MessageLog) : MessageLog := ⟨log.msgs.push msg⟩ protected def append (l₁ l₂ : MessageLog) : MessageLog := ⟨l₁.msgs ++ l₂.msgs⟩ instance : Append MessageLog := ⟨MessageLog.append⟩ def hasErrors (log : MessageLog) : Bool := log.msgs.any fun m => match m.severity with | MessageSeverity.error => true | _ => false def errorsToWarnings (log : MessageLog) : MessageLog := { msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { m with severity := MessageSeverity.warning } | _ => m) } def getInfoMessages (log : MessageLog) : MessageLog := { msgs := log.msgs.filter fun m => match m.severity with | MessageSeverity.information => true | _ => false } def forM {m : Type → Type} [Monad m] (log : MessageLog) (f : Message → m Unit) : m Unit := log.msgs.forM f def toList (log : MessageLog) : List Message := (log.msgs.foldl (fun acc msg => msg :: acc) []).reverse end MessageLog def MessageData.nestD (msg : MessageData) : MessageData := MessageData.nest 2 msg def indentD (msg : MessageData) : MessageData := MessageData.nestD (Format.line ++ msg) def indentExpr (e : Expr) : MessageData := indentD e class AddMessageContext (m : Type → Type) where addMessageContext : MessageData → m MessageData export AddMessageContext (addMessageContext) instance (m n) [MonadLift m n] [AddMessageContext m] : AddMessageContext n where addMessageContext := fun msg => liftM (addMessageContext msg : m _) def addMessageContextPartial {m} [Monad m] [MonadEnv m] [MonadOptions m] (msgData : MessageData) : m MessageData := do let env ← getEnv let opts ← getOptions pure $ MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msgData def addMessageContextFull {m} [Monad m] [MonadEnv m] [MonadMCtx m] [MonadLCtx m] [MonadOptions m] (msgData : MessageData) : m MessageData := do let env ← getEnv let mctx ← getMCtx let lctx ← getLCtx let opts ← getOptions pure $ MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msgData class ToMessageData (α : Type) where toMessageData : α → MessageData export ToMessageData (toMessageData) def stringToMessageData (str : String) : MessageData := let lines := str.split (· == '\n') let lines := lines.map (MessageData.ofFormat ∘ fmt) MessageData.joinSep lines (MessageData.ofFormat Format.line) instance {α} [ToFormat α] : ToMessageData α := ⟨MessageData.ofFormat ∘ fmt⟩ instance : ToMessageData Expr := ⟨MessageData.ofExpr⟩ instance : ToMessageData Level := ⟨MessageData.ofLevel⟩ instance : ToMessageData Name := ⟨MessageData.ofName⟩ instance : ToMessageData String := ⟨stringToMessageData⟩ instance : ToMessageData Syntax := ⟨MessageData.ofSyntax⟩ instance : ToMessageData Format := ⟨MessageData.ofFormat⟩ instance : ToMessageData MessageData := ⟨id⟩ instance {α} [ToMessageData α] : ToMessageData (List α) := ⟨fun as => MessageData.ofList $ as.map toMessageData⟩ instance {α} [ToMessageData α] : ToMessageData (Array α) := ⟨fun as => toMessageData as.toList⟩ instance {α} [ToMessageData α] : ToMessageData (Option α) := ⟨fun | none => "none" | some e => "some (" ++ toMessageData e ++ ")"⟩ instance : ToMessageData (Option Expr) := ⟨fun | none => "<not-available>" | some e => toMessageData e⟩ syntax:max "m!" interpolatedStr(term) : term macro_rules | `(m! $interpStr) => do interpStr.expandInterpolatedStr (← `(MessageData)) (← `(toMessageData)) namespace KernelException private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData := MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg def toMessageData (e : KernelException) (opts : Options) : MessageData := match e with | unknownConstant env constName => mkCtx env {} opts m!"(kernel) unknown constant '{constName}'" | alreadyDeclared env constName => mkCtx env {} opts m!"(kernel) constant has already been declared '{constName}'" | declTypeMismatch env decl givenType => let process (n : Name) (expectedType : Expr) : MessageData := m!"(kernel) declaration type mismatch, '{n}' has type{indentExpr givenType}\nbut it is expected to have type{indentExpr expectedType}"; match decl with | Declaration.defnDecl { name := n, type := type, .. } => process n type | Declaration.thmDecl { name := n, type := type, .. } => process n type | _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information | declHasMVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has metavariables '{constName}'" | declHasFVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has free variables '{constName}'" | funExpected env lctx e => mkCtx env lctx opts m!"(kernel) function expected{indentExpr e}" | typeExpected env lctx e => mkCtx env lctx opts m!"(kernel) type expected{indentExpr e}" | letTypeMismatch env lctx n _ _ => mkCtx env lctx opts m!"(kernel) let-declaration type mismatch '{n}'" | exprTypeMismatch env lctx e _ => mkCtx env lctx opts m!"(kernel) type mismatch at{indentExpr e}" | appTypeMismatch env lctx e fnType argType => mkCtx env lctx opts m!"application type mismatch{indentExpr e}\nargument has type{indentExpr argType}\nbut function has type{indentExpr fnType}" | invalidProj env lctx e => mkCtx env lctx opts m!"(kernel) invalid projection{indentExpr e}" | other msg => m!"(kernel) {msg}" end KernelException end Lean
3ab62fb5649a3332dab378f941a5179c5f0a48de
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/macroElabRulesIssue1.lean
f511da52e6fd22ebd622a78055d7bde05d1549ac
[ "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
275
lean
import Lean open Lean Elab Tactic syntax "Foo" (ident <|> num) : tactic elab_rules : tactic | `(tactic| Foo $x:num) => logInfo "num" macro_rules | `(tactic| Foo $x:ident) => `(tactic| trace "ident") example : True := by Foo x -- should not fail trivial
067cf4af33320e861771c0350bbd8c5a72b7cc34
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/basic_monitor1.lean
b38e7244fa709ddd17daee66017a74baa9d8d768
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
243
lean
@[vm_monitor] meta def basic_monitor : vm_monitor nat := { init := 0, step := λ s, return (trace ("step " ++ s^.to_string) (s+1)) >> failure } set_option debugger true def f : nat → nat | 0 := 0 | (a+1) := f a #eval trace "a" (f 4)
a2959c6a75886a1bbfd36e3e1b14a5944dd0d421
4376c25f060c13471bb89cdb12aeac1d53e53876
/src/espaces-metriques/test.lean
f4a6bd49b85958600d26ec5bcdea8cfca1e36d0b
[ "MIT" ]
permissive
RaitoBezarius/projet-maths-lean
8fa7df563d64c256561ab71893c523fc1424b85c
42356e980e021a20c3468f5ca1639fec01bb934f
refs/heads/master
1,613,002,128,339
1,589,289,282,000
1,589,289,282,000
244,431,534
0
1
MIT
1,584,312,574,000
1,583,169,883,000
TeX
UTF-8
Lean
false
false
3,570
lean
import data.real.basic class metric_space (X : Type*) := (d : X → X → ℝ) (d_pos : ∀ x y, d x y ≥ 0) (presep : ∀ x y, x=y → d x y = 0) (sep : ∀ x y, d x y = 0 → x = y) (sym : ∀ x y, d x y = d y x) (triangle : ∀ x y z, d x z ≤ d x y + d y z) class premetric_space (X : Type*) := (d : X → X → ℝ) (d_pos : ∀ x y, d x y ≥ 0) (presep : ∀ x y, x=y → d x y = 0) (sym : ∀ x y, d x y = d y x) (triangle : ∀ x y z, d x z ≤ d x y + d y z) instance real.metric_space: metric_space ℝ := { d := sorry, d_pos := sorry, presep := sorry, sep := sorry, sym := sorry, triangle := sorry } open_locale classical noncomputable theory section test open metric_space variables {X: Type*} [metric_space X] def is_cauchy (x: ℕ → X) := ∀ ε > 0, ∃ N, ∀ p ≥ N, ∀ q ≥ N, ((d (x p) (x q)) < ε) def converge (x: ℕ → X) (l : X) := ∀ ε > 0, ∃ N, ∀ n ≥ N, ((d l (x n)) < ε) def complete (T: Type) [metric_space T] := ∀ x : ℕ → T, is_cauchy x → ∃ l : T, converge x l lemma R_is_complete: complete ℝ := sorry def cauchy_seqs (X : Type*) [metric_space X] := { f : ℕ → X // is_cauchy f } def cauchy.diff (x : ℕ → X) (y : ℕ → X) : ℕ → ℝ := λ n : ℕ, d (x n) (y n) def cauchy.cauchy_of_diff (x y : ℕ → X) (h1 : is_cauchy x) (h2 : is_cauchy y): is_cauchy (cauchy.diff x y) := sorry def cauchy.limit (x: ℕ → ℝ) (H: is_cauchy x): ℝ := classical.some (R_is_complete x H) def cauchy.dist (T: Type*) [metric_space T] (x y: cauchy_seqs T): ℝ := cauchy.limit (cauchy.diff x.val y.val) (cauchy.cauchy_of_diff x.val y.val x.property y.property) instance pre_ecart.premetrique (X: Type*) [metric_space X]: premetric_space (cauchy_seqs X) := { d := cauchy.dist X, d_pos := sorry, presep := sorry, sym := sorry, triangle := sorry } def cauchy.cong (T: Type*) [metric_space T] (x y: cauchy_seqs T): Prop := cauchy.dist T x y = 0 instance cauchy.setoid (X : Type*) [metric_space X] : setoid (cauchy_seqs X) := { r := cauchy.cong X, iseqv := sorry } local attribute [instance] cauchy.setoid def completion (X : Type*) [metric_space X] : Type* := quotient (cauchy.setoid X) def completion.dist_soundness (T: Type*) [metric_space T]: ∀ x₁ x₂: cauchy_seqs T, ∀ y₁ y₂: cauchy_seqs T, (x₁ ≈ y₁) → (x₂ ≈ y₂) → (cauchy.dist T x₁ x₂ = cauchy.dist T y₁ y₂) := begin intros x y z t Hxz Hyt, change (cauchy.dist T x z = 0) at Hxz, change (cauchy.dist T y t = 0) at Hyt, apply le_antisymm, calc cauchy.dist T x y ≤ cauchy.dist T x z + cauchy.dist T z y : premetric_space.triangle x z y ... ≤ cauchy.dist T x z + (cauchy.dist T z t + cauchy.dist T t y) : add_le_add_left (premetric_space.triangle z t y) _ ... = cauchy.dist T z t + cauchy.dist T y t : by rw [Hxz, zero_add, premetric_space.sym t y] ... = cauchy.dist T z t : by rw Hyt, calc cauchy.dist T z t ≤ cauchy.dist T z x + cauchy.dist T x t : premetric_space.triangle z x t ... ≤ cauchy.dist T z x + (cauchy.dist T x y + cauchy.dist T y t) : add_le_add_left (premetric_space.triangle x y t) _ ... = cauchy.dist T x z + cauchy.dist T x y : by rw [Hyt, add_zero, premetric_space.sym z x] ... = cauchy.dist T x y : by rw Hxz, end def completion.dist (T: Type*) [metric_space T] (x y: completion T): ℝ := quotient.lift₂ (cauchy.dist T) (completion.dist_soundness T) x y instance completion.metric_space (X: Type*) [metric_space X]: metric_space (completion X) := { d := completion.dist X, d_pos := sorry, -- etc } end test
310e10b3feb8a3f0c58b9e87aa3c86809ee04390
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_topology/topological_simplex.lean
9b937cb5132641a67b77e7d7db94f66e54ebda57
[ "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,133
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Adam Topaz -/ import algebraic_topology.simplex_category import topology.category.Top.basic import topology.instances.nnreal /-! # Topological simplices We define the natural functor from `simplex_category` to `Top` sending `[n]` to the topological `n`-simplex. This is used to define `Top.to_sSet` in `algebraic_topology.simpliciaL_set`. -/ noncomputable theory namespace simplex_category open_locale simplicial nnreal big_operators classical local attribute [instance] category_theory.concrete_category.has_coe_to_sort category_theory.concrete_category.has_coe_to_fun /-- The topological simplex associated to `x : simplex_category`. This is the object part of the functor `simplex_category.to_Top`. -/ def to_Top_obj (x : simplex_category) := { f : x → ℝ≥0 | ∑ i, f i = 1 } instance (x : simplex_category) : has_coe_to_fun x.to_Top_obj (λ _, x → ℝ≥0) := ⟨λ f, (f : x → ℝ≥0)⟩ @[ext] lemma to_Top_obj.ext {x : simplex_category} (f g : x.to_Top_obj) : (f : x → ℝ≥0) = g → f = g := subtype.ext /-- A morphism in `simplex_category` induces a map on the associated topological spaces. -/ def to_Top_map {x y : simplex_category} (f : x ⟶ y) : x.to_Top_obj → y.to_Top_obj := λ g, ⟨λ i, ∑ j in (finset.univ.filter (λ k, f k = i)), g j, begin simp only [finset.filter_congr_decidable, finset.sum_congr, to_Top_obj, set.mem_set_of], rw ← finset.sum_bUnion, convert g.2, { rw finset.eq_univ_iff_forall, intros i, rw finset.mem_bUnion, exact ⟨f i, by simp, by simp⟩ }, { intros i hi j hj h e he, apply h, simp only [true_and, finset.inf_eq_inter, finset.mem_univ, finset.mem_filter, finset.mem_inter] at he, rw [← he.1, ← he.2] } end⟩ @[simp] lemma coe_to_Top_map {x y : simplex_category} (f : x ⟶ y) (g : x.to_Top_obj) (i : y) : to_Top_map f g i = ∑ j in (finset.univ.filter (λ k, f k = i)), g j := rfl @[continuity] lemma continuous_to_Top_map {x y : simplex_category} (f : x ⟶ y) : continuous (to_Top_map f) := continuous.subtype_mk (continuous_pi $ λ i, continuous_finset_sum _ $ λ j hj, (continuous_apply _).comp continuous_subtype_val) _ /-- The functor associating the topological `n`-simplex to `[n] : simplex_category`. -/ @[simps] def to_Top : simplex_category ⥤ Top := { obj := λ x, Top.of x.to_Top_obj, map := λ x y f, ⟨to_Top_map f⟩, map_id' := begin intros x, ext f i : 3, change (finset.univ.filter (λ k, k = i)).sum _ = _, simp [finset.sum_filter] end, map_comp' := begin intros x y z f g, ext h i : 3, dsimp, erw ← finset.sum_bUnion, apply finset.sum_congr, { exact finset.ext (λ j, ⟨λ hj, by simpa using hj, λ hj, by simpa using hj⟩) }, { tauto }, { intros j hj k hk h e he, apply h, simp only [true_and, finset.inf_eq_inter, finset.mem_univ, finset.mem_filter, finset.mem_inter] at he, rw [← he.1, ← he.2] }, end } end simplex_category
f4b33ae70bb9d83340a37654e0ee0d5644453d2c
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Elab/Macro.lean
722e78d3fe5092b08997eebbd702defb779f33f8
[ "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
1,955
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.MacroArgUtil namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command @[builtinMacro Lean.Parser.Command.macro] def expandMacro : Macro | `($[$doc?:docComment]? $attrKind:attrKind macro$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $head:macroArg $args:macroArg* : $cat => $rhs) => do let prio ← evalOptPrio prio? -- build parser let stxPart ← expandMacroArgIntoSyntaxItem head let stxParts ← args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build macro rules let patHead ← expandMacroArgIntoPattern head let patArgs ← args.mapM expandMacroArgIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node ((← Macro.getCurrNamespace) ++ name) (#[patHead] ++ patArgs) let stxCmd ← `($[$doc?:docComment]? $attrKind:attrKind syntax$[:$prec?]? (name := $(← mkIdentFromRef name)) (priority := $(quote prio)) $[$stxParts]* : $cat) let macroRulesCmd ← if rhs.getArgs.size == 1 then -- `rhs` is a `term` let rhs := rhs[0] `($[$doc?:docComment]? macro_rules | `($pat) => $rhs) else -- `rhs` is of the form `` `( $body ) `` let rhsBody := rhs[1] `($[$doc?:docComment]? macro_rules | `($pat) => `($rhsBody)) return mkNullNode #[stxCmd, macroRulesCmd] | _ => Macro.throwUnsupported end Lean.Elab.Command
a4ca1f37998cf76a833ed423e9cd4e2e6e0af149
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Macro.lean
93059a6c35a659568ea41448d0e866b0e22b808e
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,159
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.MacroArgUtil namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command @[builtin_command_elab Lean.Parser.Command.macro] def elabMacro : CommandElab | `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind macro%$tk$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $args:macroArg* : $cat => $rhs) => -- exclude command prefix from synthetic position used for e.g. jumping to the macro definition withRef (mkNullNode #[tk, rhs]) do let prio ← liftMacroM <| evalOptPrio prio? let (stxParts, patArgs) := (← args.mapM expandMacroArg).unzip -- name let name ← match name? with | some name => pure name.getId | none => addMacroScopeIfLocal (← liftMacroM <| mkNameFromParserSyntax cat.getId (mkNullNode stxParts)) attrKind /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := ⟨mkNode ((← getCurrNamespace) ++ name) patArgs⟩ let stxCmd ← `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind syntax$[:$prec?]? (name := $(name?.getD (mkIdentFrom tk name (canonical := true)))) (priority := $(quote prio):num) $[$stxParts]* : $cat) let rhs := rhs.raw let macroRulesCmd ← if rhs.getArgs.size == 1 then -- `rhs` is a `term` let rhs := ⟨rhs[0]⟩ `($[$doc?:docComment]? macro_rules | `($pat) => Functor.map (@TSyntax.raw $(quote cat.getId.eraseMacroScopes)) $rhs) else -- TODO(gabriel): remove after bootstrap -- `rhs` is of the form `` `( $body ) `` let rhsBody := ⟨rhs[1]⟩ `($[$doc?:docComment]? macro_rules | `($pat) => `($rhsBody)) elabCommand <| mkNullNode #[stxCmd, macroRulesCmd] | _ => throwUnsupportedSyntax end Lean.Elab.Command
f882d3f1572d0bea59f0fdb113cf28ce08dc44fc
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/cheap_try_refl.lean
5b55480fb2012a6520ce68d1797f06eccddb645e
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
387
lean
example (h : false) : 10000000 = 20000000 := begin try {simp}, contradiction end example (h : false) (x : nat) : x + 10000000 = x + 20000000 := begin try {simp}, contradiction end example (h : false) (x y : nat) : x + y + 10000000 = x + y + 20000000 := begin try {simp}, contradiction end example (h : false) : "hello" = "world" := begin try {simp}, contradiction end