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
b7f9326e2652c5705c8298b7879ca5bb07cfc9f7
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/hott/init/nat.hlean
61356f9929ffe1842a886490909171fd7eb6c75d
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,420
hlean
/- 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.hedberg init.util init.types.sum open eq.ops decidable sum namespace nat open lift notation `ℕ` := nat inductive lt (a : nat) : nat → Type := | 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) : Type₀ := 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] : decidable_eq nat := λn m : nat, have general : ∀n, decidable (n = m), from nat.rec_on m (λ n, nat.cases_on n (inl rfl) (λ m, inr (λ (e : succ m = zero), down (nat.no_confusion e)))) (λ (m' : nat) (ih : ∀n, decidable (n = m')) (n : nat), nat.cases_on n (inr (λ h, down (nat.no_confusion h))) (λ (n' : nat), decidable.rec_on (ih n') (assume Heq : n' = m', inl (eq.rec_on Heq rfl)) (assume Hne : n' ≠ m', have H1 : succ n' ≠ succ m', from assume Heq, down (nat.no_confusion Heq (λ e : n' = m', Hne e)), inr H1))), general n -- 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, lt.cases_on hlt (λ heq, down (nat.no_confusion heq)) (λ b hlt heq, down (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, lt.cases_on hlt (λ (heq : succ n = succ m), down (nat.no_confusion heq (λ (e : n = m), eq.rec_on e ih))) (λ b (hlt : m < b) (heq : succ n = succ b), down (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 → Type₀ := 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 → empty, from λ b H, lt.cases_on H (λ heq, down (nat.no_confusion heq)) (λ b h₁ heq, down (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 lt.succ_of_lt {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 (lt.succ_of_lt 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) : sum (a = b) (a < b) := have aux : Π (a₁ b₁ : nat) (hlt : a₁ < b₁), a₁ = a → b₁ = (succ b) → sum (a = b) (a < b), from λ a₁ b₁ hlt, lt.rec_on hlt (λ h₁, eq.rec_on h₁ (λ h₂, down (nat.no_confusion h₂ (λ h₃, eq.rec_on h₃ (sum.inl rfl))))) (λ b₁ hlt ih h₁, eq.rec_on h₁ (λ h₂, down (nat.no_confusion h₂ (λ h₃, eq.rec_on h₃ (sum.inr hlt))))), aux a (succ b) H rfl rfl definition le.of_eq_or_lt {a b : nat} (H : sum (a = b) (a < b)) : a ≤ b := sum.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_iff_equiv _ (iff.intro le.of_eq_or_lt eq_or_lt_of_le) definition le.rec_on {a : nat} {P : nat → Type} {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 (sum.inr (sum.inl rfl)) (λ a₁, sum.inr (sum.inr !zero_lt_succ))) (λ b₁ (ih : ∀a, a < b₁ ⊎ a = b₁ ⊎ b₁ < a) (a : nat), nat.cases_on a (sum.inl !zero_lt_succ) (λ a, sum.rec_on (ih a) (λ h : a < b₁, sum.inl (lt.succ_of_lt h)) (λ h, sum.rec_on h (λ h : a = b₁, sum.inr (sum.inl (eq.rec_on h rfl))) (λ h : b₁ < a, sum.inr (sum.inr (lt.succ_of_lt h)))))) a definition eq_or_lt_of_not_lt {a b : nat} (hnlt : ¬ a < b) : a = b ⊎ b < a := sum.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.step {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 := lt.succ_of_lt 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 definition lt.of_lt_of_eq {a b c : nat} (h₁ : a < b) (h₂ : b = c) : a < c := eq.rec_on h₂ h₁ definition le.of_le_of_eq {a b c : nat} (h₁ : a ≤ b) (h₂ : b = c) : a ≤ c := eq.rec_on h₂ h₁ definition lt.of_eq_of_lt {a b c : nat} (h₁ : a = b) (h₂ : b < c) : a < c := eq.rec_on (eq.rec_on h₁ rfl) h₂ definition le.of_eq_of_le {a b c : nat} (h₁ : a = b) (h₂ : b ≤ c) : a ≤ c := eq.rec_on (eq.rec_on h₁ rfl) h₂ calc_trans lt.trans calc_trans lt.of_le_of_lt calc_trans lt.of_lt_of_le calc_trans lt.of_lt_of_eq calc_trans lt.of_eq_of_lt calc_trans le.trans calc_trans le.of_le_of_eq calc_trans le.of_eq_of_le 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_a_a (a : nat) : a = max 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 max.right_eq {a b : nat} (H : a < b) : b = max a b := eq.rec_on (max.eq_right H) rfl definition max.left_eq {a b : nat} (H : ¬ a < b) : a = max a b := eq.rec_on (max.eq_left H) rfl definition max.left (a b : nat) : a ≤ max a b := by_cases (λ h : a < b, le.of_lt (eq.rec_on (max.right_eq h) h)) (λ h : ¬ a < b, eq.rec_on (max.eq_left h) !le.refl) definition max.right (a b : nat) : b ≤ max a b := by_cases (λ h : a < b, eq.rec_on (max.eq_right h) !le.refl) (λ h : ¬ a < b, sum.rec_on (eq_or_lt_of_not_lt h) (λ heq, eq.rec_on heq (eq.rec_on (max_a_a a) !le.refl)) (λ h : b < a, have aux : a = max a b, from max.left_eq (lt.asymm h), eq.rec_on aux (le.of_lt h))) abbreviation gt a b := lt b a notation a > b := gt a b abbreviation ge a b := le b a 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 local attribute sub [reducible] definition succ_sub_succ_eq_sub (a b : nat) : succ a - succ b = a - b := nat.rec_on b rfl (λ b₁ (ih : succ a - succ b₁ = a - b₁), eq.rec_on ih (eq.refl (pred (succ a - succ b₁)))) 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.rec_on a rfl (λ a₁ (ih : zero - a₁ = zero), calc zero - succ a₁ = pred (zero - a₁) : rfl ... = pred zero : ih ... = zero : rfl) 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.rec_on b (le.refl a) (λ b₁ ih, le.trans !pred_le ih) end nat
05c9bc9f557f2e253d40a56383c61d7348190acc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/pointwise.lean
f9e5f6392c716159582108c1af81202d24805caf
[ "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
7,466
lean
/- Copyright (c) 2021 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import algebra.bounds import data.set.pointwise.smul /-! # Pointwise operations on ordered algebraic objects > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains lemmas about the effect of pointwise operations on sets with an order structure. ## TODO `Sup (s • t) = Sup s • Sup t` and `Inf (s • t) = Inf s • Inf t` hold as well but `covariant_class` is currently not polymorphic enough to state it. -/ open function set open_locale pointwise variables {α : Type*} section conditionally_complete_lattice variables [conditionally_complete_lattice α] section has_one variables [has_one α] @[simp, to_additive] lemma cSup_one : Sup (1 : set α) = 1 := cSup_singleton _ @[simp, to_additive] lemma cInf_one : Inf (1 : set α) = 1 := cInf_singleton _ end has_one section group variables [group α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {s t : set α} @[to_additive] lemma cSup_inv (hs₀ : s.nonempty) (hs₁ : bdd_below s) : Sup s⁻¹ = (Inf s)⁻¹ := by { rw ←image_inv, exact ((order_iso.inv α).map_cInf' hs₀ hs₁).symm } @[to_additive] lemma cInf_inv (hs₀ : s.nonempty) (hs₁ : bdd_above s) : Inf s⁻¹ = (Sup s)⁻¹ := by { rw ←image_inv, exact ((order_iso.inv α).map_cSup' hs₀ hs₁).symm } @[to_additive] lemma cSup_mul (hs₀ : s.nonempty) (hs₁ : bdd_above s) (ht₀ : t.nonempty) (ht₁ : bdd_above t) : Sup (s * t) = Sup s * Sup t := cSup_image2_eq_cSup_cSup (λ _, (order_iso.mul_right _).to_galois_connection) (λ _, (order_iso.mul_left _).to_galois_connection) hs₀ hs₁ ht₀ ht₁ @[to_additive] lemma cInf_mul (hs₀ : s.nonempty) (hs₁ : bdd_below s) (ht₀ : t.nonempty) (ht₁ : bdd_below t) : Inf (s * t) = Inf s * Inf t := cInf_image2_eq_cInf_cInf (λ _, (order_iso.mul_right _).symm.to_galois_connection) (λ _, (order_iso.mul_left _).symm.to_galois_connection) hs₀ hs₁ ht₀ ht₁ @[to_additive] lemma cSup_div (hs₀ : s.nonempty) (hs₁ : bdd_above s) (ht₀ : t.nonempty) (ht₁ : bdd_below t) : Sup (s / t) = Sup s / Inf t := by rw [div_eq_mul_inv, cSup_mul hs₀ hs₁ ht₀.inv ht₁.inv, cSup_inv ht₀ ht₁, div_eq_mul_inv] @[to_additive] lemma cInf_div (hs₀ : s.nonempty) (hs₁ : bdd_below s) (ht₀ : t.nonempty) (ht₁ : bdd_above t) : Inf (s / t) = Inf s / Sup t := by rw [div_eq_mul_inv, cInf_mul hs₀ hs₁ ht₀.inv ht₁.inv, cInf_inv ht₀ ht₁, div_eq_mul_inv] end group end conditionally_complete_lattice section complete_lattice variables [complete_lattice α] section has_one variables [has_one α] @[simp, to_additive] lemma Sup_one : Sup (1 : set α) = 1 := Sup_singleton @[simp, to_additive] lemma Inf_one : Inf (1 : set α) = 1 := Inf_singleton end has_one section group variables [group α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (s t : set α) @[to_additive] lemma Sup_inv (s : set α) : Sup s⁻¹ = (Inf s)⁻¹ := by { rw [←image_inv, Sup_image], exact ((order_iso.inv α).map_Inf _).symm } @[to_additive] lemma Inf_inv (s : set α) : Inf s⁻¹ = (Sup s)⁻¹ := by { rw [←image_inv, Inf_image], exact ((order_iso.inv α).map_Sup _).symm } @[to_additive] lemma Sup_mul : Sup (s * t) = Sup s * Sup t := Sup_image2_eq_Sup_Sup (λ _, (order_iso.mul_right _).to_galois_connection) $ λ _, (order_iso.mul_left _).to_galois_connection @[to_additive] lemma Inf_mul : Inf (s * t) = Inf s * Inf t := Inf_image2_eq_Inf_Inf (λ _, (order_iso.mul_right _).symm.to_galois_connection) $ λ _, (order_iso.mul_left _).symm.to_galois_connection @[to_additive] lemma Sup_div : Sup (s / t) = Sup s / Inf t := by simp_rw [div_eq_mul_inv, Sup_mul, Sup_inv] @[to_additive] lemma Inf_div : Inf (s / t) = Inf s / Sup t := by simp_rw [div_eq_mul_inv, Inf_mul, Inf_inv] end group end complete_lattice namespace linear_ordered_field variables {K : Type*} [linear_ordered_field K] {a b r : K} (hr : 0 < r) open set include hr lemma smul_Ioo : r • Ioo a b = Ioo (r • a) (r • b) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Ioo], split, { rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩, split, exact (mul_lt_mul_left hr).mpr a_h_left_left, exact (mul_lt_mul_left hr).mpr a_h_left_right, }, { rintro ⟨a_left, a_right⟩, use x / r, refine ⟨⟨(lt_div_iff' hr).mpr a_left, (div_lt_iff' hr).mpr a_right⟩, _⟩, rw mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Icc : r • Icc a b = Icc (r • a) (r • b) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Icc], split, { rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩, split, exact (mul_le_mul_left hr).mpr a_h_left_left, exact (mul_le_mul_left hr).mpr a_h_left_right, }, { rintro ⟨a_left, a_right⟩, use x / r, refine ⟨⟨(le_div_iff' hr).mpr a_left, (div_le_iff' hr).mpr a_right⟩, _⟩, rw mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Ico : r • Ico a b = Ico (r • a) (r • b) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Ico], split, { rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩, split, exact (mul_le_mul_left hr).mpr a_h_left_left, exact (mul_lt_mul_left hr).mpr a_h_left_right, }, { rintro ⟨a_left, a_right⟩, use x / r, refine ⟨⟨(le_div_iff' hr).mpr a_left, (div_lt_iff' hr).mpr a_right⟩, _⟩, rw mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Ioc : r • Ioc a b = Ioc (r • a) (r • b) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Ioc], split, { rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩, split, exact (mul_lt_mul_left hr).mpr a_h_left_left, exact (mul_le_mul_left hr).mpr a_h_left_right, }, { rintro ⟨a_left, a_right⟩, use x / r, refine ⟨⟨(lt_div_iff' hr).mpr a_left, (div_le_iff' hr).mpr a_right⟩, _⟩, rw mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Ioi : r • Ioi a = Ioi (r • a) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Ioi], split, { rintro ⟨a_w, a_h_left, rfl⟩, exact (mul_lt_mul_left hr).mpr a_h_left, }, { rintro h, use x / r, split, exact (lt_div_iff' hr).mpr h, exact mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Iio : r • Iio a = Iio (r • a) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Iio], split, { rintro ⟨a_w, a_h_left, rfl⟩, exact (mul_lt_mul_left hr).mpr a_h_left, }, { rintro h, use x / r, split, exact (div_lt_iff' hr).mpr h, exact mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Ici : r • Ici a = Ici (r • a) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Ioi], split, { rintro ⟨a_w, a_h_left, rfl⟩, exact (mul_le_mul_left hr).mpr a_h_left, }, { rintro h, use x / r, split, exact (le_div_iff' hr).mpr h, exact mul_div_cancel' _ (ne_of_gt hr), } end lemma smul_Iic : r • Iic a = Iic (r • a) := begin ext x, simp only [mem_smul_set, smul_eq_mul, mem_Iio], split, { rintro ⟨a_w, a_h_left, rfl⟩, exact (mul_le_mul_left hr).mpr a_h_left, }, { rintro h, use x / r, split, exact (div_le_iff' hr).mpr h, exact mul_div_cancel' _ (ne_of_gt hr), } end end linear_ordered_field
7cd326efe403892a7d34f013a7715a7f927ace04
4727251e0cd73359b15b664c3170e5d754078599
/src/set_theory/game/nim.lean
ef37d3db98c379ea768396942ad654772b8dd8cd
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,471
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Markus Himmel -/ import data.nat.bitwise import set_theory.game.birthday import set_theory.game.impartial /-! # Nim and the Sprague-Grundy theorem This file contains the definition for nim for any ordinal `O`. In the game of `nim O₁` both players may move to `nim O₂` for any `O₂ < O₁`. We also define a Grundy value for an impartial game `G` and prove the Sprague-Grundy theorem, that `G` is equivalent to `nim (grundy_value G)`. Finally, we compute the sum of finite Grundy numbers: if `G` and `H` have Grundy values `n` and `m`, where `n` and `m` are natural numbers, then `G + H` has the Grundy value `n xor m`. ## Implementation details The pen-and-paper definition of nim defines the possible moves of `nim O` to be `{O' | O' < O}`. However, this definition does not work for us because it would make the type of nim `ordinal.{u} → pgame.{u + 1}`, which would make it impossible for us to state the Sprague-Grundy theorem, since that requires the type of `nim` to be `ordinal.{u} → pgame.{u}`. For this reason, we instead use `O.out.α` for the possible moves, which makes proofs significantly more messy and tedious, but avoids the universe bump. The lemma `nim_def` is somewhat prone to produce "motive is not type correct" errors. If you run into this problem, you may find the lemmas `exists_ordinal_move_left_eq` and `exists_move_left_eq` useful. -/ universes u /-- `ordinal.out'` has the sole purpose of making `nim` computable. It performs the same job as `quotient.out` but is specific to ordinals. -/ def ordinal.out' (o : ordinal) : Well_order := ⟨o.out.α, (<), o.out.wo⟩ /-- The definition of single-heap nim, which can be viewed as a pile of stones where each player can take a positive number of stones from it on their turn. -/ def nim : ordinal → pgame | O₁ := let f := λ O₂, have hwf : ordinal.typein O₁.out'.r O₂ < O₁ := ordinal.typein_lt_self O₂, nim (ordinal.typein O₁.out'.r O₂) in ⟨O₁.out'.α, O₁.out'.α, f, f⟩ using_well_founded { dec_tac := tactic.assumption } namespace pgame local infix ` ≈ ` := equiv namespace nim open ordinal lemma nim_def (O : ordinal) : nim O = pgame.mk O.out.α O.out.α (λ O₂, nim (ordinal.typein (<) O₂)) (λ O₂, nim (ordinal.typein (<) O₂)) := by { rw nim, refl } instance : is_empty (left_moves (nim 0)) := by { rw nim_def, exact α.is_empty } instance : is_empty (right_moves (nim 0)) := by { rw nim_def, exact α.is_empty } noncomputable instance : unique (left_moves (nim 1)) := by { rw nim_def, exact α.unique } noncomputable instance : unique (right_moves (nim 1)) := by { rw nim_def, exact α.unique } /-- `0` has exactly the same moves as `nim 0`. -/ def nim_zero_relabelling : relabelling 0 (nim 0) := (relabelling.is_empty _).symm @[simp] theorem nim_zero_equiv : 0 ≈ nim 0 := nim_zero_relabelling.equiv /-- `nim 1` has exactly the same moves as `star`. -/ noncomputable def nim_one_relabelling : relabelling star (nim 1) := begin rw nim_def, refine ⟨_, _, λ i, _, λ j, _⟩, any_goals { dsimp, apply equiv_of_unique_of_unique }, all_goals { simp, exact nim_zero_relabelling } end @[simp] theorem nim_one_equiv : star ≈ nim 1 := nim_one_relabelling.equiv @[simp] lemma nim_birthday (O : ordinal) : (nim O).birthday = O := begin induction O using ordinal.induction with O IH, rw [nim_def, birthday_def], dsimp, rw max_eq_right le_rfl, convert lsub_typein O, exact funext (λ i, IH _ (typein_lt_self i)) end lemma left_moves_nim (O : ordinal) : (nim O).left_moves = O.out.α := by { rw nim_def, refl } lemma right_moves_nim (O : ordinal) : (nim O).right_moves = O.out.α := by { rw nim_def, refl } lemma move_left_nim_heq (O : ordinal) : (nim O).move_left == λ i : O.out.α, nim (typein (<) i) := by { rw nim_def, refl } lemma move_right_nim_heq (O : ordinal) : (nim O).move_right == λ i : O.out.α, nim (typein (<) i) := by { rw nim_def, refl } /-- Turns an ordinal less than `O` into a left move for `nim O` and viceversa. -/ noncomputable def to_left_moves_nim {O : ordinal} : {O' // O' < O} ≃ (nim O).left_moves := (out_equiv_lt O).trans (equiv.cast (left_moves_nim O).symm) /-- Turns an ordinal less than `O` into a right move for `nim O` and viceversa. -/ noncomputable def to_right_moves_nim {O : ordinal} : {O' // O' < O} ≃ (nim O).right_moves := (out_equiv_lt O).trans (equiv.cast (right_moves_nim O).symm) @[simp] theorem to_left_moves_nim_symm_lt {O : ordinal} (i : (nim O).left_moves) : ↑(to_left_moves_nim.symm i) < O := (to_left_moves_nim.symm i).prop @[simp] theorem to_right_moves_nim_symm_lt {O : ordinal} (i : (nim O).right_moves) : ↑(to_right_moves_nim.symm i) < O := (to_right_moves_nim.symm i).prop @[simp] lemma move_left_nim' {O : ordinal.{u}} (i) : (nim O).move_left i = nim (to_left_moves_nim.symm i).val := (congr_heq (move_left_nim_heq O).symm (cast_heq _ i)).symm lemma move_left_nim {O : ordinal} (i) : (nim O).move_left (to_left_moves_nim i) = nim i := by simp @[simp] lemma move_right_nim' {O : ordinal} (i) : (nim O).move_right i = nim (to_right_moves_nim.symm i).val := (congr_heq (move_right_nim_heq O).symm (cast_heq _ i)).symm lemma move_right_nim {O : ordinal} (i) : (nim O).move_right (to_right_moves_nim i) = nim i := by simp @[simp] lemma neg_nim (O : ordinal) : -nim O = nim O := begin induction O using ordinal.induction with O IH, rw nim_def, dsimp; congr; funext i; exact IH _ (ordinal.typein_lt_self i) end instance nim_impartial (O : ordinal) : impartial (nim O) := begin induction O using ordinal.induction with O IH, rw [impartial_def, neg_nim], refine ⟨equiv_refl _, λ i, _, λ i, _⟩; simpa using IH _ (typein_lt_self _) end lemma exists_ordinal_move_left_eq {O : ordinal} (i) : ∃ O' < O, (nim O).move_left i = nim O' := ⟨_, typein_lt_self _, move_left_nim' i⟩ lemma exists_move_left_eq {O O' : ordinal} (h : O' < O) : ∃ i, (nim O).move_left i = nim O' := ⟨to_left_moves_nim ⟨O', h⟩, by simp⟩ @[simp] lemma zero_first_loses : (nim (0 : ordinal)).first_loses := begin rw [impartial.first_loses_symm, nim_def, le_def_lt], exact ⟨@is_empty_elim (0 : ordinal).out.α _ _, @is_empty_elim pempty _ _⟩ end lemma non_zero_first_wins {O : ordinal} (hO : O ≠ 0) : (nim O).first_wins := begin rw [impartial.first_wins_symm, nim_def, lt_def_le], rw ←ordinal.pos_iff_ne_zero at hO, exact or.inr ⟨(ordinal.principal_seg_out hO).top, by simp⟩ end @[simp] lemma sum_first_loses_iff_eq (O₁ O₂ : ordinal) : (nim O₁ + nim O₂).first_loses ↔ O₁ = O₂ := begin split, { contrapose, intro h, rw [impartial.not_first_loses], wlog h' : O₁ ≤ O₂ using [O₁ O₂, O₂ O₁], { exact ordinal.le_total O₁ O₂ }, { have h : O₁ < O₂ := lt_of_le_of_ne h' h, rw [impartial.first_wins_symm', lt_def_le, nim_def O₂], refine or.inl ⟨(left_moves_add (nim O₁) _).symm (sum.inr _), _⟩, { exact (ordinal.principal_seg_out h).top }, { simpa using (impartial.add_self (nim O₁)).2 } }, { exact first_wins_of_equiv add_comm_equiv (this (ne.symm h)) } }, { rintro rfl, exact impartial.add_self (nim O₁) } end @[simp] lemma sum_first_wins_iff_neq (O₁ O₂ : ordinal) : (nim O₁ + nim O₂).first_wins ↔ O₁ ≠ O₂ := by rw [iff_not_comm, impartial.not_first_wins, sum_first_loses_iff_eq] @[simp] lemma equiv_iff_eq (O₁ O₂ : ordinal) : nim O₁ ≈ nim O₂ ↔ O₁ = O₂ := ⟨λ h, (sum_first_loses_iff_eq _ _).1 $ by rw [first_loses_of_equiv_iff (add_congr h (equiv_refl _)), sum_first_loses_iff_eq], by { rintro rfl, refl }⟩ end nim /-- The Grundy value of an impartial game, the ordinal which corresponds to the game of nim that the game is equivalent to -/ noncomputable def grundy_value : Π (G : pgame.{u}), ordinal.{u} | G := ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_def (G : pgame) : grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) := by rw grundy_value /-- The Sprague-Grundy theorem which states that every impartial game is equivalent to a game of nim, namely the game of nim corresponding to the games Grundy value -/ theorem equiv_nim_grundy_value : ∀ (G : pgame.{u}) [G.impartial], G ≈ nim (grundy_value G) | G := begin introI hG, rw [impartial.equiv_iff_sum_first_loses, ←impartial.no_good_left_moves_iff_first_loses], intro i, equiv_rw left_moves_add G (nim (grundy_value G)) at i, cases i with i₁ i₂, { rw add_move_left_inl, apply first_wins_of_equiv (add_congr (equiv_nim_grundy_value (G.move_left i₁)).symm (equiv_refl _)), rw nim.sum_first_wins_iff_neq, intro heq, rw [eq_comm, grundy_value_def G] at heq, have h := ordinal.ne_mex _, rw heq at h, exact (h i₁).irrefl }, { rw [add_move_left_inr, ←impartial.good_left_move_iff_first_wins], revert i₂, rw nim.nim_def, intro i₂, have h' : ∃ i : G.left_moves, (grundy_value (G.move_left i)) = ordinal.typein (quotient.out (grundy_value G)).r i₂, { revert i₂, rw grundy_value_def, intros i₂, have hnotin : _ ∉ _ := λ hin, (le_not_le_of_lt (ordinal.typein_lt_self i₂)).2 (cInf_le' hin), simpa using hnotin}, cases h' with i hi, use (left_moves_add _ _).symm (sum.inl i), rw [add_move_left_inl, move_left_mk], apply first_loses_of_equiv (add_congr (equiv_symm (equiv_nim_grundy_value (G.move_left i))) (equiv_refl _)), simpa only [hi] using impartial.add_self (nim (grundy_value (G.move_left i))) } end using_well_founded { dec_tac := pgame_wf_tac } @[simp] lemma grundy_value_eq_iff_equiv_nim (G : pgame) [G.impartial] (O : ordinal) : grundy_value G = O ↔ G ≈ nim O := ⟨by { rintro rfl, exact equiv_nim_grundy_value G }, by { intro h, rw ←nim.equiv_iff_eq, exact equiv_trans (equiv_symm (equiv_nim_grundy_value G)) h }⟩ lemma nim.grundy_value (O : ordinal.{u}) : grundy_value (nim O) = O := by simp @[simp] lemma grundy_value_eq_iff_equiv (G H : pgame) [G.impartial] [H.impartial] : grundy_value G = grundy_value H ↔ G ≈ H := (grundy_value_eq_iff_equiv_nim _ _).trans (equiv_congr_left.1 (equiv_nim_grundy_value H) _).symm lemma grundy_value_zero : grundy_value 0 = 0 := by simp @[simp] lemma grundy_value_iff_equiv_zero (G : pgame) [G.impartial] : grundy_value G = 0 ↔ G ≈ 0 := by rw [←grundy_value_eq_iff_equiv, grundy_value_zero] lemma grundy_value_star : grundy_value star = 1 := by simp @[simp] lemma grundy_value_nim_add_nim (n m : ℕ) : grundy_value (nim.{u} n + nim.{u} m) = nat.lxor n m := begin induction n using nat.strong_induction_on with n hn generalizing m, induction m using nat.strong_induction_on with m hm, rw [grundy_value_def], -- We want to show that `n xor m` is the smallest unreachable Grundy value. We will do this in two -- steps: -- h₀: `n xor m` is not a reachable grundy number. -- h₁: every Grundy number strictly smaller than `n xor m` is reachable. have h₀ : ∀ i, grundy_value ((nim n + nim m).move_left i) ≠ (nat.lxor n m : ordinal), { -- To show that `n xor m` is unreachable, we show that every move produces a Grundy number -- different from `n xor m`. equiv_rw left_moves_add _ _, -- The move operates either on the left pile or on the right pile. rintro (a|a), all_goals { -- One of the piles is reduced to `k` stones, with `k < n` or `k < m`. obtain ⟨ok, hk, hk'⟩ := nim.exists_ordinal_move_left_eq a, obtain ⟨k, rfl⟩ := ordinal.lt_omega.1 (lt_trans hk (ordinal.nat_lt_omega _)), replace hk := ordinal.nat_cast_lt.1 hk, -- Thus, the problem is reduced to computing the Grundy value of `nim n + nim k` or -- `nim k + nim m`, both of which can be dealt with using an inductive hypothesis. simp only [hk', add_move_left_inl, add_move_left_inr, id], rw hn _ hk <|> rw hm _ hk, -- But of course xor is injective, so if we change one of the arguments, we will not get the -- same value again. intro h, rw ordinal.nat_cast_inj at h, try { rw [nat.lxor_comm n k, nat.lxor_comm n m] at h }, exact hk.ne (nat.lxor_left_inj h) } }, have h₁ : ∀ (u : ordinal), u < nat.lxor n m → u ∈ set.range (λ i, grundy_value ((nim n + nim m).move_left i)), { -- Take any natural number `u` less than `n xor m`. intros ou hu, obtain ⟨u, rfl⟩ := ordinal.lt_omega.1 (lt_trans hu (ordinal.nat_lt_omega _)), replace hu := ordinal.nat_cast_lt.1 hu, -- Our goal is to produce a move that gives the Grundy value `u`. rw set.mem_range, -- By a lemma about xor, either `u xor m < n` or `u xor n < m`. have : nat.lxor u (nat.lxor n m) ≠ 0, { intro h, rw nat.lxor_eq_zero at h, linarith }, rcases nat.lxor_trichotomy this with h|h|h, { linarith }, -- Therefore, we can play the corresponding move, and by the inductive hypothesis the new state -- is `(u xor m) xor m = u` or `n xor (u xor n) = u` as required. { obtain ⟨i, hi⟩ := nim.exists_move_left_eq (ordinal.nat_cast_lt.2 h), refine ⟨(left_moves_add _ _).symm (sum.inl i), _⟩, simp only [hi, add_move_left_inl], rw [hn _ h, nat.lxor_assoc, nat.lxor_self, nat.lxor_zero] }, { obtain ⟨i, hi⟩ := nim.exists_move_left_eq (ordinal.nat_cast_lt.2 h), refine ⟨(left_moves_add _ _).symm (sum.inr i), _⟩, simp only [hi, add_move_left_inr], rw [hm _ h, nat.lxor_comm, nat.lxor_assoc, nat.lxor_self, nat.lxor_zero] } }, -- We are done! apply (ordinal.mex_le_of_ne.{u u} h₀).antisymm, contrapose! h₁, exact ⟨_, ⟨h₁, ordinal.mex_not_mem_range _⟩⟩, end lemma nim_add_nim_equiv {n m : ℕ} : nim n + nim m ≈ nim (nat.lxor n m) := by rw [←grundy_value_eq_iff_equiv_nim, grundy_value_nim_add_nim] lemma grundy_value_add (G H : pgame) [G.impartial] [H.impartial] {n m : ℕ} (hG : grundy_value G = n) (hH : grundy_value H = m) : grundy_value (G + H) = nat.lxor n m := begin rw [←nim.grundy_value (nat.lxor n m), grundy_value_eq_iff_equiv], refine equiv_trans _ nim_add_nim_equiv, convert add_congr (equiv_nim_grundy_value G) (equiv_nim_grundy_value H); simp only [hG, hH] end end pgame
77db288098f530c9057c2c9b58b874020b64d463
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/category/functor.lean
fc6e05c17763a44c274d18b3b9b7a42d30e3e4f1
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
3,063
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Standard identity and composition functors -/ import tactic.ext import category.basic 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 end functor def id.mk {α : Sort u} : α → id α := id namespace functor /-- `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. -/ structure comp (f : Type u → Type w) (g : Type v → Type u) (α : Type v) : Type w := (run : f $ g α) @[extensionality] protected lemma comp.ext {f : Type u → Type w} {g : Type v → Type u} {α : Type v} : ∀ {x y : comp f g α}, x.run = y.run → x = y | ⟨x⟩ ⟨._⟩ rfl := rfl namespace comp variables {f : Type u → Type w} {g : Type v → Type u} variables [functor f] [functor g] protected def map {α β : Type v} (h : α → β) : comp f g α → comp f g β | ⟨x⟩ := ⟨(<$>) h <$> x⟩ 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 | ⟨x⟩ := by simp [comp.map,functor.map_id] protected lemma comp_map (g_1 : α → β) (h : β → γ) : ∀ (x : comp f g α), comp.map (h ∘ g_1) x = comp.map h (comp.map g_1 x) | ⟨x⟩ := by simp [comp.map,functor.map_comp_map g_1 h] with functor_norm instance {f : Type u → Type w} {g : Type v → Type u} [functor f] [functor g] : functor (comp f g) := { map := @comp.map f g _ _ } @[simp] protected lemma run_map {α β : Type v} (h : α → β) : ∀ x : comp f g α, (h <$> x).run = (<$>) h <$> x.run | ⟨_⟩ := rfl instance {f : Type u → Type w} {g : Type v → Type u} [functor f] [functor g] [is_lawful_functor f] [is_lawful_functor g] : is_lawful_functor (comp f g) := { id_map := @comp.id_map f g _ _ _ _, comp_map := @comp.comp_map f g _ _ _ _ } end comp @[functor_norm] lemma comp.map_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [functor f] [functor g] (h : α → β) (x : f (g α)) : h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl end functor namespace ulift instance : functor ulift := { map := λ α β f, up ∘ f ∘ down } end ulift namespace sum variables {γ α β : Type v} protected def mapr (f : α → β) : γ ⊕ α → γ ⊕ β | (inl x) := inl x | (inr x) := inr (f x) instance : functor (sum γ) := { map := @sum.mapr γ } instance : is_lawful_functor.{v} (sum γ) := { id_map := by intros; casesm _ ⊕ _; refl, comp_map := by intros; casesm _ ⊕ _; refl } end sum
7ed5ac30cc74018049da034cafa7bf674016e9a9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/suggest.lean
47aec96b356810c2036082f98e5f417da4cb93e1
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
20,474
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- Map a name (typically a head symbol) to a "canonical" definitional synonym. Given a name `n`, we want a name `n'` such that a sufficiently applied expression with head symbol `n` is always definitionally equal to an expression with head symbol `n'`. Thus, we can search through all lemmas with a result type of `n'` to solve a goal with head symbol `n`. For example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`, and `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false` The default is that the original argument is returned, so `<` is just mapped to `<`. `normalize_synonym` is called for every lemma in the library, so it needs to be fast. -/ -- TODO this is a hack; if you suspect more cases here would help, please report them meta def normalize_synonym : name → name | `gt := `has_lt.lt | `ge := `has_le.le | `monotone := `has_le.le | `not := `false | n := n /-- Compute the head symbol of an expression, then normalise synonyms. This is only used when analysing the goal, so it is okay to do more expensive analysis here. -/ -- We may want to tweak this further? meta def allowed_head_symbols : expr → list name -- We first have a various "customisations": -- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`, -- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`. -- Note we only do this in the `ℕ` case, for performance. | `(@has_le.le ℕ _ (nat.succ _) _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ (nat.succ _)) := [`has_le.le, `has_lt.lt] | `(@has_le.le ℕ _ 1 _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ 1) := [`has_le.le, `has_lt.lt] -- And then the generic cases: | (expr.pi _ _ _ t) := allowed_head_symbols t | (expr.app f _) := allowed_head_symbols f | (expr.const n _) := [normalize_synonym n] | _ := [`_] . /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name_set) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if hs.contains `iff then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if hs.contains (normalize_synonym n) then some ex else none | _ := if hs.contains `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name_set) (d : declaration) : option decl_data := let n := d.to_name in if !d.is_trusted || n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name_set) : tactic (list decl_data) := do trace_if_enabled `suggest format!"Looking for lemmas with head symbols {hs}.", env ← get_env, let defs := env.decl_filter_map (process_declaration hs), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), return defs /-- We unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply in both directions into two separate elements. This ensures that both directions can be independently returned by `suggest`, and avoids a problem where the application of one direction prevents the application of the other direction. (See `exp_le_exp` in the tests.) -/ meta def unpack_iff_both : list decl_data → list decl_data | [] := [] | (⟨d, n, both, l⟩ :: L) := ⟨d, n, mp, l⟩ :: ⟨d, n, mpr, l⟩ :: unpack_iff_both L | (⟨d, n, m, l⟩ :: L) := ⟨d, n, m, l⟩ :: unpack_iff_both L /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. Returns the number of subgoals which were closed using `solve_by_elim`. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on the independent goals, -- whether or not `close_goals` is set, -- and then run `solve_by_elim { all_goals := tt }`, -- requiring that it succeeds if `close_goals = tt`. meta def apply_and_solve (close_goals : bool) (opt : opt := { }) (e : expr) : tactic ℕ := do trace_if_enabled `suggest format!"Trying to apply lemma: {e}", apply e opt.to_apply_cfg, trace_if_enabled `suggest format!"Applied lemma: {e}", ng ← num_goals, -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. In Phase 2 we will do -- backtracking search across all goals, allowing us to guess solutions that involve data, or -- unify metavariables, but only as long as we can finish all goals.) try (any_goals (independent_goal >> solve_by_elim opt)), -- Phase 2 (done >> return ng) <|> (do -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). (any_goals (success_if_fail independent_goal) >> solve_by_elim { backtrack_all_goals := tt, ..opt }) <|> -- and fail unless `close_goals = ff` guard ¬ close_goals, ng' ← num_goals, return (ng - ng')) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the subgoal using `apply_and_solve`. Returns the number of subgoals successfully closed. -/ meta def apply_declaration (close_goals : bool) (opt : opt := { }) (d : decl_data) : tactic ℕ := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := undefined -- we use `unpack_iff_both` to ensure this isn't reachable end /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : ℕ) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, ng ← num_goals, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.countp (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Make sure that `solve_by_elim` doesn't just solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, return $ mllist.of_list [⟨s, m, none, 0, hyps.countp (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← unpack_iff_both <$> library_defs (name_set.of_list $ allowed_head_symbols t), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `Try this: refine ...` or `Try this: exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used ≥ d₂.hyps_used)) /-- Returns a list of at most `limit` strings, of the form `Try this: exact ...` or `Try this: refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `Try this: exact ...`, which closes the current goal. -/ meta def library_search (opt : opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive open tactic open interactive open lean.parser open interactive.types open solve_by_elim local postfix `?`:9001 := optional declare_trace silence_suggest -- Turn off `Try this: exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, L ← tactic.suggest_scripts (n.get_or_else 50) { lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, ..opt }, if is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } -- Turn off `Try this: exact ...` trace message for `library_search` declare_trace silence_library_search /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact nat.mul_sub_left_distrib n m k ``` By default `library_search` only unfolds `reducible` definitions when attempting to match lemmas against the goal. Previously, it would unfold most definitions, sometimes giving surprising answers, or slow answers. The old behaviour is still available via `library_search!`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `library_search with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (semireducible : parse $ optional (tk "!")) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, (tactic.library_search { backtrack_all_goals := tt, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, md := if semireducible.is_some then tactic.transparency.semireducible else tactic.transparency.reducible, ..opt } >>= if is_trace_enabled_for `silence_library_search then (λ _, skip) else trace) <|> fail "`library_search` failed. If you aren't sure what to do next, you can also try `library_search!`, `suggest`, or `hint`. Possible reasons why `library_search` failed: * `library_search` will only apply a single lemma from the library, and then try to fill in its hypotheses from local hypotheses. * If you haven't already, try stating the theorem you want in its own lemma. * Sometimes the library has one version of a lemma but not a very similar version obtained by permuting arguments. Try replacing `a + b` with `b + a`, or `a - b < c` with `a < b + c`, to see if maybe the lemma exists but isn't stated quite the way you would like. * Make sure that you have all the side conditions for your theorem to be true. For example you won't find `a - b + b = a` for natural numbers in the library because it's false! Search for `b ≤ a → a - b + b = a` instead. * If a definition you made is in the goal, you won't find any theorems about it in the library. Try unfolding the definition using `unfold my_definition`. * If all else fails, ask on https://leanprover.zulipchat.com/, and maybe we can improve the library and/or `library_search` for next time." add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'Try this: exact ' prefix on this string? return [((script.get_rest "Try this: exact ").get_or_else script, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
24ff420cc6340ef66764dd7e8e5140bae0e619c7
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/category_theory/fully_faithful.lean
cbc4942bc84b6b4aeb965d2beb733c46bc39c394
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,172
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 logic.function import category_theory.natural_isomorphism universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective. In fact, we use a constructive definition, so the `full F` typeclass contains data, specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`. -/ class full (F : C ⥤ D) := (preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y) (witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously) restate_axiom full.witness' attribute [simp] full.witness /-- A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective.-/ class faithful (F : C ⥤ D) : Prop := (injectivity' [] : ∀ {X Y : C}, function.injective (@functor.map _ _ _ _ F X Y) . obviously) restate_axiom faithful.injectivity' namespace functor lemma injectivity (F : C ⥤ D) [faithful F] {X Y : C} : function.injective $ @functor.map _ _ _ _ F X Y := faithful.injectivity F /-- The specified preimage of a morphism under a full functor. -/ def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y := full.preimage.{v₁ v₂} f @[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : F.map (preimage F f) = f := by unfold preimage; obviously end functor variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C} @[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X := F.injectivity (by simp) @[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) : F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g := F.injectivity (by simp) @[simp] lemma preimage_map (f : X ⟶ Y) : F.preimage (F.map f) = f := F.injectivity (by simp) /-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/ def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y := { hom := F.preimage f.hom, inv := F.preimage f.inv, hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp), } @[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).hom = F.preimage f.hom := rfl @[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).inv = F.preimage (f.inv) := rfl @[simp] lemma preimage_iso_map_iso (f : X ≅ Y) : preimage_iso (F.map_iso f) = f := by tidy variables (F) def is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f := { inv := F.preimage (inv (F.map f)), hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp) } end category_theory namespace category_theory variables {C : Type u₁} [category.{v₁} C] instance full.id : full (𝟭 C) := { preimage := λ _ _ f, f } instance faithful.id : faithful (𝟭 C) := by obviously variables {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] variables (F F' : C ⥤ D) (G : D ⥤ E) instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) := { injectivity' := λ _ _ _ _ p, F.injectivity (G.injectivity p) } lemma faithful.of_comp [faithful $ F ⋙ G] : faithful F := { injectivity' := λ X Y, (F ⋙ G).injectivity.of_comp } section variables {F F'} lemma faithful.of_iso [faithful F] (α : F ≅ F') : faithful F' := { injectivity' := λ X Y f f' h, F.injectivity (by rw [←nat_iso.naturality_1 α.symm, h, nat_iso.naturality_1 α.symm]) } end variables {F G} lemma faithful.of_comp_iso {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (faithful.of_iso h.symm) alias faithful.of_comp_iso ← category_theory.iso.faithful_of_comp -- We could prove this from `faithful.of_comp_iso` using `eq_to_iso`, -- but that would introduce a cyclic import. lemma faithful.of_comp_eq {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (h.symm ▸ ℋ) alias faithful.of_comp_eq ← eq.faithful_of_comp variables (F G) /-- “Divide” a functor by a faithful functor. -/ protected def faithful.div (F : C ⥤ E) (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : C ⥤ D := { obj := obj, map := @map, map_id' := begin assume X, apply G.injectivity, apply eq_of_heq, transitivity F.map (𝟙 X), from h_map, rw [F.map_id, G.map_id, h_obj X] end, map_comp' := begin assume X Y Z f g, apply G.injectivity, apply eq_of_heq, transitivity F.map (f ≫ g), from h_map, rw [F.map_comp, G.map_comp], congr' 1; try { exact (h_obj _).symm }; exact h_map.symm end } lemma faithful.div_comp (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : (faithful.div F G obj @h_obj @map @h_map) ⋙ G = F := begin tactic.unfreeze_local_instances, cases F with F_obj _ _ _; cases G with G_obj _ _ _, unfold faithful.div functor.comp, unfold_projs at h_obj, have: F_obj = G_obj ∘ obj := (funext h_obj).symm, subst this, congr, funext, exact eq_of_heq h_map end lemma faithful.div_faithful (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : faithful (faithful.div F G obj @h_obj @map @h_map) := (faithful.div_comp F G _ h_obj _ @h_map).faithful_of_comp instance full.comp [full F] [full G] : full (F ⋙ G) := { preimage := λ _ _ f, F.preimage (G.preimage f) } end category_theory
28e1da264cbb2528844400013581fefd5fb0da63
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/natural_transformation.lean
24f44f6420d26e599e67182ece5570d425fce665
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
2,561
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn Defines natural transformations between functors. Introduces notations `τ.app X` for the components of natural transformations, `F ⟶ G` for the type of natural transformations between functors `F` and `G`, `σ ≫ τ` for vertical compositions, and `σ ◫ τ` for horizontal compositions. -/ import category_theory.functor namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `nat_trans F G` represents a natural transformation between functors `F` and `G`. The field `app` provides the components of the natural transformation. Naturality is expressed by `α.naturality_lemma`. -/ structure nat_trans (F G : C ⥤ D) : Sort (max (u₁+1) v₂) := (app : Π X : C, (F.obj X) ⟶ (G.obj X)) (naturality' : ∀ {{X Y : C}} (f : X ⟶ Y), (F.map f) ≫ (app Y) = (app X) ≫ (G.map f) . obviously) restate_axiom nat_trans.naturality' attribute [simp] nat_trans.naturality namespace nat_trans /-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/ protected def id (F : C ⥤ D) : nat_trans F F := { app := λ X, 𝟙 (F.obj X) } @[simp] lemma id_app' (F : C ⥤ D) (X : C) : (nat_trans.id F).app X = 𝟙 (F.obj X) := rfl open category open category_theory.functor section variables {F G H I : C ⥤ D} /-- `vcomp α β` is the vertical compositions of natural transformations. -/ def vcomp (α : nat_trans F G) (β : nat_trans G H) : nat_trans F H := { app := λ X, (α.app X) ≫ (β.app X), naturality' := begin /- `obviously'` says: -/ intros, simp, rw [←assoc, naturality, assoc, ←naturality], end } -- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal. @[extensionality] lemma ext {α β : nat_trans F G} (w : ∀ X : C, α.app X = β.app X) : α = β := begin induction α with α_components α_naturality, induction β with β_components β_naturality, have hc : α_components = β_components := funext w, subst hc end @[simp] lemma vcomp_app (α : nat_trans F G) (β : nat_trans G H) (X : C) : (vcomp α β).app X = (α.app X) ≫ (β.app X) := rfl end end nat_trans end category_theory
1e224986e145206bc586a3a7e61d2d94f2693d68
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/group_theory/cyclic.lean
4dca4762daa0fc1a8f1609e0fd87b495c5dfc41c
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,335
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland We define finite cyclic groups, in multiplicative notation. We prove that an element `g ∈ G` with `gⁿ = 1` gives rise to a homomorphism `Cₙ → G`. -/ import data.fintype group_theory.group_action algebra.group_power algebra.big_operators data.zmod.basic import tactic.ring import group_theory.pow_mod namespace group_theory variable n : ℕ+ @[derive decidable_eq] inductive cyclic | r : (zmod n) → cyclic namespace cyclic variable {n} def log : cyclic n → zmod n := λ ⟨i⟩, i def log_equiv : (cyclic n) ≃ (zmod n) := { to_fun := log, inv_fun := r, left_inv := λ ⟨i⟩, rfl, right_inv := λ i, rfl } instance : fintype (cyclic n) := fintype.of_equiv (zmod n) log_equiv.symm lemma card : fintype.card (cyclic n) = n := by {rw[fintype.card_congr log_equiv], exact fintype.card_fin n} def one : cyclic n := r 0 def inv : ∀ (g : cyclic n), cyclic n | (r i) := r (-i) def mul : ∀ (g h : cyclic n), cyclic n | (r i) (r j) := r (i + j) instance : has_one (cyclic n) := ⟨r 0⟩ lemma one_eq : (1 : cyclic n) = r 0 := rfl instance : has_inv (cyclic n) := ⟨cyclic.inv⟩ lemma r_inv (i : zmod n) : (r i)⁻¹ = r (- i) := rfl instance : has_mul (cyclic n) := ⟨cyclic.mul⟩ lemma rr_mul (i j : zmod n) : (r i) * (r j) = r (i + j) := rfl instance : group (cyclic n) := { one := 1, mul := (*), inv := has_inv.inv, one_mul := λ g, by {cases g, simp[one_eq,r_inv,rr_mul],}, mul_one := λ g, by {cases g, simp[one_eq,r_inv,rr_mul],}, mul_left_inv := λ g, by {cases g, simp[one_eq,r_inv,rr_mul],}, mul_assoc := λ g h k, by {cases g, cases h, cases k; simp[rr_mul],}, } def hom_from_gens {G : Type*} [group G] {g : G} (hg : monoid.pow g n = 1) : (cyclic n) → G | (r i) := pow_mod n hg i def is_hom_from_gens {G : Type*} [group G] {g : G} (hg : g ^ (n : ℕ) = 1) : is_monoid_hom (hom_from_gens hg) := begin split, {dsimp[has_one.one,monoid.one,group.one],refl}, {rintros ⟨i⟩ ⟨j⟩, change (g ^ (i + j).val) = (g ^ i.val) * (g ^ j.val), rw[← pow_add,← nat.mod_add_div (i.val + j.val) n], rw[pow_add,pow_mul,hg,one_pow,mul_one,zmod.add_val], } end end cyclic end group_theory
d0431745980310ca0a6fe7768eeb96a0d55192c7
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/squeeze.lean
f219819c7fc740850d29fa5cd3b93fc4ae6b55e0
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
15,200
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.traversable.basic import tactic.simpa setup_tactic_parser private meta def loc.to_string_aux : option name → string | none := "⊢" | (some x) := to_string x /-- pretty print a `loc` -/ meta def loc.to_string : loc → string | (loc.ns []) := "" | (loc.ns [none]) := "" | (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux) | loc.wildcard := " at *" /-- shift `pos` `n` columns to the left -/ meta def pos.move_left (p : pos) (n : ℕ) : pos := { line := p.line, column := p.column - n } namespace tactic attribute [derive decidable_eq] simp_arg_type /-- Turn a `simp_arg_type` into a string. -/ meta instance simp_arg_type.has_to_string : has_to_string simp_arg_type := ⟨λ a, match a with | simp_arg_type.all_hyps := "*" | (simp_arg_type.except n) := "-" ++ to_string n | (simp_arg_type.expr e) := to_string e | (simp_arg_type.symm_expr e) := "←" ++ to_string e end⟩ open list /-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/ meta def struct_inst : lean.parser pexpr := do tk "{", ls ← sep_by (skip_info (tk ",")) ( sum.inl <$> (tk ".." *> texpr) <|> sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)), tk "}", let (srcs,fields) := partition_map id ls, let (names,values) := unzip fields, pure $ pexpr.mk_structure_instance { field_names := names, field_values := values, sources := srcs } /-- pretty print structure instance -/ meta def struct.to_tactic_format (e : pexpr) : tactic format := do r ← e.get_structure_instance_info, fs ← mzip_with (λ n v, do v ← to_expr v >>= pp, pure $ format!"{n} := {v}" ) r.field_names r.field_values, let ss := r.sources.map (λ s, format!" .. {s}"), let x : format := format.join $ list.intersperse ", " (fs ++ ss), pure format!" {{{x}}}" /-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/ @[user_attribute] private meta def squeeze_loc_attr : user_attribute unit (option (list (pos × string × list simp_arg_type × string))) := { name := `_squeeze_loc, parser := fail "this attribute should not be used", descr := "table to accumulate multiple `squeeze_simp` suggestions" } /-- dummy declaration used as target of `squeeze_loc` attribute -/ def squeeze_loc_attr_carrier := () run_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt /-- Format a list of arguments for use with `simp` and friends. This omits the list entirely if it is empty. Patch: `pp` was changed to `to_string` because it was getting rid of prefixes that would be necessary for some disambiguations. -/ meta def render_simp_arg_list : list simp_arg_type → format | [] := "" | args := (++) " " $ to_line_wrap_format $ args.map to_string /-- Emit a suggestion to the user. If inside a `squeeze_scope` block, the suggestions emitted through `mk_suggestion` will be aggregated so that every tactic that makes a suggestion can consider multiple execution of the same invocation. If `at_pos` is true, make the suggestion at `p` instead of the current position. -/ meta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type) (at_pos := ff) : tactic unit := do xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier, match xs with | none := do let args := render_simp_arg_list args, if at_pos then @scope_trace _ p.line p.column $ λ _, _root_.trace sformat!"{pre}{args}{post}" (pure () : tactic unit) else trace sformat!"{pre}{args}{post}" | some xs := do squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff end /-- translate a `pexpr` into a `simp` configuration -/ meta def parse_config : option pexpr → tactic (simp_config_ext × format) | none := pure ({}, "") | (some cfg) := do e ← to_expr ``(%%cfg : simp_config_ext), fmt ← has_to_tactic_format.to_tactic_format cfg, prod.mk <$> eval_expr simp_config_ext e <*> struct.to_tactic_format cfg /-- translate a `pexpr` into a `dsimp` configuration -/ meta def parse_dsimp_config : option pexpr → tactic (dsimp_config × format) | none := pure ({}, "") | (some cfg) := do e ← to_expr ``(%%cfg : simp_config_ext), fmt ← has_to_tactic_format.to_tactic_format cfg, prod.mk <$> eval_expr dsimp_config e <*> struct.to_tactic_format cfg /-- `same_result proof tac` runs tactic `tac` and checks if the proof produced by `tac` is equivalent to `proof`. -/ meta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool := do s ← get_proof_state_after tac, pure $ some pr = s /-- Consumes the first list of `simp` arguments, accumulating required arguments on the second one and unnecessary arguments on the third one. -/ private meta def filter_simp_set_aux (tac : bool → list simp_arg_type → tactic unit) (args : list simp_arg_type) (pr : proof_state) : list simp_arg_type → list simp_arg_type → list simp_arg_type → tactic (list simp_arg_type × list simp_arg_type) | [] ys ds := pure (ys, ds) | (x :: xs) ys ds := do b ← same_result pr (tac tt (args ++ xs ++ ys)), if b then filter_simp_set_aux xs ys (ds.concat x) else filter_simp_set_aux xs (ys.concat x) ds declare_trace squeeze.deleted /-- `filter_simp_set g call_simp user_args simp_args` returns `args'` such that, when calling `call_simp tt /- only -/ args'` on the goal `g` (`g` is a meta var) we end up in the same state as if we had called `call_simp ff (user_args ++ simp_args)` and removing any one element of `args'` changes the resulting proof. -/ meta def filter_simp_set (tac : bool → list simp_arg_type → tactic unit) (user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) := do some s ← get_proof_state_after (tac ff (user_args ++ simp_args)), (simp_args', _) ← filter_simp_set_aux tac user_args s simp_args [] [], (user_args', ds) ← filter_simp_set_aux tac simp_args' s user_args [] [], when (is_trace_enabled_for `squeeze.deleted = tt ∧ ¬ ds.empty) trace!"deleting provided arguments {ds}", pure (user_args' ++ simp_args') /-- make a `simp_arg_type` that references the name given as an argument -/ meta def name.to_simp_args (n : name) : simp_arg_type := simp_arg_type.expr $ @expr.local_const ff n n (default) pexpr.mk_placeholder /-- If the `name` is (likely) to be overloaded, then prepend a `_root_` on it. The `expr` of an overloaded name is constructed using `expr.macro`; this is how we guess whether it's overloaded. -/ meta def prepend_root_if_needed (n : name) : tactic name := do x ← resolve_name' n, return $ match x with | expr.macro _ _ := `_root_ ++ n | _ := n end /-- tactic combinator to create a `simp`-like tactic that minimizes its argument list. * `slow`: adds all rfl-lemmas from the environment to the initial list (this is a slower but more accurate strategy) * `no_dflt`: did the user use the `only` keyword? * `args`: list of `simp` arguments * `tac`: how to invoke the underlying `simp` tactic -/ meta def squeeze_simp_core (slow no_dflt : bool) (args : list simp_arg_type) (tac : Π (no_dflt : bool) (args : list simp_arg_type), tactic unit) (mk_suggestion : list simp_arg_type → tactic unit) : tactic unit := do v ← target >>= mk_meta_var, args ← if slow then do simp_set ← attribute.get_instances `simp, simp_set ← simp_set.mfilter $ has_attribute' `_refl_lemma, simp_set ← simp_set.mmap $ resolve_name' >=> pure ∘ simp_arg_type.expr, pure $ args ++ simp_set else pure args, g ← retrieve $ do { g ← main_goal, tac no_dflt args, instantiate_mvars g }, let vs := g.list_constant', vs ← vs.mfilter is_simp_lemma, vs ← vs.mmap strip_prefix, vs ← vs.mmap prepend_root_if_needed, with_local_goals' [v] (filter_simp_set tac args $ vs.map name.to_simp_args) >>= mk_suggestion, tac no_dflt args namespace interactive /-- combinator meant to aggregate the suggestions issued by multiple calls of `squeeze_simp` (due, for instance, to `;`). Can be used as: ```lean example {α β} (xs ys : list α) (f : α → β) : (xs ++ ys.tail).map f = xs.map f ∧ (xs.tail.map f).length = xs.length := begin have : xs = ys, admit, squeeze_scope { split; squeeze_simp, -- `squeeze_simp` is run twice, the first one requires -- `list.map_append` and the second one -- `[list.length_map, list.length_tail]` -- prints only one message and combine the suggestions: -- > Try this: simp only [list.length_map, list.length_tail, list.map_append] squeeze_simp [this] -- `squeeze_simp` is run only once -- prints: -- > Try this: simp only [this] }, end ``` -/ meta def squeeze_scope (tac : itactic) : tactic unit := do none ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (), squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff, finally tac $ do some xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail "invalid state", let m := native.rb_lmap.of_list xs, squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff, m.to_list.reverse.mmap' $ λ ⟨p,suggs⟩, do { let ⟨pre,_,post⟩ := suggs.head, let suggs : list (list simp_arg_type) := suggs.map $ prod.fst ∘ prod.snd, mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () } /-- `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp` perform the same task with the difference that `squeeze_simp` relates to `simp` while `squeeze_simpa` relates to `simpa` and `squeeze_dsimp` relates to `dsimp`. The following applies to `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp`. `squeeze_simp` behaves like `simp` (including all its arguments) and prints a `simp only` invocation to skip the search through the `simp` lemma list. For instance, the following is easily solved with `simp`: ```lean example : 0 + 1 = 1 + 0 := by simp ``` To guide the proof search and speed it up, we may replace `simp` with `squeeze_simp`: ```lean example : 0 + 1 = 1 + 0 := by squeeze_simp -- prints: -- Try this: simp only [add_zero, eq_self_iff_true, zero_add] ``` `squeeze_simp` suggests a replacement which we can use instead of `squeeze_simp`. ```lean example : 0 + 1 = 1 + 0 := by simp only [add_zero, eq_self_iff_true, zero_add] ``` `squeeze_simp only` prints nothing as it already skips the `simp` list. This tactic is useful for speeding up the compilation of a complete file. Steps: 1. search and replace ` simp` with ` squeeze_simp` (the space helps avoid the replacement of `simp` in `@[simp]`) throughout the file. 2. Starting at the beginning of the file, go to each printout in turn, copy the suggestion in place of `squeeze_simp`. 3. after all the suggestions were applied, search and replace `squeeze_simp` with `simp` to remove the occurrences of `squeeze_simp` that did not produce a suggestion. Known limitation(s): * in cases where `squeeze_simp` is used after a `;` (e.g. `cases x; squeeze_simp`), `squeeze_simp` will produce as many suggestions as the number of goals it is applied to. It is likely that none of the suggestion is a good replacement but they can all be combined by concatenating their list of lemmas. `squeeze_scope` can be used to combine the suggestions: `by squeeze_scope { cases x; squeeze_simp }` * sometimes, `simp` lemmas are also `_refl_lemma` and they can be used without appearing in the resulting proof. `squeeze_simp` won't know to try that lemma unless it is called as `squeeze_simp?` -/ meta def squeeze_simp (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse struct_inst?) : tactic unit := do (cfg',c) ← parse_config cfg, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg') (λ args, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), loc := loc.to_string locat in mk_suggestion (key.move_left 1) sformat!"Try this: simp{use_iota_eqn} only" sformat!"{attrs}{loc}{c}" args) /-- see `squeeze_simp` -/ meta def squeeze_simpa (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : parse struct_inst?) : tactic unit := do (cfg',c) ← parse_config cfg, tgt' ← traverse (λ t, do t ← to_expr t >>= pp, pure format!" using {t}") tgt, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg') (λ args, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), tgt' := tgt'.get_or_else "" in mk_suggestion (key.move_left 1) sformat!"Try this: simpa{use_iota_eqn} only" sformat!"{attrs}{tgt'}{c}" args) /-- `squeeze_dsimp` behaves like `dsimp` (including all its arguments) and prints a `dsimp only` invocation to skip the search through the `simp` lemma list. See the doc string of `squeeze_simp` for examples. -/ meta def squeeze_dsimp (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse struct_inst?) : tactic unit := do (cfg',c) ← parse_dsimp_config cfg, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg') (λ args, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), loc := loc.to_string locat in mk_suggestion (key.move_left 1) sformat!"Try this: dsimp{use_iota_eqn} only" sformat!"{attrs}{loc}{c}" args) end interactive end tactic open tactic.interactive add_tactic_doc { name := "squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope", category := doc_category.tactic, decl_names := [``squeeze_simp, ``squeeze_dsimp, ``squeeze_simpa, ``squeeze_scope], tags := ["simplification", "Try this"], inherit_description_from := ``squeeze_simp }
3808a78f8ed67f10a0876fbe56845c74fb98e350
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/metric_space/contracting.lean
8e0cd464168bfadb56053596fac9f39a544a5829
[ "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
15,800
lean
/- Copyright (c) 2019 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov -/ import analysis.specific_limits import data.setoid.basic import dynamics.fixed_points.topology /-! # Contracting maps A Lipschitz continuous self-map with Lipschitz constant `K < 1` is called a *contracting map*. In this file we prove the Banach fixed point theorem, some explicit estimates on the rate of convergence, and some properties of the map sending a contracting map to its fixed point. ## Main definitions * `contracting_with K f` : a Lipschitz continuous self-map with `K < 1`; * `efixed_point` : given a contracting map `f` on a complete emetric space and a point `x` such that `edist x (f x) ≠ ∞`, `efixed_point f hf x hx` is the unique fixed point of `f` in `emetric.ball x ∞`; * `fixed_point` : the unique fixed point of a contracting map on a complete nonempty metric space. ## Tags contracting map, fixed point, Banach fixed point theorem -/ open_locale nnreal topological_space classical ennreal open filter function variables {α : Type*} /-- A map is said to be `contracting_with K`, if `K < 1` and `f` is `lipschitz_with K`. -/ def contracting_with [emetric_space α] (K : ℝ≥0) (f : α → α) := (K < 1) ∧ lipschitz_with K f namespace contracting_with variables [emetric_space α] [cs : complete_space α] {K : ℝ≥0} {f : α → α} open emetric set lemma to_lipschitz_with (hf : contracting_with K f) : lipschitz_with K f := hf.2 lemma one_sub_K_pos' (hf : contracting_with K f) : (0:ℝ≥0∞) < 1 - K := by simp [hf.1] lemma one_sub_K_ne_zero (hf : contracting_with K f) : (1:ℝ≥0∞) - K ≠ 0 := ne_of_gt hf.one_sub_K_pos' lemma one_sub_K_ne_top : (1:ℝ≥0∞) - K ≠ ∞ := by { norm_cast, exact ennreal.coe_ne_top } lemma edist_inequality (hf : contracting_with K f) {x y} (h : edist x y ≠ ∞) : edist x y ≤ (edist x (f x) + edist y (f y)) / (1 - K) := suffices edist x y ≤ edist x (f x) + edist y (f y) + K * edist x y, by rwa [ennreal.le_div_iff_mul_le (or.inl hf.one_sub_K_ne_zero) (or.inl one_sub_K_ne_top), mul_comm, ennreal.sub_mul (λ _ _, h), one_mul, tsub_le_iff_right], calc edist x y ≤ edist x (f x) + edist (f x) (f y) + edist (f y) y : edist_triangle4 _ _ _ _ ... = edist x (f x) + edist y (f y) + edist (f x) (f y) : by rw [edist_comm y, add_right_comm] ... ≤ edist x (f x) + edist y (f y) + K * edist x y : add_le_add (le_refl _) (hf.2 _ _) lemma edist_le_of_fixed_point (hf : contracting_with K f) {x y} (h : edist x y ≠ ∞) (hy : is_fixed_pt f y) : edist x y ≤ (edist x (f x)) / (1 - K) := by simpa only [hy.eq, edist_self, add_zero] using hf.edist_inequality h lemma eq_or_edist_eq_top_of_fixed_points (hf : contracting_with K f) {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt f y) : x = y ∨ edist x y = ∞ := begin refine or_iff_not_imp_right.2 (λ h, edist_le_zero.1 _), simpa only [hx.eq, edist_self, add_zero, ennreal.zero_div] using hf.edist_le_of_fixed_point h hy end /-- If a map `f` is `contracting_with K`, and `s` is a forward-invariant set, then restriction of `f` to `s` is `contracting_with K` as well. -/ lemma restrict (hf : contracting_with K f) {s : set α} (hs : maps_to f s s) : contracting_with K (hs.restrict f s s) := ⟨hf.1, λ x y, hf.2 x y⟩ include cs /-- Banach fixed-point theorem, contraction mapping theorem, `emetric_space` version. A contracting map on a complete metric space has a fixed point. We include more conclusions in this theorem to avoid proving them again later. The main API for this theorem are the functions `efixed_point` and `fixed_point`, and lemmas about these functions. -/ theorem exists_fixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) ≠ ∞) : ∃ y, is_fixed_pt f y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧ ∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) := have cauchy_seq (λ n, f^[n] x), from cauchy_seq_of_edist_le_geometric K (edist x (f x)) (ennreal.coe_lt_one_iff.2 hf.1) hx (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x), let ⟨y, hy⟩ := cauchy_seq_tendsto_of_complete this in ⟨y, is_fixed_pt_of_tendsto_iterate hy hf.2.continuous.continuous_at, hy, edist_le_of_edist_le_geometric_of_tendsto K (edist x (f x)) (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x) hy⟩ variable (f) -- avoid `efixed_point _` in pretty printer /-- Let `x` be a point of a complete emetric space. Suppose that `f` is a contracting map, and `edist x (f x) ≠ ∞`. Then `efixed_point` is the unique fixed point of `f` in `emetric.ball x ∞`. -/ noncomputable def efixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) ≠ ∞) : α := classical.some $ hf.exists_fixed_point x hx variables {f} lemma efixed_point_is_fixed_pt (hf : contracting_with K f) {x : α} (hx : edist x (f x) ≠ ∞) : is_fixed_pt f (efixed_point f hf x hx) := (classical.some_spec $ hf.exists_fixed_point x hx).1 lemma tendsto_iterate_efixed_point (hf : contracting_with K f) {x : α} (hx : edist x (f x) ≠ ∞) : tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point f hf x hx) := (classical.some_spec $ hf.exists_fixed_point x hx).2.1 lemma apriori_edist_iterate_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) ≠ ∞) (n : ℕ) : edist (f^[n] x) (efixed_point f hf x hx) ≤ (edist x (f x)) * K^n / (1 - K) := (classical.some_spec $ hf.exists_fixed_point x hx).2.2 n lemma edist_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) ≠ ∞) : edist x (efixed_point f hf x hx) ≤ (edist x (f x)) / (1 - K) := by { convert hf.apriori_edist_iterate_efixed_point_le hx 0, simp only [pow_zero, mul_one] } lemma edist_efixed_point_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) ≠ ∞) : edist x (efixed_point f hf x hx) < ∞ := (hf.edist_efixed_point_le hx).trans_lt (ennreal.mul_lt_top hx $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero) lemma efixed_point_eq_of_edist_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) ≠ ∞) {y : α} (hy : edist y (f y) ≠ ∞) (h : edist x y ≠ ∞) : efixed_point f hf x hx = efixed_point f hf y hy := begin refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h')); try { apply efixed_point_is_fixed_pt }, change edist_lt_top_setoid.rel _ _, transitivity x, by { symmetry, exact hf.edist_efixed_point_lt_top hx }, transitivity y, exacts [lt_top_iff_ne_top.2 h, hf.edist_efixed_point_lt_top hy] end omit cs /-- Banach fixed-point theorem for maps contracting on a complete subset. -/ theorem exists_fixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : ∃ y ∈ s, is_fixed_pt f y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧ ∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) := begin haveI := hsc.complete_space_coe, rcases hf.exists_fixed_point ⟨x, hxs⟩ hx with ⟨y, hfy, h_tendsto, hle⟩, refine ⟨y, y.2, subtype.ext_iff_val.1 hfy, _, λ n, _⟩, { convert (continuous_subtype_coe.tendsto _).comp h_tendsto, ext n, simp only [(∘), maps_to.iterate_restrict, maps_to.coe_restrict_apply, subtype.coe_mk] }, { convert hle n, rw [maps_to.iterate_restrict, eq_comm, maps_to.coe_restrict_apply, subtype.coe_mk] } end variable (f) -- avoid `efixed_point _` in pretty printer /-- Let `s` be a complete forward-invariant set of a self-map `f`. If `f` contracts on `s` and `x ∈ s` satisfies `edist x (f x) ≠ ∞`, then `efixed_point'` is the unique fixed point of the restriction of `f` to `s ∩ emetric.ball x ∞`. -/ noncomputable def efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) (x : α) (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : α := classical.some $ hf.exists_fixed_point' hsc hsf hxs hx variables {f} lemma efixed_point_mem' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : efixed_point' f hsc hsf hf x hxs hx ∈ s := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).fst lemma efixed_point_is_fixed_pt' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : is_fixed_pt f (efixed_point' f hsc hsf hf x hxs hx) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.1 lemma tendsto_iterate_efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point' f hsc hsf hf x hxs hx) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.1 lemma apriori_edist_iterate_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) (n : ℕ) : edist (f^[n] x) (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) * K^n / (1 - K) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.2 n lemma edist_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : edist x (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) / (1 - K) := by { convert hf.apriori_edist_iterate_efixed_point_le' hsc hsf hxs hx 0, rw [pow_zero, mul_one] } lemma edist_efixed_point_lt_top' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) : edist x (efixed_point' f hsc hsf hf x hxs hx) < ∞ := (hf.edist_efixed_point_le' hsc hsf hxs hx).trans_lt (ennreal.mul_lt_top hx $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero) /-- If a globally contracting map `f` has two complete forward-invariant sets `s`, `t`, and `x ∈ s` is at a finite distance from `y ∈ t`, then the `efixed_point'` constructed by `x` is the same as the `efixed_point'` constructed by `y`. This lemma takes additional arguments stating that `f` contracts on `s` and `t` because this way it can be used to prove the desired equality with non-trivial proofs of these facts. -/ lemma efixed_point_eq_of_edist_lt_top' (hf : contracting_with K f) {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hfs : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) ≠ ∞) {t : set α} (htc : is_complete t) (htf : maps_to f t t) (hft : contracting_with K $ htf.restrict f t t) {y : α} (hyt : y ∈ t) (hy : edist y (f y) ≠ ∞) (hxy : edist x y ≠ ∞) : efixed_point' f hsc hsf hfs x hxs hx = efixed_point' f htc htf hft y hyt hy := begin refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h')); try { apply efixed_point_is_fixed_pt' }, change edist_lt_top_setoid.rel _ _, transitivity x, by { symmetry, apply edist_efixed_point_lt_top' }, transitivity y, exact lt_top_iff_ne_top.2 hxy, apply edist_efixed_point_lt_top' end end contracting_with namespace contracting_with variables [metric_space α] {K : ℝ≥0} {f : α → α} (hf : contracting_with K f) include hf lemma one_sub_K_pos (hf : contracting_with K f) : (0:ℝ) < 1 - K := sub_pos.2 hf.1 lemma dist_le_mul (x y : α) : dist (f x) (f y) ≤ K * dist x y := hf.to_lipschitz_with.dist_le_mul x y lemma dist_inequality (x y) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) := suffices dist x y ≤ dist x (f x) + dist y (f y) + K * dist x y, by rwa [le_div_iff hf.one_sub_K_pos, mul_comm, sub_mul, one_mul, sub_le_iff_le_add], calc dist x y ≤ dist x (f x) + dist y (f y) + dist (f x) (f y) : dist_triangle4_right _ _ _ _ ... ≤ dist x (f x) + dist y (f y) + K * dist x y : add_le_add_left (hf.dist_le_mul _ _) _ lemma dist_le_of_fixed_point (x) {y} (hy : is_fixed_pt f y) : dist x y ≤ (dist x (f x)) / (1 - K) := by simpa only [hy.eq, dist_self, add_zero] using hf.dist_inequality x y theorem fixed_point_unique' {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt f y) : x = y := (hf.eq_or_edist_eq_top_of_fixed_points hx hy).resolve_right (edist_ne_top _ _) /-- Let `f` be a contracting map with constant `K`; let `g` be another map uniformly `C`-close to `f`. If `x` and `y` are their fixed points, then `dist x y ≤ C / (1 - K)`. -/ lemma dist_fixed_point_fixed_point_of_dist_le' (g : α → α) {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt g y) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) : dist x y ≤ C / (1 - K) := calc dist x y = dist y x : dist_comm x y ... ≤ (dist y (f y)) / (1 - K) : hf.dist_le_of_fixed_point y hx ... = (dist (f y) (g y)) / (1 - K) : by rw [hy.eq, dist_comm] ... ≤ C / (1 - K) : (div_le_div_right hf.one_sub_K_pos).2 (hfg y) noncomputable theory variables [nonempty α] [complete_space α] variable (f) /-- The unique fixed point of a contracting map in a nonempty complete metric space. -/ def fixed_point : α := efixed_point f hf _ (edist_ne_top (classical.choice ‹nonempty α›) _) variable {f} /-- The point provided by `contracting_with.fixed_point` is actually a fixed point. -/ lemma fixed_point_is_fixed_pt : is_fixed_pt f (fixed_point f hf) := hf.efixed_point_is_fixed_pt _ lemma fixed_point_unique {x} (hx : is_fixed_pt f x) : x = fixed_point f hf := hf.fixed_point_unique' hx hf.fixed_point_is_fixed_pt lemma dist_fixed_point_le (x) : dist x (fixed_point f hf) ≤ (dist x (f x)) / (1 - K) := hf.dist_le_of_fixed_point x hf.fixed_point_is_fixed_pt /-- Aposteriori estimates on the convergence of iterates to the fixed point. -/ lemma aposteriori_dist_iterate_fixed_point_le (x n) : dist (f^[n] x) (fixed_point f hf) ≤ (dist (f^[n] x) (f^[n+1] x)) / (1 - K) := by { rw [iterate_succ'], apply hf.dist_fixed_point_le } lemma apriori_dist_iterate_fixed_point_le (x n) : dist (f^[n] x) (fixed_point f hf) ≤ (dist x (f x)) * K^n / (1 - K) := le_trans (hf.aposteriori_dist_iterate_fixed_point_le x n) $ (div_le_div_right hf.one_sub_K_pos).2 $ hf.to_lipschitz_with.dist_iterate_succ_le_geometric x n lemma tendsto_iterate_fixed_point (x) : tendsto (λn, f^[n] x) at_top (𝓝 $ fixed_point f hf) := begin convert tendsto_iterate_efixed_point hf (edist_ne_top x _), refine (fixed_point_unique _ _).symm, apply efixed_point_is_fixed_pt end lemma fixed_point_lipschitz_in_map {g : α → α} (hg : contracting_with K g) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) : dist (fixed_point f hf) (fixed_point g hg) ≤ C / (1 - K) := hf.dist_fixed_point_fixed_point_of_dist_le' g hf.fixed_point_is_fixed_pt hg.fixed_point_is_fixed_pt hfg omit hf /-- If a map `f` has a contracting iterate `f^[n]`, then the fixed point of `f^[n]` is also a fixed point of `f`. -/ lemma is_fixed_pt_fixed_point_iterate {n : ℕ} (hf : contracting_with K (f^[n])) : is_fixed_pt f (hf.fixed_point (f^[n])) := begin set x := hf.fixed_point (f^[n]), have hx : (f^[n] x) = x := hf.fixed_point_is_fixed_pt, have := hf.to_lipschitz_with.dist_le_mul x (f x), rw [← iterate_succ_apply, iterate_succ_apply', hx] at this, contrapose! this, have := dist_pos.2 (ne.symm this), simpa only [nnreal.coe_one, one_mul] using (mul_lt_mul_right this).2 hf.1 end end contracting_with
0ff01d73b010c3616b94372edcbc2cd7c3a6d35b
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/precofibration_category.lean
77d62a2f6469c0b867d653e96eb82006a1da3045
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
2,402
lean
import homotopy_theory.formal.cofibrations.precofibration_category import homotopy_theory.formal.cylinder.hep import .cofibrations import .colimits import .pushout_lemmas open set open category_theory local notation f ` ∘ `:80 g:80 := g ≫ f namespace homotopy_theory.topological_spaces open homotopy_theory.cofibrations open homotopy_theory.cylinder open Top local notation `Top` := Top.{0} -- We're interested in structures whose "cofibrations" are the -- *closed* cofibrations, that is, the cofibrations in the classical -- sense with closed image. def closed_cofibration {A X : Top} (j : A ⟶ X) : Prop := cofibration j ∧ is_closed (range j) -- A closed cofibration is a closed map. lemma closed_cofibration.is_closed {A X : Top} {j : A ⟶ X} (hj : closed_cofibration j) {v : set A} : is_closed v → is_closed (j '' v) := embedding_is_closed (embedding_of_cofibration hj.1) hj.2 lemma closed_cofibration_id (A : Top) : closed_cofibration (𝟙 A) := ⟨hep_id 0, by change is_closed (range (id : A → A)); rw [range_id]; exact is_closed_univ⟩ lemma closed_cofibration_comp {A B C : Top} {j : A ⟶ B} {k : B ⟶ C} (hj : closed_cofibration j) (hk : closed_cofibration k) : closed_cofibration (k ∘ j) := ⟨hep_comp 0 hj.1 hk.1, by change is_closed (range (function.comp k j)); rw [range_comp]; exact hk.is_closed hj.2⟩ instance : precofibration_category Top := { is_cof := @closed_cofibration, mem_id := closed_cofibration_id, mem_comp := @closed_cofibration_comp, pushout_by_cof := λ _ _ _ f g _, has_pushouts.pushout f g, pushout_is_cof := λ _ _ _ _ f g f' g' po ⟨co_f, cl_f⟩, ⟨hep_pushout' 0 po co_f, (range_i_closed_iff_range_j_closed po).mp cl_f⟩ } instance : all_objects_cofibrant.{0} Top := ⟨assume A, ⟨hep_initial_induced 0 Top.empty_is_initial_object (preserves_initial_object.Is_initial_object_of_Is_initial_object Top.empty_is_initial_object), begin convert is_closed_empty, rw eq_empty_iff_forall_not_mem, intros x h, rcases h with ⟨⟨⟩, he⟩ end⟩⟩ lemma closed_cofibration_incl_iff {P : pair} : closed_cofibration P.incl ↔ P.cofibered ∧ is_closed P.subset := iff.intro (assume ⟨h₁, h₂⟩, ⟨h₁, by convert h₂; exact subtype.range_val.symm⟩) (assume ⟨h₁, h₂⟩, ⟨h₁, by convert h₂; exact subtype.range_val⟩) end homotopy_theory.topological_spaces
f4497dd0ed61987ab370545b20ea08fb73eafe79
6e36ebd5594a0d512dea8bc6ffe78c71b5b5032d
/src/mywork/Exams/exam1.lean
1d8feda2c8d0f4d9813b2b709046bdddfb5bbd98
[]
no_license
wrw2ztk/cs2120f21
cdc4b1b4043c8ae8f3c8c3c0e91cdacb2cfddb16
f55df4c723d3ce989908679f5653e4be669334ae
refs/heads/main
1,691,764,473,342
1,633,707,809,000
1,633,707,809,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,484
lean
/- Wyndham White wrw2ztk -/ /- ******************************* PART 1 of 2: AXIOMS [50 points] ******************************* -/ /- Explain the inference (introduction and elimination) rules of predicate logic as directed below. To give you guidance on how to answer these questions we include answers for some questions. -/ -- ------------------------------------- /- #1: → implies [5 points] INTRODUCTION Explain the introduction rule for →. [We give you the answer here.] In English: Given propositions, P and Q, a derivation (computation) a proof of Q from any proof of P, is a proof of P → Q. In constructive logic, a derivation is a given as a function definition. A proof of P → Q literally is a function, that, when given any proof of P as an argument returns a proof of Q. If you define such a function, you have proved P → Q. ELIMINATION Complete the definition of the elimination rule for →. (P Q : Prop) (p2q : P → Q) (p : P) ---------------------------------- (q : Q) -/ -- Give a formal proof of the following example : ∀ (P Q : Prop) (p2q : P → Q) (p : P), Q := begin assume P Q, assume piq, assume p, apply piq p, end -- Extra credit [2 points]. Who invented this principle? -- ------------------------------------- /- #2: true [5 points] INTRODUCTION Give the introduction rule for true using inference rule notation. [Here's our answer.] ---------- intro (pf: true) Give a brief English language explanation of the introduction rule for true. -- There is always a proof of true. So, any time true needs to be proved -- it always can be by applying the proof of true. ELIMINATION Give an English language description of the eliimination rule for true. [Our answer] A proof of true carries no information so there's no use for an elimination rule. -/ -- Give a formal proof of the following: example : true := begin exact true.intro, end -- ------------------------------------- /- #3: ∧ - and [10 points] INTRODUCTION Using inference rule notation, give the introduction rule for ∧. [Our answer] (P Q : Prop) (p : P) (q : Q) ---------------------------- intro (pq : P ∧ Q) Given an English language description of this inference rule. What does it really say, in plain simple English. -- Given a proof of the proposition P and a proof of the proposition Q, -- they can be combined to make a proof of the proposition (P ∧ Q). ELIMINATION Given the elimination rules for ∧ in both inference rule and English language forms. (P Q : Prop) (paq : P ∧ Q) ---------------------------- (p : P) (q : Q) Given a proof of P ∧ Q for propositions P and Q, that proof can be split into individual proofs of P and Q, respectively. -/ /- Formally state and prove the theorem that, for any propositions P and Q, Q ∧ P → P. -/ example : ∀ (P Q : Prop), Q ∧ P → P:= begin assume P Q, assume qap, exact qap.right, end -- ------------------------------------- /- #4: ∀ - for all [10 points] INTRODUCTION Explain in English the introduction rule for ∀. If T is any type (such as nat) and Q is any proposition (often in the form of a predicate on values of the given type), how do you prove ∀ (t : T), Q? What is the introduction rule for ∀? -- Assume you have an arbitrary object of the type T, then show -- that Q is true for the arbitrary object. Because Q is true for -- any arbitrary object of type T, it must be true for all objects -- of type T. ELIMINATION Here's an inference rule representation of the elim rule for ∀. First, complete the inference rule by filling in the bottom half, then Explain in English what it says. (T : Type) (Q : Prop), (pf : ∀ (t : T), Q) (t : T) -------------------------------------------------- elim (q : Q) -- Given a type T and a proposition Q, if you have a proof that -- Q is true for all t of type T and you have a t, then -- you have a proof of Q. Given a proof, (pf : ∀ (t : T), Q), and a value, (t : T), briefly explain in English how you *use* pf to derive a proof of Q. -- answer here You have the proof that any t of type T implies Q. So, when given a t of type T, a proof of Q can be created by applying the proof that t implies Q to t. QED. -/ --Fleshing out this example to prove my answer to myself namespace hidden example : ∀ (T : Type) (Q : Prop) (pf : ∀ (t:T), Q) (t:T), Q := begin assume T Q, assume tiq, exact tiq, end end hidden /- Consider the following assumptions, and then in the context of these assumptions, given answers to the challenge problems. -/ axioms (Person : Type) (KnowsLogic BetterComputerScientist : Person → Prop) (LogicMakesYouBetterAtCS: ∀ (p : Person), KnowsLogic p → BetterComputerScientist p) -- formalizee the following assumptions here -- (1) Lynn is a person -- (2) Lynn knows logic (Lynn : Person) (lkl : KnowsLogic Lynn) /- Now, formally state and prove the proposition that Lynn is a better computer scientist -/ example : ∀ (Person : Type) (Lynn : Person) (KnowsLogic BetterComputerScientist : Person → Prop) (LogicMakesYouBetterAtCS: ∀ (p : Person), KnowsLogic p → BetterComputerScientist p), KnowsLogic Lynn → BetterComputerScientist Lynn := begin assume person, assume Lynn, intros KnowsLogic BetterComputerScientist, intros lmybacs, assume LynnKL, apply lmybacs, exact LynnKL, end -- ------------------------------------- /- #5: ¬ - not [10 points] The ¬ connective in Lean is short for *not*. Give the short formal definition of ¬ in Lean. Note that surround the place where you give your answer with a namespace. This is just to avoid conflicting with Lean's definition of not. -/ namespace hidden def not (P : Prop) := P → false end hidden /- Explain precisely in English the "proof strategy" of "proof by negation." Explain how one uses this strategy to prove a proposition, ¬P. -/ -- For proof by negation, you assume P and show how it implies false. Because -- ¬P means by definition that (P → false), constructing a proof of false -- from the assumed proof of P proves that ¬P is true. This is proof by negation. /- Explain precisely in English the "proof strategy" of "proof by contradiction." Explain how one uses this strategy to prove a proposition, P (notice the lack of a ¬ in front of the P). Fill in the blanks the following partial answer: To prove P, assume ¬P and show that ¬P → false. From this derivation you can conclude ¬¬P. Then you apply the rule of negation ¬¬P → P to that result to arrive a a proof of P. We have seen that the inference rule you apply in the last step is not constructively valid but that it is classically valid, and that accepting the axiom of the excluded middle suffices to establish negation elimination (better called double negation elimination) as a theorem. -/ -- ------------------------------------- /- #6: ↔ - if and only if, equivalent to [10 points] -/ /- ELIMINATION As with ∧, ↔ has two elimination rules. You can see their statements here. -/ #check @iff.elim_left #check @iff.elim_right /- Formally state and prove the theorem that biimplication, ↔, is *commutative*. Note: put parentheses around each ↔ proposition, as → has higher precedence than ↔. Recall that iff has both elim_left and elim_right rules, just like ∧. -/ example : ∀ (P Q : Prop), (Q ↔ P) ↔ (P ↔ Q) := begin assume P Q, apply iff.intro, --forwards assume qiffp, have qip := iff.elim_left qiffp, have piq := iff.elim_right qiffp, apply iff.intro, exact piq, exact qip, --backwards assume piffq, have qip := iff.elim_right piffq, have piq := iff.elim_left piffq, apply iff.intro, exact qip, exact piq, end /- ************************************************ PART 2 of 3: PROPOSITIONS AND PROOFS [50 points] ************************************************ -/ /- #7 [20 points] First, give a fluent English rendition of the following proposition. Note that the identifier we use, elantp, is short for "everyone likes a nice, talented person." Then give a formal proof. Hint: try the "intros" tactic by itself where you'd previously have used assume followed by a list of identifiers. Think about what each expression means. -/ def ELJL : Prop := ∀ (Person : Type) (Nice : Person → Prop) (Talented : Person → Prop) (Likes : Person → Person → Prop) (elantp : ∀ (p : Person), Nice p → Talented p → ∀ (q : Person), Likes q p) (JohnLennon : Person) (JLNT : Nice JohnLennon ∧ Talented JohnLennon), (∀ (p : Person), Likes p JohnLennon) /- A person can be nice and a person can be talented. A person can like a person or not like that person. If a person is nice and talented, then all people like that person. John Lennon is a Person. John Lennon is nice and talented. Everyone likes John Lennon. -/ example : ELJL := begin intros Person Nice Talented Likes elantp JohnLennon JLNT p, apply elantp, exact JLNT.left, exact JLNT.right, end /- #8 [10 points] If every car is either heavy or light, and red or blue, and we want a prove by cases that every car is rad, then: -- how many cases will need to be considered? 4 -- list the cases (informally) heavy and red heavy and blue light and red light and blue -/ /- ********* RELATIONS ********* -/ /- #9 [20 points] Equality can be understood as a binary relation on objects of a given type. There is a binary equality relation on natural numbers, rational numbers, on strings, on Booleans, and so forth. We also saw that from the two axioms (inference rules) for equality, we could prove that it is not only reflexive, but also both symmetric and transitive. Complete the following definitions to express the propositions that equality is respectively symmetric and transitive. (Don't worry about proving these propositions. We just want you to write them formally, to show that you what the terms means.) -/ def eq_is_symmetric : Prop := ∀ (T : Type) (x y : T), x = y → y = x def eq_is_transitive : Prop := ∀ (T : Type) (x y z : T) (xey : x = y) (yez : y = z), x = z /- ************ EXTRA CREDIT ************ -/ /- EXTRA CREDIT: State and prove the proposition that (double) negation elimination is equivalent to excluded middle. You get 1 point for writing the correct proposition, 2 points for proving it in one direction and five points for proving it both directions. -/ def negelim_equiv_exmid : Prop := ∀ (P : Prop), ¬¬P ↔ (P ∨ ¬ P) example : negelim_equiv_exmid := begin assume P, apply iff.intro, assume nnp, have pornp := classical.em P, exact pornp, assume pornp, apply or.elim pornp, assume p, trivial, assume np, have p : P := _, trivial, end /- EXTRA CREDIT: Formally express and prove the proposition that if there is someone everyone loves, and loves is a symmetric relation, then thre is someone who loves everyone. [5 points] -/ axiom Loves : Person → Person → Prop example : ∀ (someone everyone : Person), Loves everyone someone → (Loves everyone someone ↔ Loves someone everyone) → Loves someone everyone := begin assume s e, assume eLs, assume symm, have h : Loves e s → Loves s e := iff.elim_left symm, apply h eLs, end
ae27c28ec20fae50207039bcb1a481bd6fdb9209
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_1805.lean
c6ca6ab3d2d1f0b82620edb4cbf397bad70dd67c
[]
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
359
lean
import order.basic variables {α : Type*} [partial_order α] variables x y z : α -- BEGIN #check x < y #check (lt_irrefl x : ¬ x < x) #check (lt_trans : x < y → y < z → x < z) #check (lt_of_le_of_lt : x ≤ y → y < z → x < z) #check (lt_of_lt_of_le : x < y → y ≤ z → x < z) example : x < y ↔ x ≤ y ∧ x ≠ y := lt_iff_le_and_ne -- END
5a881019f4d0143affeecad582c9185980be71cf
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set/Union_lift.lean
c65156fc3296e988ae9c4a12df0ea3e507e5148d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,006
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.set.lattice import order.directed /-! # Union lift This file defines `set.Union_lift` to glue together functions defined on each of a collection of sets to make a function on the Union of those sets. ## Main definitions * `set.Union_lift` - Given a Union of sets `Union S`, define a function on any subset of the Union by defining it on each component, and proving that it agrees on the intersections. * `set.lift_cover` - Version of `set.Union_lift` for the special case that the sets cover the entire type. ## Main statements There are proofs of the obvious properties of `Union_lift`, i.e. what it does to elements of each of the sets in the `Union`, stated in different ways. There are also three lemmas about `Union_lift` intended to aid with proving that `Union_lift` is a homomorphism when defined on a Union of substructures. There is one lemma each to show that constants, unary functions, or binary functions are preserved. These lemmas are: *`set.Union_lift_const` *`set.Union_lift_unary` *`set.Union_lift_binary` ## Tags directed union, directed supremum, glue, gluing -/ variables {α ι β : Type*} namespace set section Union_lift /- The unused argument `hf` is left in the definition so that the `simp` lemmas `Union_lift_inclusion` will work without the user having to provide `hf` explicitly to simplify terms involving `Union_lift`. -/ /-- Given a Union of sets `Union S`, define a function on the Union by defining it on each component, and proving that it agrees on the intersections. -/ @[nolint unused_arguments] noncomputable def Union_lift (S : ι → set α) (f : Π i (x : S i), β) (hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩) (T : set α) (hT : T ⊆ Union S) (x : T) : β := let i := classical.indefinite_description _ (mem_Union.1 (hT x.prop)) in f i ⟨x, i.prop⟩ variables {S : ι → set α} {f : Π i (x : S i), β} {hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩} {T : set α} {hT : T ⊆ Union S} (hT' : T = Union S) @[simp] lemma Union_lift_mk {i : ι} (x : S i) (hx : (x : α) ∈ T) : Union_lift S f hf T hT ⟨x, hx⟩ = f i x := let j := classical.indefinite_description _ (mem_Union.1 (hT hx)) in by cases x with x hx; exact hf j i x j.2 _ @[simp] lemma Union_lift_inclusion {i : ι} (x : S i) (h : S i ⊆ T) : Union_lift S f hf T hT (set.inclusion h x) = f i x := Union_lift_mk x _ lemma Union_lift_of_mem (x : T) {i : ι} (hx : (x : α) ∈ S i) : Union_lift S f hf T hT x = f i ⟨x, hx⟩ := by cases x with x hx; exact hf _ _ _ _ _ /-- `Union_lift_const` is useful for proving that `Union_lift` is a homomorphism of algebraic structures when defined on the Union of algebraic subobjects. For example, it could be used to prove that the lift of a collection of group homomorphisms on a union of subgroups preserves `1`. -/ lemma Union_lift_const (c : T) (ci : Π i, S i) (hci : ∀ i, (ci i : α) = c) (cβ : β) (h : ∀ i, f i (ci i) = cβ) : Union_lift S f hf T hT c = cβ := let ⟨i, hi⟩ := set.mem_Union.1 (hT c.prop) in have (ci i) = ⟨c, hi⟩, from subtype.ext (hci i), by rw [Union_lift_of_mem _ hi, ← this, h] /-- `Union_lift_unary` is useful for proving that `Union_lift` is a homomorphism of algebraic structures when defined on the Union of algebraic subobjects. For example, it could be used to prove that the lift of a collection of linear_maps on a union of submodules preserves scalar multiplication. -/ lemma Union_lift_unary (u : T → T) (ui : Π i, S i → S i) (hui : ∀ i (x : S i), u (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) x) = set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) (ui i x)) (uβ : β → β) (h : ∀ i (x : S i), (f i (ui i x)) = uβ (f i x)) (x : T) : Union_lift S f hf T (le_of_eq hT') (u x) = uβ (Union_lift S f hf T (le_of_eq hT') x) := begin subst hT', cases set.mem_Union.1 x.prop with i hi, rw [Union_lift_of_mem x hi, ← h i], have : x = (set.inclusion (set.subset_Union S i) ⟨x, hi⟩), { cases x, refl }, have hx' : (set.inclusion (set.subset_Union S i) (ui i ⟨x, hi⟩) : α) ∈ S i, from (ui i ⟨x, hi⟩).prop, conv_lhs { rw [this, hui, Union_lift_inclusion] } end /-- `Union_lift_binary` is useful for proving that `Union_lift` is a homomorphism of algebraic structures when defined on the Union of algebraic subobjects. For example, it could be used to prove that the lift of a collection of group homomorphisms on a union of subgroups preserves `*`. -/ lemma Union_lift_binary (dir: directed (≤) S) (op : T → T → T) (opi : Π i, S i → S i → S i) (hopi : ∀ i x y, set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) (opi i x y) = op (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) x) (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) y)) (opβ : β → β → β) (h : ∀ i (x y : S i), (f i (opi i x y)) = opβ (f i x) (f i y)) (x y : T) : Union_lift S f hf T (le_of_eq hT') (op x y) = opβ (Union_lift S f hf T (le_of_eq hT') x) (Union_lift S f hf T (le_of_eq hT') y) := begin subst hT', cases set.mem_Union.1 x.prop with i hi, cases set.mem_Union.1 y.prop with j hj, rcases dir i j with ⟨k, hik, hjk⟩, rw [Union_lift_of_mem x (hik hi), Union_lift_of_mem y (hjk hj), ← h k], have hx : x = (set.inclusion (set.subset_Union S k) ⟨x, hik hi⟩), { cases x, refl }, have hy : y = (set.inclusion (set.subset_Union S k) ⟨y, hjk hj⟩), { cases y, refl }, have hxy : (set.inclusion (set.subset_Union S k) (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩) : α) ∈ S k, from (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩).prop, conv_lhs { rw [hx, hy, ← hopi, Union_lift_of_mem _ hxy] }, simp only [coe_inclusion, subtype.coe_eta] end end Union_lift variables {S : ι → set α} {f : Π i (x : S i), β} {hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩} {hS : Union S = univ} /-- Glue together functions defined on each of a collection `S` of sets that cover a type. See also `set.Union_lift`. -/ noncomputable def lift_cover (S : ι → set α) (f : Π i (x : S i), β) (hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩) (hS : Union S = univ) (a : α) : β := Union_lift S f hf univ (hS ▸ set.subset.refl _) ⟨a, trivial⟩ @[simp] lemma lift_cover_coe {i : ι} (x : S i) : lift_cover S f hf hS x = f i x := Union_lift_mk x _ lemma lift_cover_of_mem {i : ι} {x : α} (hx : (x : α) ∈ S i) : lift_cover S f hf hS x = f i ⟨x, hx⟩ := Union_lift_of_mem ⟨x, trivial⟩ hx attribute [irreducible] Union_lift lift_cover end set
1a2465458ef70f2d4d877df279ab88def1103f44
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/path_category.lean
1cc410217934ceeafa2566e960256ee30ab29ce7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,122
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.eq_to_hom import category_theory.quotient import combinatorics.quiver.path /-! # The category paths on a quiver. When `C` is a quiver, `paths C` is the category of paths. ## When the quiver is itself a category We provide `path_composition : paths C ⥤ C`. We check that the quotient of the path category of a category by the canonical relation (paths are related if they compose to the same path) is equivalent to the original category. -/ universes v₁ v₂ u₁ u₂ namespace category_theory section /-- A type synonym for the category of paths in a quiver. -/ def paths (V : Type u₁) : Type u₁ := V instance (V : Type u₁) [inhabited V] : inhabited (paths V) := ⟨(default : V)⟩ variables (V : Type u₁) [quiver.{v₁+1} V] namespace paths instance category_paths : category.{max u₁ v₁} (paths V) := { hom := λ (X Y : V), quiver.path X Y, id := λ X, quiver.path.nil, comp := λ X Y Z f g, quiver.path.comp f g, } variables {V} /-- The inclusion of a quiver `V` into its path category, as a prefunctor. -/ @[simps] def of : V ⥤q (paths V) := { obj := λ X, X, map := λ X Y f, f.to_path, } local attribute [ext] functor.ext /-- Any prefunctor from `V` lifts to a functor from `paths V` -/ def lift {C} [category C] (φ : V ⥤q C) : paths V ⥤ C := { obj := φ.obj, map := λ X Y f, @quiver.path.rec V _ X (λ Y f, φ.obj X ⟶ φ.obj Y) (𝟙 $ φ.obj X) (λ Y Z p f ihp, ihp ≫ (φ.map f)) Y f, map_id' := λ X, by { refl, }, map_comp' := λ X Y Z f g, by { induction g with _ _ g' p ih _ _ _, { rw category.comp_id, refl, }, { have : f ≫ g'.cons p = (f ≫ g').cons p, by apply quiver.path.comp_cons, rw this, simp only, rw [ih, category.assoc], } } } @[simp] lemma lift_nil {C} [category C] (φ : V ⥤q C) (X : V) : (lift φ).map (quiver.path.nil) = 𝟙 (φ.obj X) := rfl @[simp] lemma lift_cons {C} [category C] (φ : V ⥤q C) {X Y Z : V} (p : quiver.path X Y) (f : Y ⟶ Z) : (lift φ).map (p.cons f) = (lift φ).map p ≫ (φ.map f) := rfl @[simp] lemma lift_to_path {C} [category C] (φ : V ⥤q C) {X Y : V} (f : X ⟶ Y) : (lift φ).map f.to_path = φ.map f := by {dsimp [quiver.hom.to_path,lift], simp, } lemma lift_spec {C} [category C] (φ : V ⥤q C) : of ⋙q (lift φ).to_prefunctor = φ := begin apply prefunctor.ext, rotate, { rintro X, refl, }, { rintro X Y f, rcases φ with ⟨φo,φm⟩, dsimp [lift, quiver.hom.to_path], simp only [category.id_comp], }, end lemma lift_unique {C} [category C] (φ : V ⥤q C) (Φ : paths V ⥤ C) (hΦ : of ⋙q Φ.to_prefunctor = φ) : Φ = lift φ := begin subst_vars, apply functor.ext, rotate, { rintro X, refl, }, { rintro X Y f, dsimp [lift], induction f with _ _ p f' ih, { simp only [category.comp_id], apply functor.map_id, }, { simp only [category.comp_id, category.id_comp] at ih ⊢, have : Φ.map (p.cons f') = Φ.map p ≫ (Φ.map (f'.to_path)), by { convert functor.map_comp Φ p (f'.to_path), }, rw [this, ih], }, }, end /-- Two functors out of a path category are equal when they agree on singleton paths. -/ @[ext] lemma ext_functor {C} [category C] {F G : paths V ⥤ C} (h_obj : F.obj = G.obj) (h : ∀ (a b : V) (e : a ⟶ b), F.map e.to_path = eq_to_hom (congr_fun h_obj a) ≫ G.map e.to_path ≫ eq_to_hom (congr_fun h_obj.symm b)) : F = G := begin ext X Y f, { induction f with Y' Z' g e ih, { erw [F.map_id, G.map_id, category.id_comp, eq_to_hom_trans, eq_to_hom_refl], }, { erw [F.map_comp g e.to_path, G.map_comp g e.to_path, ih, h], simp only [category.id_comp, eq_to_hom_refl, eq_to_hom_trans_assoc, category.assoc], }, }, { intro X, rw h_obj, } end end paths variables (W : Type u₂) [quiver.{v₂+1} W] -- A restatement of `prefunctor.map_path_comp` using `f ≫ g` instead of `f.comp g`. @[simp] lemma prefunctor.map_path_comp' (F : V ⥤q W) {X Y Z : paths V} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map_path (f ≫ g) = (F.map_path f).comp (F.map_path g) := prefunctor.map_path_comp _ _ _ end section variables {C : Type u₁} [category.{v₁} C] open quiver /-- A path in a category can be composed to a single morphism. -/ @[simp] def compose_path {X : C} : Π {Y : C} (p : path X Y), X ⟶ Y | _ path.nil := 𝟙 X | _ (path.cons p e) := compose_path p ≫ e @[simp] lemma compose_path_to_path {X Y : C} (f : X ⟶ Y) : compose_path (f.to_path) = f := category.id_comp _ @[simp] lemma compose_path_comp {X Y Z : C} (f : path X Y) (g : path Y Z) : compose_path (f.comp g) = compose_path f ≫ compose_path g := begin induction g with Y' Z' g e ih, { simp, }, { simp [ih], }, end @[simp] lemma compose_path_id {X : paths C} : compose_path (𝟙 X) = 𝟙 X := rfl @[simp] lemma compose_path_comp' {X Y Z : paths C} (f : X ⟶ Y) (g : Y ⟶ Z) : compose_path (f ≫ g) = compose_path f ≫ compose_path g := compose_path_comp f g variables (C) /-- Composition of paths as functor from the path category of a category to the category. -/ @[simps] def path_composition : paths C ⥤ C := { obj := λ X, X, map := λ X Y f, compose_path f, } /-- The canonical relation on the path category of a category: two paths are related if they compose to the same morphism. -/ -- TODO: This, and what follows, should be generalized to -- the `hom_rel` for the kernel of any functor. -- Indeed, this should be part of an equivalence between congruence relations on a category `C` -- and full, essentially surjective functors out of `C`. @[simp] def paths_hom_rel : hom_rel (paths C) := λ X Y p q, (path_composition C).map p = (path_composition C).map q /-- The functor from a category to the canonical quotient of its path category. -/ @[simps] def to_quotient_paths : C ⥤ quotient (paths_hom_rel C) := { obj := λ X, quotient.mk X, map := λ X Y f, quot.mk _ f.to_path, map_id' := λ X, quot.sound (quotient.comp_closure.of _ _ _ (by simp)), map_comp' := λ X Y Z f g, quot.sound (quotient.comp_closure.of _ _ _ (by simp)), } /-- The functor from the canonical quotient of a path category of a category to the original category. -/ @[simps] def quotient_paths_to : quotient (paths_hom_rel C) ⥤ C := quotient.lift _ (path_composition C) (λ X Y p q w, w) /-- The canonical quotient of the path category of a category is equivalent to the original category. -/ def quotient_paths_equiv : quotient (paths_hom_rel C) ≌ C := { functor := quotient_paths_to C, inverse := to_quotient_paths C, unit_iso := nat_iso.of_components (λ X, by { cases X, refl, }) begin intros, cases X, cases Y, induction f, dsimp, simp only [category.comp_id, category.id_comp], apply quot.sound, apply quotient.comp_closure.of, simp [paths_hom_rel], end, counit_iso := nat_iso.of_components (λ X, iso.refl _) (by tidy), functor_unit_iso_comp' := by { intros, cases X, dsimp, simp, refl, }, } end end category_theory
e892b887c469c83470c7f586eb7e90bffeaa1b59
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/monotonicity/lemmas.lean
22c977d4a6c94f09db1fca988e5ae45d02219691
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,737
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity.basic variables {α : Type*} @[mono] lemma mul_mono_nonneg {x y z : α} [ordered_semiring α] (h' : 0 ≤ z) (h : x ≤ y) : x * z ≤ y * z := by apply mul_le_mul_of_nonneg_right; assumption lemma gt_of_mul_lt_mul_neg_right {a b c : α} [linear_ordered_ring α] (h : a * c < b * c) (hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc, have h2 : -(b * c) < -(a * c), from neg_lt_neg h, have h3 : b * (-c) < a * (-c), from calc b * (-c) = - (b * c) : by rewrite neg_mul_eq_mul_neg ... < - (a * c) : h2 ... = a * (-c) : by rewrite neg_mul_eq_mul_neg, lt_of_mul_lt_mul_right h3 nhc @[mono] lemma mul_mono_nonpos {x y z : α} [linear_ordered_ring α] (h' : 0 ≥ z) (h : y ≤ x) : x * z ≤ y * z := begin classical, by_contradiction h'', revert h, apply not_le_of_lt, apply gt_of_mul_lt_mul_neg_right _ h', apply lt_of_not_ge h'' end @[mono] lemma nat.sub_mono_left_strict {x y z : ℕ} (h' : z ≤ x) (h : x < y) : x - z < y - z := begin have : z ≤ y, { transitivity, assumption, apply le_of_lt h, }, apply @lt_of_add_lt_add_left _ _ z, rw [nat.add_sub_of_le,nat.add_sub_of_le]; solve_by_elim end @[mono] lemma nat.sub_mono_right_strict {x y z : ℕ} (h' : x ≤ z) (h : y < x) : z - x < z - y := begin have h'' : y ≤ z, { transitivity, apply le_of_lt h, assumption }, apply @lt_of_add_lt_add_right _ _ _ x, rw [nat.sub_add_cancel h'], apply @lt_of_le_of_lt _ _ _ (z - y + y), rw [nat.sub_add_cancel h''], apply nat.add_lt_add_left h end
c0450f0bfbb18385b2b4984970544ef00ebddf1c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/dynamics/fixed_points/basic.lean
d5eda405f92dcbb388dd49a191a435576b8ea949
[ "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
6,528
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.set.function import logic.function.iterate import group_theory.perm.basic /-! # Fixed points of a self-map > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define * the predicate `is_fixed_pt f x := f x = x`; * the set `fixed_points f` of fixed points of a self-map `f`. We also prove some simple lemmas about `is_fixed_pt` and `∘`, `iterate`, and `semiconj`. ## Tags fixed point -/ open equiv universes u v variables {α : Type u} {β : Type v} {f fa g : α → α} {x y : α} {fb : β → β} {m n k : ℕ} {e : perm α} namespace function /-- A point `x` is a fixed point of `f : α → α` if `f x = x`. -/ def is_fixed_pt (f : α → α) (x : α) := f x = x /-- Every point is a fixed point of `id`. -/ lemma is_fixed_pt_id (x : α) : is_fixed_pt id x := (rfl : _) namespace is_fixed_pt instance [h : decidable_eq α] {f : α → α} {x : α} : decidable (is_fixed_pt f x) := h (f x) x /-- If `x` is a fixed point of `f`, then `f x = x`. This is useful, e.g., for `rw` or `simp`.-/ protected lemma eq (hf : is_fixed_pt f x) : f x = x := hf /-- If `x` is a fixed point of `f` and `g`, then it is a fixed point of `f ∘ g`. -/ protected lemma comp (hf : is_fixed_pt f x) (hg : is_fixed_pt g x) : is_fixed_pt (f ∘ g) x := calc f (g x) = f x : congr_arg f hg ... = x : hf /-- If `x` is a fixed point of `f`, then it is a fixed point of `f^[n]`. -/ protected lemma iterate (hf : is_fixed_pt f x) (n : ℕ) : is_fixed_pt (f^[n]) x := iterate_fixed hf n /-- If `x` is a fixed point of `f ∘ g` and `g`, then it is a fixed point of `f`. -/ lemma left_of_comp (hfg : is_fixed_pt (f ∘ g) x) (hg : is_fixed_pt g x) : is_fixed_pt f x := calc f x = f (g x) : congr_arg f hg.symm ... = x : hfg /-- If `x` is a fixed point of `f` and `g` is a left inverse of `f`, then `x` is a fixed point of `g`. -/ lemma to_left_inverse (hf : is_fixed_pt f x) (h : left_inverse g f) : is_fixed_pt g x := calc g x = g (f x) : congr_arg g hf.symm ... = x : h x /-- If `g` (semi)conjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ protected lemma map {x : α} (hx : is_fixed_pt fa x) {g : α → β} (h : semiconj g fa fb) : is_fixed_pt fb (g x) := calc fb (g x) = g (fa x) : (h.eq x).symm ... = g x : congr_arg g hx protected lemma apply {x : α} (hx : is_fixed_pt f x) : is_fixed_pt f (f x) := by convert hx lemma preimage_iterate {s : set α} (h : is_fixed_pt (set.preimage f) s) (n : ℕ) : is_fixed_pt (set.preimage (f^[n])) s := by { rw set.preimage_iterate_eq, exact h.iterate n, } protected lemma equiv_symm (h : is_fixed_pt e x) : is_fixed_pt e.symm x := h.to_left_inverse e.left_inverse_symm protected lemma perm_inv (h : is_fixed_pt e x) : is_fixed_pt ⇑(e⁻¹) x := h.equiv_symm protected lemma perm_pow (h : is_fixed_pt e x) (n : ℕ) : is_fixed_pt ⇑(e ^ n) x := by { rw equiv.perm.coe_pow, exact h.iterate _ } protected lemma perm_zpow (h : is_fixed_pt e x) : ∀ n : ℤ, is_fixed_pt ⇑(e ^ n) x | (int.of_nat n) := h.perm_pow _ | (int.neg_succ_of_nat n) := (h.perm_pow $ n + 1).perm_inv end is_fixed_pt @[simp] lemma injective.is_fixed_pt_apply_iff (hf : injective f) {x : α} : is_fixed_pt f (f x) ↔ is_fixed_pt f x := ⟨λ h, hf h.eq, is_fixed_pt.apply⟩ /-- The set of fixed points of a map `f : α → α`. -/ def fixed_points (f : α → α) : set α := {x : α | is_fixed_pt f x} instance fixed_points.decidable [decidable_eq α] (f : α → α) (x : α) : decidable (x ∈ fixed_points f) := is_fixed_pt.decidable @[simp] lemma mem_fixed_points : x ∈ fixed_points f ↔ is_fixed_pt f x := iff.rfl lemma mem_fixed_points_iff {α : Type*} {f : α → α} {x : α} : x ∈ fixed_points f ↔ f x = x := by refl @[simp] lemma fixed_points_id : fixed_points (@id α) = set.univ := set.ext $ λ _, by simpa using is_fixed_pt_id _ lemma fixed_points_subset_range : fixed_points f ⊆ set.range f := λ x hx, ⟨x, hx⟩ /-- If `g` semiconjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ lemma semiconj.maps_to_fixed_pts {g : α → β} (h : semiconj g fa fb) : set.maps_to g (fixed_points fa) (fixed_points fb) := λ x hx, hx.map h /-- Any two maps `f : α → β` and `g : β → α` are inverse of each other on the sets of fixed points of `f ∘ g` and `g ∘ f`, respectively. -/ lemma inv_on_fixed_pts_comp (f : α → β) (g : β → α) : set.inv_on f g (fixed_points $ f ∘ g) (fixed_points $ g ∘ f) := ⟨λ x, id, λ x, id⟩ /-- Any map `f` sends fixed points of `g ∘ f` to fixed points of `f ∘ g`. -/ lemma maps_to_fixed_pts_comp (f : α → β) (g : β → α) : set.maps_to f (fixed_points $ g ∘ f) (fixed_points $ f ∘ g) := λ x hx, hx.map $ λ x, rfl /-- Given two maps `f : α → β` and `g : β → α`, `g` is a bijective map between the fixed points of `f ∘ g` and the fixed points of `g ∘ f`. The inverse map is `f`, see `inv_on_fixed_pts_comp`. -/ lemma bij_on_fixed_pts_comp (f : α → β) (g : β → α) : set.bij_on g (fixed_points $ f ∘ g) (fixed_points $ g ∘ f) := (inv_on_fixed_pts_comp f g).bij_on (maps_to_fixed_pts_comp g f) (maps_to_fixed_pts_comp f g) /-- If self-maps `f` and `g` commute, then they are inverse of each other on the set of fixed points of `f ∘ g`. This is a particular case of `function.inv_on_fixed_pts_comp`. -/ lemma commute.inv_on_fixed_pts_comp (h : commute f g) : set.inv_on f g (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using inv_on_fixed_pts_comp f g /-- If self-maps `f` and `g` commute, then `f` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `function.bij_on_fixed_pts_comp`. -/ lemma commute.left_bij_on_fixed_pts_comp (h : commute f g) : set.bij_on f (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using bij_on_fixed_pts_comp g f /-- If self-maps `f` and `g` commute, then `g` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `function.bij_on_fixed_pts_comp`. -/ lemma commute.right_bij_on_fixed_pts_comp (h : commute f g) : set.bij_on g (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using bij_on_fixed_pts_comp f g end function
6e5811a2c0ac99a3e55310f6b7e636082f0f2192
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/fubini.lean
579c595280a86e0df24cf72a2ad58e39e246cd6c
[ "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
9,989
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.limits.has_limits import category_theory.products.basic import category_theory.currying /-! # A Fubini theorem for categorical limits We prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`, when all the appropriate limits exist. We begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated "uncurried" functor. In the first part, given a coherent family `D` of limit cones over the functors `F.obj j`, and a cone `c` over `G`, we construct a cone over the cone points of `D`. We then show that if `c` is a limit cone, the constructed cone is also a limit cone. In the second part, we state the Fubini theorem in the setting where limits are provided by suitable `has_limit` classes. We construct `limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)` and give simp lemmas characterising it. For convenience, we also provide `limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)` in terms of the uncurried functor. ## Future work The dual statement. -/ universes v u open category_theory namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables (F : J ⥤ K ⥤ C) /-- A structure carrying a diagram of cones over the functors `F.obj j`. -/ -- We could try introducing a "dependent functor type" to handle this? structure diagram_of_cones := (obj : Π j : J, cone (F.obj j)) (map : Π {j j' : J} (f : j ⟶ j'), (cones.postcompose (F.map f)).obj (obj j) ⟶ obj j') (id : ∀ j : J, (map (𝟙 j)).hom = 𝟙 _ . obviously) (comp : ∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃), (map (f ≫ g)).hom = (map f).hom ≫ (map g).hom . obviously) variables {F} /-- Extract the functor `J ⥤ C` consisting of the cone points and the maps between them, from a `diagram_of_cones`. -/ @[simps] def diagram_of_cones.cone_points (D : diagram_of_cones F) : J ⥤ C := { obj := λ j, (D.obj j).X, map := λ j j' f, (D.map f).hom, map_id' := λ j, D.id j, map_comp' := λ j₁ j₂ j₃ f g, D.comp f g, } /-- Given a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`, we can construct a cone over the diagram consisting of the cone points from `D`. -/ @[simps] def cone_of_cone_uncurry {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) (c : cone (uncurry.obj F)) : cone (D.cone_points) := { X := c.X, π := { app := λ j, (Q j).lift { X := c.X, π := { app := λ k, c.π.app (j, k), naturality' := λ k k' f, begin dsimp, simp only [category.id_comp], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j, k') (𝟙 j, f), dsimp at this, simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end } }, naturality' := λ j j' f, (Q j').hom_ext begin dsimp, intro k, simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_π, limits.is_limit.fac_assoc, limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j', k) (f, 𝟙 k), dsimp at this, simp only [category.id_comp, category.comp_id, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end, } }. /-- `cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.` -/ def cone_of_cone_uncurry_is_limit {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) {c : cone (uncurry.obj F)} (P : is_limit c) : is_limit (cone_of_cone_uncurry Q c) := { lift := λ s, P.lift { X := s.X, π := { app := λ p, s.π.app p.1 ≫ (D.obj p.1).π.app p.2, naturality' := λ p p' f, begin dsimp, simp only [category.id_comp, category.assoc], rcases p with ⟨j, k⟩, rcases p' with ⟨j', k'⟩, rcases f with ⟨fj, fk⟩, dsimp, slice_rhs 3 4 { rw ←nat_trans.naturality, }, slice_rhs 2 3 { rw ←(D.obj j).π.naturality, }, simp only [functor.const.obj_map, category.id_comp, category.assoc], have w := (D.map fj).w k', dsimp at w, rw ←w, have n := s.π.naturality fj, dsimp at n, simp only [category.id_comp] at n, rw n, simp, end, } }, fac' := λ s j, begin apply (Q j).hom_ext, intro k, simp, end, uniq' := λ s m w, begin refine P.uniq { X := s.X, π := _, } m _, rintro ⟨j, k⟩, dsimp, rw [←w j], simp, end, } section variables (F) variables [has_limits_of_shape K C] /-- Given a functor `F : J ⥤ K ⥤ C`, with all needed limits, we can construct a diagram consisting of the limit cone over each functor `F.obj j`, and the universal cone morphisms between these. -/ @[simps] noncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F := { obj := λ j, limit.cone (F.obj j), map := λ j j' f, { hom := lim.map (F.map f), }, } -- Satisfying the inhabited linter. noncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) := ⟨diagram_of_cones.mk_of_has_limits F⟩ @[simp] lemma diagram_of_cones.mk_of_has_limits_cone_points : (diagram_of_cones.mk_of_has_limits F).cone_points = (F ⋙ lim) := rfl variables [has_limit (uncurry.obj F)] variables [has_limit (F ⋙ lim)] /-- The Fubini theorem for a functor `F : J ⥤ K ⥤ C`, showing that the limit of `uncurry.obj F` can be computed as the limit of the limits of the functors `F.obj j`. -/ noncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) ≅ limit (F ⋙ lim) := begin let c := limit.cone (uncurry.obj F), let P : is_limit c := limit.is_limit _, let G := diagram_of_cones.mk_of_has_limits F, let Q : Π j, is_limit (G.obj j) := λ j, limit.is_limit _, have Q' := cone_of_cone_uncurry_is_limit Q P, have Q'' := (limit.is_limit (F ⋙ lim)), exact is_limit.cone_point_unique_up_to_iso Q' Q'', end @[simp] lemma limit_uncurry_iso_limit_comp_lim_hom_π_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := begin dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso], simp, end @[simp] lemma limit_uncurry_iso_limit_comp_lim_inv_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom], simp, end end section variables (G : J × K ⥤ C) section variables [has_limits_of_shape K C] variables [has_limit G] variables [has_limit ((curry.obj G) ⋙ lim)] /-- The Fubini theorem for a functor `G : J × K ⥤ C`, showing that the limit of `G` can be computed as the limit of the limits of the functors `G.obj (j, _)`. -/ noncomputable def limit_iso_limit_curry_comp_lim : limit G ≅ limit ((curry.obj G) ⋙ lim) := begin have i : G ≅ uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G, haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) := has_limit_of_iso i, transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)), apply has_limit.iso_of_nat_iso i, exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G), end @[simp, reassoc] lemma limit_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := by simp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso] @[simp, reassoc] lemma limit_iso_limit_curry_comp_lim_inv_π {j} {k} : (limit_iso_limit_curry_comp_lim G).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_iso_limit_curry_comp_lim G).hom], simp, end end section variables [has_limits C] -- Certainly one could weaken the hypotheses here. open category_theory.prod /-- A variant of the Fubini theorem for a functor `G : J × K ⥤ C`, showing that $\lim_k \lim_j G(j,k) ≅ \lim_j \lim_k G(j,k)$. -/ noncomputable def limit_curry_swap_comp_lim_iso_limit_curry_comp_lim : limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit ((curry.obj G) ⋙ lim) := calc limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit (swap K J ⋙ G) : (limit_iso_limit_curry_comp_lim _).symm ... ≅ limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _) ... ≅ limit ((curry.obj G) ⋙ lim) : limit_iso_limit_curry_comp_lim _ @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ k ≫ limit.π _ j := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv ≫ limit.π _ k ≫ limit.π _ j = limit.π _ j ≫ limit.π _ k := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end end end end category_theory.limits
1350fc230fcca920be7080ac7c63cf528c297db9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/char_p/algebra.lean
75efbd747a656a80a011bbd84df3c8593d4cec80
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,044
lean
/- Copyright (c) 2021 Jon Eugster. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jon Eugster, Eric Wieser -/ import algebra.char_p.basic import ring_theory.localization import algebra.free_algebra /-! # Characteristics of algebras In this file we describe the characteristic of `R`-algebras. In particular we are interested in the characteristic of free algebras over `R` and the fraction field `fraction_ring R`. ## Main results - `char_p_of_injective_algebra_map` If `R →+* A` is an injective algebra map then `A` has the same characteristic as `R`. Instances constructed from this result: - Any `free_algebra R X` has the same characteristic as `R`. - The `fraction_ring R` of an integral domain `R` has the same characteristic as `R`. -/ /-- If the algebra map `R →+* A` is injective then `A` has the same characteristic as `R`. -/ lemma char_p_of_injective_algebra_map {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (h : function.injective (algebra_map R A)) (p : ℕ) [char_p R p] : char_p A p := { cast_eq_zero_iff := λx, begin rw ←char_p.cast_eq_zero_iff R p x, change algebra_map ℕ A x = 0 ↔ algebra_map ℕ R x = 0, rw is_scalar_tower.algebra_map_apply ℕ R A x, refine iff.trans _ h.eq_iff, rw ring_hom.map_zero, end } /-- If the algebra map `R →+* A` is injective and `R` has characteristic zero then so does `A`. -/ lemma char_zero_of_injective_algebra_map {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (h : function.injective (algebra_map R A)) [char_zero R] : char_zero A := { cast_injective := λ x y hxy, begin change algebra_map ℕ A x = algebra_map ℕ A y at hxy, rw is_scalar_tower.algebra_map_apply ℕ R A x at hxy, rw is_scalar_tower.algebra_map_apply ℕ R A y at hxy, exact char_zero.cast_injective (h hxy), end } -- `char_p.char_p_to_char_zero A _ (char_p_of_injective_algebra_map h 0)` does not work -- here as it would require `ring A`. namespace free_algebra variables {R X : Type*} [comm_semiring R] (p : ℕ) /-- If `R` has characteristic `p`, then so does `free_algebra R X`. -/ instance char_p [char_p R p] : char_p (free_algebra R X) p := char_p_of_injective_algebra_map free_algebra.algebra_map_left_inverse.injective p /-- If `R` has characteristic `0`, then so does `free_algebra R X`. -/ instance char_zero [char_zero R] : char_zero (free_algebra R X) := char_zero_of_injective_algebra_map free_algebra.algebra_map_left_inverse.injective end free_algebra namespace fraction_ring variables {R : Type*} [integral_domain R] (p : ℕ) /-- If `R` has characteristic `p`, then so does `fraction_ring R`. -/ instance char_p [char_p R p] : char_p (fraction_ring R) p := char_p_of_injective_algebra_map (fraction_map.injective (fraction_ring.of R)) p /-- If `R` has characteristic `0`, then so does `fraction_ring R`. -/ instance char_zero [char_zero R] : char_zero (fraction_ring R) := char_p.char_p_to_char_zero (fraction_ring R) end fraction_ring
a50b4c7203dde3994bdc06031f5916c2f9d0bd4c
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Lean/Elab/Quotation.lean
9ece69df32676aa9758bd77bc0fea001cd6dcabf
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,620
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ import Lean.Syntax import Lean.ResolveName import Lean.Elab.Term import Lean.Elab.Quotation.Util import Lean.Elab.Quotation.Precheck import Lean.Parser.Term namespace Lean.Elab.Term.Quotation open Lean.Parser.Term open Lean.Syntax open Meta /-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/ private partial def floatOutAntiquotTerms : Syntax → StateT (Syntax → TermElabM Syntax) TermElabM Syntax | stx@(Syntax.node k args) => do if isAntiquot stx && !isEscapedAntiquot stx then let e := getAntiquotTerm stx if !e.isIdent || !e.getId.isAtomic then return ← withFreshMacroScope do let a ← `(a) modify (fun cont stx => (`(let $a:ident := $e; $stx) : TermElabM _)) stx.setArg 2 a Syntax.node k (← args.mapM floatOutAntiquotTerms) | stx => pure stx private def getSepFromSplice (splice : Syntax) : Syntax := do let Syntax.atom _ sep ← getAntiquotSpliceSuffix splice | unreachable! Syntax.mkStrLit (sep.dropRight 1) partial def mkTuple : Array Syntax → TermElabM Syntax | #[] => `(Unit.unit) | #[e] => e | es => do let stx ← mkTuple (es.eraseIdx 0) `(Prod.mk $(es[0]) $stx) def resolveSectionVariable (sectionVars : NameMap Name) (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 sectionVars.find? id with | some newId => [(newId, projs)] | none => loop p (s::projs) | _, _ => [] loop extractionResult.name [] -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax → TermElabM Syntax | Syntax.ident info rawVal val preresolved => do if !hygiene.get (← getOptions) then return ← `(Syntax.ident info $(quote rawVal) $(quote val) $(quote preresolved)) -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. let r ← resolveGlobalName val -- extension of the paper algorithm: also store unique section variable names as top-level scopes -- so they can be captured and used inside the section, but not outside let r' := resolveSectionVariable (← read).sectionVars val let preresolved := r ++ r' ++ preresolved let val := quote val -- `scp` is bound in stxQuot.expand `(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node k _) => do if isAntiquot stx && !isEscapedAntiquot stx then getAntiquotTerm stx else if isTokenAntiquot stx && !isEscapedAntiquot stx then match stx[0] with | Syntax.atom _ val => `(Syntax.atom (Option.getD (getHeadInfo? $(getAntiquotTerm stx)) info) $(quote val)) | _ => throwErrorAt stx "expected token" else if isAntiquotSuffixSplice stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node throwErrorAt stx "unexpected antiquotation splice" else if isAntiquotSplice stx && !isEscapedAntiquot stx then throwErrorAt stx "unexpected antiquotation splice" else let empty ← `(Array.empty); -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx let args ← stx.getArgs.foldlM (fun args arg => do if k == nullKind && isAntiquotSuffixSplice arg then let antiquot := getAntiquotSuffixSpliceInner arg match antiquotSuffixSplice? arg with | `optional => `(Array.appendCore $args (match $(getAntiquotTerm antiquot):term with | some x => Array.empty.push x | none => Array.empty)) | `many => `(Array.appendCore $args $(getAntiquotTerm antiquot)) | `sepBy => `(Array.appendCore $args (@SepArray.elemsAndSeps $(getSepFromSplice arg) $(getAntiquotTerm antiquot))) | k => throwErrorAt arg "invalid antiquotation suffix splice kind '{k}'" else if k == nullKind && isAntiquotSplice arg then let k := antiquotSpliceKind? arg let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax let ids ← getAntiquotationIds arg if ids.isEmpty then throwErrorAt stx "antiquotation splice must contain at least one antiquotation" let arr ← match k with | `optional => `(match $[$ids:ident],* with | $[some $ids:ident],* => $(quote inner) | none => Array.empty) | _ => let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id $arr)) ids.back `(Array.map (fun $(← mkTuple ids) => $(inner[0])) $arr) let arr ← if k == `sepBy then `(mkSepArray $arr (mkAtom $(getSepFromSplice arg))) else arr let arr ← bindLets arr `(Array.appendCore $args $arr) else do let arg ← quoteSyntax arg; `(Array.push $args $arg)) empty `(Syntax.node $(quote k) $args) | Syntax.atom _ val => `(Syntax.atom info $(quote val)) | Syntax.missing => throwUnsupportedSyntax def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) let stx ← quoteSyntax stx.getQuotContent; `(Bind.bind MonadRef.mkInfoFromRefPos (fun info => Bind.bind getCurrMacroScope (fun scp => Bind.bind getMainModule (fun mainModule => Pure.pure $stx)))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ macro "elab_stx_quot" kind:ident : command => `(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand) -- elab_stx_quot Parser.Level.quot elab_stx_quot Parser.Term.quot elab_stx_quot Parser.Term.funBinder.quot elab_stx_quot Parser.Term.bracketedBinder.quot elab_stx_quot Parser.Term.matchDiscr.quot elab_stx_quot Parser.Tactic.quot elab_stx_quot Parser.Tactic.quotSeq elab_stx_quot Parser.Term.stx.quot elab_stx_quot Parser.Term.prec.quot elab_stx_quot Parser.Term.attr.quot elab_stx_quot Parser.Term.prio.quot elab_stx_quot Parser.Term.doElem.quot elab_stx_quot Parser.Term.dynamicQuot /- match -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax × Syntax /-- In a single match step, we match the first discriminant against the "head" of the first pattern of the first alternative. This datatype describes what kind of check this involves, which helps other patterns decide if they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/ inductive HeadCheck where -- match step that always succeeds: _, x, `($x), ... | unconditional -- match step based on kind and, optionally, arity of discriminant -- If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the -- same number of new patterns. -- We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by -- the node kind. -- without arity: `($x:k) -- with arity: any quotation without an antiquotation head pattern | shape (k : SyntaxNodeKind) (arity : Option Nat) -- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants -- for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children. -- example: `([$x, $xs,*, $y]) is `slice 2 2` | slice (numPrefix numSuffix : Nat) -- other, complicated match step that will probably only cover identical patterns -- example: antiquotation splices `($[...]*) | other (pat : Syntax) open HeadCheck /-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/ inductive MatchResult where -- Pattern agrees with head check, remove and transform remaining alternative. -- If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch. | covered (f : Alt → TermElabM Alt) (exhaustive : Bool) -- Pattern disagrees with head check, include in "no" branch only | uncovered -- Pattern is not quite sure yet; include unchanged in both branches | undecided open MatchResult /-- All necessary information on a pattern head. -/ structure HeadInfo where -- check induced by the pattern check : HeadCheck -- compute compatibility of pattern with given head check onMatch (taken : HeadCheck) : MatchResult -- actually run the specified head check, with the discriminant bound to `discr` doMatch (yes : (newDiscrs : List Syntax) → TermElabM Syntax) (no : TermElabM Syntax) : TermElabM Syntax /-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/ private def noOpMatchAdaptPats : HeadCheck → Alt → Alt | shape k (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs) | slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs) | _, alt => alt private def adaptRhs (fn : Syntax → TermElabM Syntax) : Alt → TermElabM Alt | (pats, rhs) => do (pats, ← fn rhs) private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo := let pat := alt.fst.head! let unconditionally (rhsFn) := pure { check := unconditional, doMatch := fun yes no => yes [], onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (match taken with | unconditional => true | _ => false) } -- quotation pattern if isQuot pat then let quoted := getQuotContent pat if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditionally pure else if quoted.isTokenAntiquot then unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·))) else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted |>.get! match getAntiquotTerm quoted with | `(_) => unconditionally pure | `($id:ident) => -- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by -- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `ident` here. -- -- if stx.isOfKind `ident then -- let id := stx; let e := stx; ... -- else -- let e := stx; ... let rhsFn := (`(let $id := discr; $(·))) if k == Name.anonymous then unconditionally rhsFn else pure { check := shape k none, onMatch := fun | other _ => undecided | taken@(shape k' sz) => if k' == k then covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone) else uncovered | _ => uncovered, doMatch := fun yes no => do `(cond (Syntax.isOfKind discr $(quote k)) $(← yes []) $(← no)), } | anti => throwErrorAt anti "unsupported antiquotation kind in pattern" else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then let anti := getAntiquotTerm (getAntiquotSuffixSpliceInner quoted[0]) unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with | `optional => `(let $anti := Syntax.getOptional? discr; $rhs) | `many => `(let $anti := Syntax.getArgs discr; $rhs) | `sepBy => `(let $anti := @SepArray.mk $(getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs) | k => throwErrorAt quoted "invalid antiquotation suffix splice kind '{k}'" else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure { check := other pat, onMatch := fun | other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided | _ => undecided, doMatch := fun yes no => do let splice := quoted[0] let k := antiquotSpliceKind? splice let contents := getAntiquotSpliceContents splice let ids ← getAntiquotationIds splice let yes ← yes [] let no ← no match k with | `optional => let nones := mkArray ids.size (← `(none)) `(let_delayed yes _ $ids* := $yes; if discr.isNone then yes () $[ $nones]* else match discr with | `($(mkNullNode contents)) => yes () $[ (some $ids)]* | _ => $no) | _ => let mut discrs ← `(Syntax.getArgs discr) if k == `sepBy then discrs ← `(Array.getSepElems $discrs) let tuple ← mkTuple ids let mut yes := yes let resId ← match ids with | #[id] => id | _ => for id in ids do yes ← `(let $id := tuples.map (fun $tuple => $id); $yes) `(tuples) let contents := if contents.size == 1 then contents[0] else mkNullNode contents `(match OptionM.run ($(discrs).sequenceMap fun | `($contents) => some $tuple | _ => none) with | some $resId => $yes | none => $no) } else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do /- pattern of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...` transform to ``` if discr.getNumArgs >= $quoted.getNumArgs - 1 then match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with | `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ... ``` -/ let numSuffix := quoted.getNumArgs - 1 - idx pure { check := slice idx numSuffix onMatch := fun | other _ => undecided | slice p s => if p == idx && s == numSuffix then let argPats := quoted.getArgs.mapIdx fun i arg => let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg Unhygienic.run `(`($(arg))) covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered doMatch := fun yes no => do let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·))) let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix)))) let suffixDiscrs ← (List.range numSuffix).mapM fun i => `(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i)))) `(ite (GE.ge discr.getNumArgs $(quote (quoted.getNumArgs - 1))) $(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs)) $(← no)) } else -- not an antiquotation, or an escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted let kind := quoted.getKind let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg))) pure { check := shape kind argPats.size, onMatch := fun | other _ => undecided | shape k' sz => if k' == kind && sz == argPats.size then covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered, doMatch := fun yes no => do let cond ← match kind with | `null => `(Syntax.matchesNull discr $(quote argPats.size)) | `ident => `(Syntax.matchesIdent discr $(quote quoted.getId)) | _ => `(Syntax.isOfKind discr $(quote kind)) let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i)) `(ite (Eq $cond true) $(← yes newDiscrs) $(← no)) } else match pat with | `(_) => unconditionally pure | `($id:ident) => unconditionally (`(let $id := discr; $(·))) | `($id:ident@$pat) => do let info ← getHeadInfo (pat::alt.1.tail!, alt.2) { info with onMatch := fun taken => match info.onMatch taken with | covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh | r => r } | _ => throwErrorAt pat "match (syntax) : unexpected pattern kind {pat}" -- Bind right-hand side to new `let_delayed` decl in order to prevent code duplication private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt) -- NOTE: new macro scope so that introduced bindings do not collide | (pats, rhs) => do if let `($f:ident $[ $args:ident]*) := rhs then -- looks simple enough/created by this function, skip return (floatedLetDecls, (pats, rhs)) withFreshMacroScope do match ← getPatternsVars pats.toArray with | #[] => -- no antiquotations => introduce Unit parameter to preserve evaluation order let rhs' ← `(rhs Unit.unit) (floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs')) | vars => let rhs' ← `(rhs $vars*) (floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs')) private partial def compileStxMatch (discrs : List Syntax) (alts : List Alt) : TermElabM Syntax := do trace[Elab.match_syntax] "match {discrs} with {alts}" match discrs, alts with | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => logError "non-exhaustive 'match' (syntax)" pure Syntax.missing | discr::discrs, alt::alts => do let info ← getHeadInfo alt let pat := alt.1.head! let alts ← (alt::alts).mapM fun alt => do ((← getHeadInfo alt).onMatch info.check, alt) let mut yesAlts := #[] let mut undecidedAlts := #[] let mut nonExhaustiveAlts := #[] let mut floatedLetDecls := #[] for alt in alts do let mut alt := alt match alt with | (covered f exh, alt) => -- we can only factor out a common check if there are no undecided patterns in between; -- otherwise we would change the order of alternatives if undecidedAlts.isEmpty then yesAlts ← yesAlts.push <$> f (alt.1.tail!, alt.2) if !exh then nonExhaustiveAlts := nonExhaustiveAlts.push alt else (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (undecided, alt) => (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (uncovered, alt) => nonExhaustiveAlts := nonExhaustiveAlts.push alt let mut stx ← info.doMatch (yes := fun newDiscrs => do let mut yesAlts := yesAlts if !undecidedAlts.isEmpty then -- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...` let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr) let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => $(alt.2)) let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*) yesAlts := yesAlts.push (pats, rhs) withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList) (no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList) for d in floatedLetDecls do stx ← `(let_delayed $d:letDecl; $stx) `(let discr := $discr; $stx) | _, _ => unreachable! def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do match stx with | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do if !patss.any (·.any (fun | `($id@$pat) => pat.isQuot | pat => pat.isQuot)) then -- no quotations => fall back to regular `match` throwUnsupportedSyntax let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList trace[Elab.match_syntax.result] "{stx}" stx | _ => throwUnsupportedSyntax @[builtinTermElab «match»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand builtin_initialize registerTraceClass `Elab.match_syntax registerTraceClass `Elab.match_syntax.result end Lean.Elab.Term.Quotation
0afd4269ad1ea545dd954b8578953c6076c7cea0
a047a4718edfa935d17231e9e6ecec8c7b701e05
/archive/sensitivity.lean
a8f0c8dd79e431481dd048471683fb0561c41ea9
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
15,513
lean
/- Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot -/ import tactic.fin_cases import tactic.apply_fun import linear_algebra.finite_dimensional import linear_algebra.dual import analysis.normed_space.basic /-! # Huang's sensitivity theorem A formalization of Hao Huang's sensitivity theorem: in the hypercube of dimension n ≥ 1, if one colors more than half the vertices then at least one vertex has at least √n colored neighbors. A fun summer collaboration by Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot, based on Don Knuth's account of the story (https://www.cs.stanford.edu/~knuth/papers/huang.pdf), using the Lean theorem prover (https://leanprover.github.io/), by Leonardo de Moura at Microsoft Research, and his collaborators (https://leanprover.github.io/people/), and using Lean's user maintained mathematics library (https://github.com/leanprover-community/mathlib). The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean -/ /-! The next two lines assert we do not want to give a constructive proof, but rather use classical logic. -/ noncomputable theory open_locale classical /-! We also want to use the notation `∑` for sums. -/ open_locale big_operators notation `|`x`|` := abs x notation `√` := real.sqrt open function bool linear_map fintype finite_dimensional dual_pair /-! ### The hypercube Notations: - `ℕ` denotes natural numbers (including zero). - `fin n` = {0, ⋯ , n - 1}. - `bool` = {`tt`, `ff`}. -/ /-- The hypercube in dimension `n`. -/ @[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool /-- The projection from `Q (n + 1)` to `Q n` forgetting the first value (ie. the image of zero). -/ def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ namespace Q /-! `n` will always denote a natural number. -/ variable (n : ℕ) /-- `Q 0` has a unique element. -/ instance : unique (Q 0) := ⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩ /-- `Q n` has 2^n elements. -/ lemma card : card (Q n) = 2^n := by simp [Q] /-! Until the end of this namespace, `n` will be an implicit argument (still a natural number). -/ variable {n} lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) := begin split, { rintro rfl, exact ⟨rfl, rfl⟩, }, { rintros ⟨h₀, h⟩, ext x, by_cases hx : x = 0, { rwa hx }, { rw ← fin.succ_pred x hx, convert congr_fun h (fin.pred x hx) } } end /-- The adjacency relation defining the graph structure on `Q n`: `p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/ def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i /-- In `Q 0`, no two vertices are adjacent. -/ lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q := by rintros ⟨v, _⟩; apply fin_zero_elim v /-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent iff their projections to `Q n` are equal. -/ lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) : p.adjacent q ↔ π p = π q := begin split, { rintros ⟨i, h_eq, h_uni⟩, ext x, by_contradiction hx, apply fin.succ_ne_zero x, rw [h_uni _ hx, h_uni _ h₀] }, { intro heq, use [0, h₀], intros y hy, contrapose! hy, rw ←fin.succ_pred _ hy, apply congr_fun heq } end /-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent iff their projections to `Q n` are adjacent. -/ lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) : p.adjacent q ↔ (π p).adjacent (π q) := begin split, { rintros ⟨i, h_eq, h_uni⟩, have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq), use [i.pred h_i, show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)), by rwa fin.succ_pred], intros y hy, simp [eq.symm (h_uni _ hy)] }, { rintros ⟨i, h_eq, h_uni⟩, use [i.succ, h_eq], intros y hy, rw [←fin.pred_inj, fin.pred_succ], { apply h_uni, change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ, simp [hy] }, { contrapose! hy, rw [hy, h₀] }, { apply fin.succ_ne_zero } } end @[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p := by simp only [adjacent, ne_comm] end Q /-! ### The vector space -/ /-- The free vector space on vertices of a hypercube, defined inductively. -/ def V : ℕ → Type | 0 := ℝ | (n+1) := V n × V n namespace V variables (n : ℕ) /-! `V n` is a real vector space whose equality relation is computable. -/ instance : decidable_eq (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : add_comm_group (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : vector_space ℝ (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } end V /-- The basis of `V` indexed by the hypercube, defined inductively. -/ noncomputable def e : Π {n}, Q n → V n | 0 := λ _, (1:ℝ) | (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x)) @[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl /-- The dual basis to `e`, defined inductively. -/ noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ | 0 _ := linear_map.id | (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _) ((ε $ π p).comp $ linear_map.snd _ _ _) variable {n : ℕ} lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 := begin induction n with n IH, { rw (show p = q, from subsingleton.elim p q), dsimp [ε, e], simp }, { dsimp [ε, e], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH], try { congr' 1, rw Q.succ_n_eq, finish }, try { erw (ε _).map_zero, have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish }, simp [this] } } } end /-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/ lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 := begin induction n with n ih, { dsimp [ε] at h, exact h (λ _, tt) }, { cases v with v₁ v₂, ext ; change _ = (0 : V n) ; simp only [] ; apply ih ; intro p ; [ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h), let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)], all_goals { specialize h q, rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|> rw [ε, show q 0 = ff, from rfl, cond_ff] at h, rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } } end /-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis and `ε` computes coefficients of decompositions of vectors on that basis. -/ def dual_pair_e_ε (n : ℕ) : dual_pair (@e n) (@ε n) := { eval := duality, total := @epsilon_total _ } /-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and, since this cardinal is finite, as a natural number in `findim_V` -/ lemma dim_V : vector_space.dim ℝ (V n) = 2^n := have vector_space.dim ℝ (V n) = (2^n : ℕ), by { rw [dim_eq_card_basis (dual_pair_e_ε _).is_basis, Q.card]; apply_instance }, by assumption_mod_cast instance : finite_dimensional ℝ (V n) := finite_dimensional.of_finite_basis (dual_pair_e_ε _).is_basis lemma findim_V : findim ℝ (V n) = 2^n := have _ := @dim_V n, by rw ←findim_eq_dim at this; assumption_mod_cast /-! ### The linear map -/ /-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$, defined inductively as a ℝ-linear map from `V n` to `V n`. -/ noncomputable def f : Π n, V n →ₗ[ℝ] V n | 0 := 0 | (n+1) := linear_map.prod (linear_map.coprod (f n) linear_map.id) (linear_map.coprod linear_map.id (-f n)) /-! The preceding definition uses linear map constructions to automatically get that `f` is linear, but its values are somewhat buried as a side-effect. The next two lemmas unbury them. -/ @[simp] lemma f_zero : f 0 = 0 := rfl lemma f_succ_apply (v : V (n+1)) : f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) := begin cases v, rw f, simp only [linear_map.id_apply, linear_map.prod_apply, prod.mk.inj_iff, linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply], exact ⟨rfl, rfl⟩ end /-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number is necessary since otherwise `n • v` refers to the multiplication defined using only the addition of `V`. -/ lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v := begin induction n with n IH; intro, { simpa only [nat.cast_zero, zero_smul] }, { cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel } end /-! We now compute the matrix of `f` in the `e` basis (`p` is the line index, `q` the column index). -/ lemma f_matrix : ∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 := begin induction n with n IH, { intros p q, dsimp [f], simp [Q.not_adjacent_zero] }, { intros p q, have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0, { split_ifs ; norm_num }, have f_map_zero := (show linear_map ℝ (V (n+0)) (V n), from f n).map_zero, dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq, Q.adj_iff_proj_adj] } } end /-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/ noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) := linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id /-! In the following lemmas, `m` will denote a natural number. -/ variables {m : ℕ} /-! Again we unpack what are the values of `g`. -/ lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) := by delta g; simp lemma g_injective : injective (g m) := begin rw g, intros x₁ x₂ h, simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff] at h, exact h.right end lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) : f (m + 1) w = √(m + 1) • w := begin rcases hv with ⟨v, rfl⟩, have : √(m+1) * √(m+1) = m+1 := real.mul_self_sqrt (by exact_mod_cast zero_le _), simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul], abel end /-! ### The main proof In this section, in order to enforce that `n` is positive, we write it as `m + 1` for some natural number `m`. -/ /-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/ notation `dim` X:70 := vector_space.dim ℝ ↥X /-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/ notation `fdim` := findim ℝ /-! `Span S` will denote the ℝ-subspace spanned by `S`. -/ notation `Span` := submodule.span ℝ /-! `Card X` will denote the cardinal of a subset of a finite type, as a natural number. -/ notation `Card` X:70 := X.to_finset.card /-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces, equipped with their subspace structures. The notations come from the general theory of lattices, with inf and sup (also known as meet and join). -/ /-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially intersects the range of `g m`. -/ lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) := begin let W := Span (e '' H), let img := (g m).range, suffices : 0 < dim (W ⊓ img), { simp only [exists_prop], exact_mod_cast exists_mem_ne_zero_of_dim_pos this }, have dim_le : dim (W ⊔ img) ≤ 2^(m + 1), { convert ← dim_submodule_le (W ⊔ img), apply dim_V }, have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m, { convert ← dim_sup_add_dim_inf_eq W img, rw ← dim_eq_injective (g m) g_injective, apply dim_V }, have dimW : dim W = card H, { have li : linear_independent ℝ (set.restrict e H) := linear_independent.comp (dual_pair_e_ε _).is_basis.1 _ subtype.val_injective, have hdW := dim_span li, rw set.range_restrict at hdW, convert hdW, rw [cardinal.mk_image_eq ((dual_pair_e_ε _).is_basis.injective zero_ne_one), cardinal.fintype_card] }, rw ← findim_eq_dim ℝ at ⊢ dim_le dim_add dimW, rw [← findim_eq_dim ℝ, ← findim_eq_dim ℝ] at dim_add, norm_cast at ⊢ dim_le dim_add dimW, rw nat.pow_succ at dim_le, rw set.to_finset_card at hH, linarith end theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) := begin rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩, have coeffs_support : ((dual_pair_e_ε (m+1)).coeffs y).support ⊆ H.to_finset, { intros p p_in, rw finsupp.mem_support_iff at p_in, rw set.mem_to_finset, exact (dual_pair_e_ε _).mem_of_mem_span y_mem_H p p_in }, obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|, from fintype.exists_max _, have H_q_pos : 0 < |ε q y|, { contrapose! y_ne, exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) }, refine ⟨q, (dual_pair_e_ε _).mem_of_mem_span y_mem_H q (abs_pos_iff.mp H_q_pos), _⟩, let s := √(m+1), suffices : s * |ε q y| ≤ ↑(_) * |ε q y|, from (mul_le_mul_right H_q_pos).mp ‹_›, let coeffs := (dual_pair_e_ε (m+1)).coeffs, calc s * (abs (ε q y)) = abs (ε q (s • y)) : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)] ... = abs (ε q (f (m+1) y)) : by rw [← f_image_g y (by simpa using y_mem_g)] ... = abs (ε q (f (m+1) (lc _ (coeffs y)))) : by rw (dual_pair_e_ε _).decomposition y ... = abs ((coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)): by { erw [(f $ m+1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ; apply_instance } ... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _ ... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix] ... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter] ... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p) ... = (finset.card ((coeffs y).support.filter (Q.adjacent q)): ℝ) * |coeffs y q| : by rw [← smul_eq_mul, ← finset.sum_const'] ... = (finset.card ((coeffs y).support ∩ (Q.adjacent q).to_finset): ℝ) * |coeffs y q| : by {congr, ext, simp, refl} ... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| : (mul_le_mul_right H_q_pos).mpr (by { norm_cast, exact finset.card_le_of_subset (by rw set.to_finset_inter; convert finset.inter_subset_inter_right coeffs_support) }) end
8d573c5867277cfbbcdaacfd93004a491bd2e2a0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/linear_recurrence.lean
1e9b19c88f5466759125e32d9febbbcedb5b57c6
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,601
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import data.polynomial.eval import linear_algebra.dimension /-! # Linear recurrence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Informally, a "linear recurrence" is an assertion of the form `∀ n : ℕ, u (n + d) = a 0 * u n + a 1 * u (n+1) + ... + a (d-1) * u (n+d-1)`, where `u` is a sequence, `d` is the *order* of the recurrence and the `a i` are its *coefficients*. In this file, we define the structure `linear_recurrence` so that `linear_recurrence.mk d a` represents the above relation, and we call a sequence `u` which verifies it a *solution* of the linear recurrence. We prove a few basic lemmas about this concept, such as : * the space of solutions is a submodule of `(ℕ → α)` (i.e a vector space if `α` is a field) * the function that maps a solution `u` to its first `d` terms builds a `linear_equiv` between the solution space and `fin d → α`, aka `α ^ d`. As a consequence, two solutions are equal if and only if their first `d` terms are equals. * a geometric sequence `q ^ n` is solution iff `q` is a root of a particular polynomial, which we call the *characteristic polynomial* of the recurrence Of course, although we can inductively generate solutions (cf `mk_sol`), the interesting part would be to determinate closed-forms for the solutions. This is currently *not implemented*, as we are waiting for definition and properties of eigenvalues and eigenvectors. -/ noncomputable theory open finset open_locale big_operators polynomial /-- A "linear recurrence relation" over a commutative semiring is given by its order `n` and `n` coefficients. -/ structure linear_recurrence (α : Type*) [comm_semiring α] := (order : ℕ) (coeffs : fin order → α) instance (α : Type*) [comm_semiring α] : inhabited (linear_recurrence α) := ⟨⟨0, default⟩⟩ namespace linear_recurrence section comm_semiring variables {α : Type*} [comm_semiring α] (E : linear_recurrence α) /-- We say that a sequence `u` is solution of `linear_recurrence order coeffs` when we have `u (n + order) = ∑ i : fin order, coeffs i * u (n + i)` for any `n`. -/ def is_solution (u : ℕ → α) := ∀ n, u (n + E.order) = ∑ i, E.coeffs i * u (n + i) /-- A solution of a `linear_recurrence` which satisfies certain initial conditions. We will prove this is the only such solution. -/ def mk_sol (init : fin E.order → α) : ℕ → α | n := if h : n < E.order then init ⟨n, h⟩ else ∑ k : fin E.order, have n - E.order + k < n := begin rw [add_comm, ← add_tsub_assoc_of_le (not_lt.mp h), tsub_lt_iff_left], { exact add_lt_add_right k.is_lt n }, { convert add_le_add (zero_le (k : ℕ)) (not_lt.mp h), simp only [zero_add] } end, E.coeffs k * mk_sol (n - E.order + k) /-- `E.mk_sol` indeed gives solutions to `E`. -/ lemma is_sol_mk_sol (init : fin E.order → α) : E.is_solution (E.mk_sol init) := λ n, by rw mk_sol; simp /-- `E.mk_sol init`'s first `E.order` terms are `init`. -/ lemma mk_sol_eq_init (init : fin E.order → α) : ∀ n : fin E.order, E.mk_sol init n = init n := λ n, by { rw mk_sol, simp only [n.is_lt, dif_pos, fin.mk_coe, fin.eta] } /-- If `u` is a solution to `E` and `init` designates its first `E.order` values, then `∀ n, u n = E.mk_sol init n`. -/ lemma eq_mk_of_is_sol_of_eq_init {u : ℕ → α} {init : fin E.order → α} (h : E.is_solution u) (heq : ∀ n : fin E.order, u n = init n) : ∀ n, u n = E.mk_sol init n | n := if h' : n < E.order then by rw mk_sol; simp only [h', dif_pos]; exact_mod_cast heq ⟨n, h'⟩ else begin rw [mk_sol, ← tsub_add_cancel_of_le (le_of_not_lt h'), h (n-E.order)], simp [h'], congr' with k, exact have wf : n - E.order + k < n := begin rw [add_comm, ← add_tsub_assoc_of_le (not_lt.mp h'), tsub_lt_iff_left], { exact add_lt_add_right k.is_lt n }, { convert add_le_add (zero_le (k : ℕ)) (not_lt.mp h'), simp only [zero_add] } end, by rw eq_mk_of_is_sol_of_eq_init end /-- If `u` is a solution to `E` and `init` designates its first `E.order` values, then `u = E.mk_sol init`. This proves that `E.mk_sol init` is the only solution of `E` whose first `E.order` values are given by `init`. -/ lemma eq_mk_of_is_sol_of_eq_init' {u : ℕ → α} {init : fin E.order → α} (h : E.is_solution u) (heq : ∀ n : fin E.order, u n = init n) : u = E.mk_sol init := funext (E.eq_mk_of_is_sol_of_eq_init h heq) /-- The space of solutions of `E`, as a `submodule` over `α` of the module `ℕ → α`. -/ def sol_space : submodule α (ℕ → α) := { carrier := {u | E.is_solution u}, zero_mem' := λ n, by simp, add_mem' := λ u v hu hv n, by simp [mul_add, sum_add_distrib, hu n, hv n], smul_mem' := λ a u hu n, by simp [hu n, mul_sum]; congr'; ext; ac_refl } /-- Defining property of the solution space : `u` is a solution iff it belongs to the solution space. -/ lemma is_sol_iff_mem_sol_space (u : ℕ → α) : E.is_solution u ↔ u ∈ E.sol_space := iff.rfl /-- The function that maps a solution `u` of `E` to its first `E.order` terms as a `linear_equiv`. -/ def to_init : E.sol_space ≃ₗ[α] (fin E.order → α) := { to_fun := λ u x, (u : ℕ → α) x, map_add' := λ u v, by { ext, simp }, map_smul' := λ a u, by { ext, simp }, inv_fun := λ u, ⟨E.mk_sol u, E.is_sol_mk_sol u⟩, left_inv := λ u, by ext n; symmetry; apply E.eq_mk_of_is_sol_of_eq_init u.2; intros k; refl, right_inv := λ u, function.funext_iff.mpr (λ n, E.mk_sol_eq_init u n) } /-- Two solutions are equal iff they are equal on `range E.order`. -/ lemma sol_eq_of_eq_init (u v : ℕ → α) (hu : E.is_solution u) (hv : E.is_solution v) : u = v ↔ set.eq_on u v ↑(range E.order) := begin refine iff.intro (λ h x hx, h ▸ rfl) _, intro h, set u' : ↥(E.sol_space) := ⟨u, hu⟩, set v' : ↥(E.sol_space) := ⟨v, hv⟩, change u'.val = v'.val, suffices h' : u' = v', from h' ▸ rfl, rw [← E.to_init.to_equiv.apply_eq_iff_eq, linear_equiv.coe_to_equiv], ext x, exact_mod_cast h (mem_range.mpr x.2) end /-! `E.tuple_succ` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`, where `n := E.order`. This operation is quite useful for determining closed-form solutions of `E`. -/ /-- `E.tuple_succ` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`, where `n := E.order`. -/ def tuple_succ : (fin E.order → α) →ₗ[α] (fin E.order → α) := { to_fun := λ X i, if h : (i : ℕ) + 1 < E.order then X ⟨i+1, h⟩ else (∑ i, E.coeffs i * X i), map_add' := λ x y, begin ext i, split_ifs ; simp [h, mul_add, sum_add_distrib], end, map_smul' := λ x y, begin ext i, split_ifs ; simp [h, mul_sum], exact sum_congr rfl (λ x _, by ac_refl), end } end comm_semiring section strong_rank_condition -- note: `strong_rank_condition` is the same as `nontrivial` on `comm_ring`s, but that result, -- `comm_ring_strong_rank_condition`, is in a much later file. variables {α : Type*} [comm_ring α] [strong_rank_condition α] (E : linear_recurrence α) /-- The dimension of `E.sol_space` is `E.order`. -/ lemma sol_space_rank : module.rank α E.sol_space = E.order := begin letI := nontrivial_of_invariant_basis_number α, exact @rank_fin_fun α _ _ E.order ▸ E.to_init.rank_eq end end strong_rank_condition section comm_ring variables {α : Type*} [comm_ring α] (E : linear_recurrence α) /-- The characteristic polynomial of `E` is `X ^ E.order - ∑ i : fin E.order, (E.coeffs i) * X ^ i`. -/ def char_poly : α[X] := polynomial.monomial E.order 1 - (∑ i : fin E.order, polynomial.monomial i (E.coeffs i)) /-- The geometric sequence `q^n` is a solution of `E` iff `q` is a root of `E`'s characteristic polynomial. -/ lemma geom_sol_iff_root_char_poly (q : α) : E.is_solution (λ n, q^n) ↔ E.char_poly.is_root q := begin rw [char_poly, polynomial.is_root.def, polynomial.eval], simp only [polynomial.eval₂_finset_sum, one_mul, ring_hom.id_apply, polynomial.eval₂_monomial, polynomial.eval₂_sub], split, { intro h, simpa [sub_eq_zero] using h 0 }, { intros h n, simp only [pow_add, sub_eq_zero.mp h, mul_sum], exact sum_congr rfl (λ _ _, by ring) } end end comm_ring end linear_recurrence
93c003e788ddf61b2aec3be4f377b5660abf6b4e
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/ring_theory/algebra_tower.lean
6b2ad58086cf6af6abd045f055b2db29b23c2ed1
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,308
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.tower import algebra.invertible import linear_algebra.basis import ring_theory.adjoin /-! # Towers of algebras We set up the basic theory of algebra towers. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. In `field_theory/tower.lean` we use this to prove the tower law for finite extensions, that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`. In this file we prepare the main lemma: if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the base rings to be a field, so we also generalize the lemma to rings in this file. -/ universes u v w u₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) namespace is_scalar_tower section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R) {S A B} instance polynomial : is_scalar_tower R S (polynomial A) := of_algebra_map_eq $ λ x, congr_arg polynomial.C $ algebra_map_apply R S A x variables (R S A) theorem aeval_apply (x : A) (p : polynomial R) : polynomial.aeval x p = polynomial.aeval x (polynomial.map (algebra_map R S) p) := by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.eval₂_map, algebra_map_eq R S A] /-- Suppose that `R -> S -> A` is a tower of algebras. If an element `r : R` is invertible in `S`, then it is invertible in `A`. -/ def invertible.algebra_tower (r : R) [invertible (algebra_map R S r)] : invertible (algebra_map R A r) := invertible.copy (invertible.map (algebra_map S A : S →* A) (algebra_map R S r)) (algebra_map R A r) (by rw [ring_hom.coe_monoid_hom, is_scalar_tower.algebra_map_apply R S A]) /-- A natural number that is invertible when coerced to `R` is also invertible when coerced to any `R`-algebra. -/ def invertible_algebra_coe_nat (n : ℕ) [inv : invertible (n : R)] : invertible (n : A) := by { haveI : invertible (algebra_map ℕ R n) := inv, exact invertible.algebra_tower ℕ R A n } end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] lemma algebra_map_aeval (x : A) (p : polynomial R) : algebra_map A B (polynomial.aeval x p) = polynomial.aeval (algebra_map A B x) p := by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.hom_eval₂, ←is_scalar_tower.algebra_map_eq] lemma aeval_eq_zero_of_aeval_algebra_map_eq_zero {x : A} {p : polynomial R} (h : function.injective (algebra_map A B)) (hp : polynomial.aeval (algebra_map A B x) p = 0) : polynomial.aeval x p = 0 := begin rw [← algebra_map_aeval, ← (algebra_map A B).map_zero] at hp, exact h hp, end lemma aeval_eq_zero_of_aeval_algebra_map_eq_zero_field {R A B : Type*} [comm_semiring R] [field A] [comm_semiring B] [nontrivial B] [algebra R A] [algebra R B] [algebra A B] [is_scalar_tower R A B] {x : A} {p : polynomial R} (h : polynomial.aeval (algebra_map A B x) p = 0) : polynomial.aeval x p = 0 := aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B (algebra_map A B).injective h end comm_semiring end is_scalar_tower namespace algebra theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] (s : set S) : adjoin R (algebra_map S (comap R S A) '' s) = subalgebra.map (adjoin R s) (to_comap R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w) [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (s : set S) : adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_scalar_tower.to_alg_hom R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) lemma adjoin_res (C D E : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [algebra C D] [algebra C E] [algebra D E] [is_scalar_tower C D E] (S : set E) : (algebra.adjoin D S).res C = ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)).under (algebra.adjoin ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) S) := begin suffices : set.range (algebra_map D E) = set.range (algebra_map ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) E), { ext x, change x ∈ subsemiring.closure (_ ∪ S) ↔ x ∈ subsemiring.closure (_ ∪ S), rw this }, ext x, split, { rintros ⟨y, hy⟩, exact ⟨⟨algebra_map D E y, ⟨y, ⟨algebra.mem_top, rfl⟩⟩⟩, hy⟩ }, { rintros ⟨⟨y, ⟨z, ⟨h0, h1⟩⟩⟩, h2⟩, exact ⟨z, eq.trans h1 h2⟩ }, end lemma adjoin_res_eq_adjoin_res (C D E F : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [comm_semiring F] [algebra C D] [algebra C E] [algebra C F] [algebra D F] [algebra E F] [is_scalar_tower C D F] [is_scalar_tower C E F] {S : set D} {T : set E} (hS : algebra.adjoin C S = ⊤) (hT : algebra.adjoin C T = ⊤) : (algebra.adjoin E (algebra_map D F '' S)).res C = (algebra.adjoin D (algebra_map E F '' T)).res C := by { rw [adjoin_res, adjoin_res, ←hS, ←hT, ←algebra.adjoin_image, ←algebra.adjoin_image, ←alg_hom.coe_to_ring_hom, ←alg_hom.coe_to_ring_hom, is_scalar_tower.coe_to_alg_hom, is_scalar_tower.coe_to_alg_hom, ←algebra.adjoin_union, ←algebra.adjoin_union, set.union_comm] } end algebra namespace subalgebra open is_scalar_tower section comm_semiring variables (R) {S A} [comm_semiring R] [comm_semiring S] [comm_semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] @[simp] lemma aeval_coe {S : subalgebra R A} {x : S} {p : polynomial R} : polynomial.aeval (x : A) p = polynomial.aeval x p := (algebra_map_aeval R S A x p).symm end comm_semiring end subalgebra section open_locale classical lemma algebra.fg_trans' {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (hRS : (⊤ : subalgebra R S).fg) (hSA : (⊤ : subalgebra S A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := hRS, ⟨t, ht⟩ := hSA in ⟨s.image (algebra_map S A) ∪ t, by rw [finset.coe_union, finset.coe_image, algebra.adjoin_union, algebra.adjoin_algebra_map, hs, algebra.map_top, is_scalar_tower.range_under_adjoin, ht, subalgebra.res_top]⟩ end section ring open finsupp open_locale big_operators classical universes v₁ w₁ variables {R S A} variables [comm_ring R] [ring S] [add_comm_group A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {ι' : Type w₁} {c : ι' → A} (hb : linear_independent R b) (hc : linear_independent S c) : linear_independent R (λ p : ι × ι', b p.1 • c p.2) := begin rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩, by_cases hik : (i, k) ∈ s, { have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0, { rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp, show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm }, rw [finset.sum_product, finset.sum_comm] at h1, simp_rw [← smul_assoc, ← finset.sum_smul] at h1, exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) }, exact hg _ hik end theorem is_basis.smul {ι : Type v₁} {b : ι → S} {ι' : Type w₁} {c : ι' → A} (hb : is_basis R b) (hc : is_basis S c) : is_basis R (λ p : ι × ι', b p.1 • c p.2) := ⟨linear_independent_smul hb.1 hc.1, by rw [← set.range_smul_range, submodule.span_smul hb.2, ← submodule.restrict_scalars_top R S A, submodule.restrict_scalars_inj, hc.2]⟩ theorem is_basis.smul_repr {ι ι' : Type*} {b : ι → S} {c : ι' → A} (hb : is_basis R b) (hc : is_basis S c) (x : A) (ij : ι × ι') : (hb.smul hc).repr x ij = hb.repr (hc.repr x ij.2) ij.1 := begin apply (hb.smul hc).repr_apply_eq, { intros x y, ext, simp only [linear_map.map_add, add_apply, pi.add_apply] }, { intros c x, ext, simp only [← is_scalar_tower.algebra_map_smul S c x, linear_map.map_smul, smul_eq_mul, ← algebra.smul_def, smul_apply, pi.smul_apply] }, rintros ij, ext ij', rw single_apply, split_ifs with hij, { simp [hij] }, rw [linear_map.map_smul, smul_apply, hc.repr_self_apply], split_ifs with hj, { simp [hj, show ¬ (ij.1 = ij'.1), from λ hi, hij (prod.ext hi hj)] }, simp end theorem is_basis.smul_repr_mk {ι ι' : Type*} {b : ι → S} {c : ι' → A} (hb : is_basis R b) (hc : is_basis S c) (x : A) (i : ι) (j : ι') : (hb.smul hc).repr x (i, j) = hb.repr (hc.repr x j) i := by simp [is_basis.smul_repr] end ring section artin_tate variables (C : Type*) variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C] open finset submodule open_locale classical lemma exists_subalgebra_of_fg (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) : ∃ B₀ : subalgebra A B, B₀.fg ∧ (⊤ : submodule B₀ C).fg := begin cases hAC with x hx, cases hBC with y hy, have := hy, simp_rw [eq_top_iff', mem_span_finset] at this, choose f hf, let s : finset B := (finset.product (x ∪ (y * y)) y).image (function.uncurry f), have hsx : ∀ (xi ∈ x) (yj ∈ y), f xi yj ∈ s := λ xi hxi yj hyj, show function.uncurry f (xi, yj) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_left _ hxi, hyj⟩, have hsy : ∀ (yi yj yk ∈ y), f (yi * yj) yk ∈ s := λ yi yj yk hyi hyj hyk, show function.uncurry f (yi * yj, yk) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_right _ $ finset.mul_mem_mul hyi hyj, hyk⟩, have hxy : ∀ xi ∈ x, xi ∈ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) := λ xi hxi, hf xi ▸ sum_mem _ (λ yj hyj, smul_mem (span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C)) ⟨f xi yj, algebra.subset_adjoin $ hsx xi hxi yj hyj⟩ (subset_span $ mem_insert_of_mem hyj)), have hyy : span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) * span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) ≤ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C), { rw [span_mul_span, span_le, coe_insert], rintros _ ⟨yi, yj, rfl | hyi, rfl | hyj, rfl⟩, { rw mul_one, exact subset_span (set.mem_insert _ _) }, { rw one_mul, exact subset_span (set.mem_insert_of_mem _ hyj) }, { rw mul_one, exact subset_span (set.mem_insert_of_mem _ hyi) }, { rw ← hf (yi * yj), exact (submodule.mem_coe _).2 (sum_mem _ $ λ yk hyk, smul_mem (span (algebra.adjoin A (↑s : set B)) (insert 1 ↑y : set C)) ⟨f (yi * yj) yk, algebra.subset_adjoin $ hsy yi yj yk hyi hyj hyk⟩ (subset_span $ set.mem_insert_of_mem _ hyk : yk ∈ _)) } }, refine ⟨algebra.adjoin A (↑s : set B), subalgebra.fg_adjoin_finset _, insert 1 y, _⟩, refine restrict_scalars_injective A _ _ _, rw [restrict_scalars_top, eq_top_iff, ← algebra.coe_top, ← hx, algebra.adjoin_eq_span, span_le], refine λ r hr, monoid.in_closure.rec_on hr hxy (subset_span $ mem_insert_self _ _) (λ p q _ _ hp hq, hyy $ submodule.mul_mem_mul hp hq) end /-- Artin--Tate lemma: if A ⊆ B ⊆ C is a chain of subrings of commutative rings, and A is noetherian, and C is algebra-finite over A, and C is module-finite over B, then B is algebra-finite over A. References: Atiyah--Macdonald Proposition 7.8; Stacks 00IS; Altman--Kleiman 16.17. -/ theorem fg_of_fg_of_fg [is_noetherian_ring A] (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) (hBCi : function.injective (algebra_map B C)) : (⊤ : subalgebra A B).fg := let ⟨B₀, hAB₀, hB₀C⟩ := exists_subalgebra_of_fg A B C hAC hBC in algebra.fg_trans' (B₀.fg_top.2 hAB₀) $ subalgebra.fg_of_submodule_fg $ have is_noetherian_ring B₀, from is_noetherian_ring_of_fg hAB₀, have is_noetherian B₀ C, by exactI is_noetherian_of_fg_of_noetherian' hB₀C, by exactI fg_of_injective (is_scalar_tower.to_alg_hom B₀ B C).to_linear_map (linear_map.ker_eq_bot.2 hBCi) end artin_tate section alg_hom_tower variables {A} {C D : Type*} [comm_semiring A] [comm_semiring C] [comm_semiring D] [algebra A C] [algebra A D] variables (f : C →ₐ[A] D) (B) [comm_semiring B] [algebra A B] [algebra B C] [is_scalar_tower A B C] /-- Restrict the domain of an `alg_hom`. -/ def alg_hom.restrict_domain : B →ₐ[A] D := f.comp (is_scalar_tower.to_alg_hom A B C) /-- Extend the scalars of an `alg_hom`. -/ def alg_hom.extend_scalars : @alg_hom B C D _ _ _ _ (f.restrict_domain B).to_ring_hom.to_algebra := { commutes' := λ _, rfl .. f } variables {B} /-- `alg_hom`s from the top of a tower are equivalent to a pair of `alg_hom`s. -/ def alg_hom_equiv_sigma : (C →ₐ[A] D) ≃ Σ (f : B →ₐ[A] D), @alg_hom B C D _ _ _ _ f.to_ring_hom.to_algebra := { to_fun := λ f, ⟨f.restrict_domain B, f.extend_scalars B⟩, inv_fun := λ fg, @is_scalar_tower.restrict_base A _ _ _ _ _ _ _ _ _ fg.1.to_ring_hom.to_algebra _ _ _ _ fg.2, left_inv := λ f, by { dsimp only, ext, refl }, right_inv := begin rintros ⟨⟨f, _, _, _, _, _⟩, g, _, _, _, _, hg⟩, have : f = λ x, g (algebra_map B C x) := by { ext, exact (hg x).symm }, subst this, refl, end } end alg_hom_tower
659614f0d45995926774b7965cc934b7cd273f24
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/hall/basic.lean
b150a76c13cf99902697c24bd3ed4a66dbf6fd58
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,273
lean
/- Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller -/ import combinatorics.hall.finite import category_theory.cofiltered_system import data.rel /-! # Hall's Marriage Theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a list of finite subsets $X_1, X_2, \dots, X_n$ of some given set $S$, P. Hall in [Hall1935] gave a necessary and sufficient condition for there to be a list of distinct elements $x_1, x_2, \dots, x_n$ with $x_i\in X_i$ for each $i$: it is when for each $k$, the union of every $k$ of these subsets has at least $k$ elements. Rather than a list of finite subsets, one may consider indexed families `t : ι → finset α` of finite subsets with `ι` a `fintype`, and then the list of distinct representatives is given by an injective function `f : ι → α` such that `∀ i, f i ∈ t i`, called a *matching*. This version is formalized as `finset.all_card_le_bUnion_card_iff_exists_injective'` in a separate module. The theorem can be generalized to remove the constraint that `ι` be a `fintype`. As observed in [Halpern1966], one may use the constrained version of the theorem in a compactness argument to remove this constraint. The formulation of compactness we use is that inverse limits of nonempty finite sets are nonempty (`nonempty_sections_of_finite_inverse_system`), which uses the Tychonoff theorem. The core of this module is constructing the inverse system: for every finite subset `ι'` of `ι`, we can consider the matchings on the restriction of the indexed family `t` to `ι'`. ## Main statements * `finset.all_card_le_bUnion_card_iff_exists_injective` is in terms of `t : ι → finset α`. * `fintype.all_card_le_rel_image_card_iff_exists_injective` is in terms of a relation `r : α → β → Prop` such that `rel.image r {a}` is a finite set for all `a : α`. * `fintype.all_card_le_filter_rel_iff_exists_injective` is in terms of a relation `r : α → β → Prop` on finite types, with the Hall condition given in terms of `finset.univ.filter`. ## Todo * The statement of the theorem in terms of bipartite graphs is in preparation. ## Tags Hall's Marriage Theorem, indexed families -/ open finset universes u v /-- The set of matchings for `t` when restricted to a `finset` of `ι`. -/ def hall_matchings_on {ι : Type u} {α : Type v} (t : ι → finset α) (ι' : finset ι) := {f : ι' → α | function.injective f ∧ ∀ x, f x ∈ t x} /-- Given a matching on a finset, construct the restriction of that matching to a subset. -/ def hall_matchings_on.restrict {ι : Type u} {α : Type v} (t : ι → finset α) {ι' ι'' : finset ι} (h : ι' ⊆ ι'') (f : hall_matchings_on t ι'') : hall_matchings_on t ι' := begin refine ⟨λ i, f.val ⟨i, h i.property⟩, _⟩, cases f.property with hinj hc, refine ⟨_, λ i, hc ⟨i, h i.property⟩⟩, rintro ⟨i, hi⟩ ⟨j, hj⟩ hh, simpa only [subtype.mk_eq_mk] using hinj hh, end /-- When the Hall condition is satisfied, the set of matchings on a finite set is nonempty. This is where `finset.all_card_le_bUnion_card_iff_exists_injective'` comes into the argument. -/ lemma hall_matchings_on.nonempty {ι : Type u} {α : Type v} [decidable_eq α] (t : ι → finset α) (h : (∀ (s : finset ι), s.card ≤ (s.bUnion t).card)) (ι' : finset ι) : nonempty (hall_matchings_on t ι') := begin classical, refine ⟨classical.indefinite_description _ _⟩, apply (all_card_le_bUnion_card_iff_exists_injective' (λ (i : ι'), t i)).mp, intro s', convert h (s'.image coe) using 1, simp only [card_image_of_injective s' subtype.coe_injective], rw image_bUnion, end /-- This is the `hall_matchings_on` sets assembled into a directed system. -/ -- TODO: This takes a long time to elaborate for an unknown reason. def hall_matchings_functor {ι : Type u} {α : Type v} (t : ι → finset α) : (finset ι)ᵒᵖ ⥤ Type (max u v) := { obj := λ ι', hall_matchings_on t ι'.unop, map := λ ι' ι'' g f, hall_matchings_on.restrict t (category_theory.le_of_hom g.unop) f } instance hall_matchings_on.finite {ι : Type u} {α : Type v} (t : ι → finset α) (ι' : finset ι) : finite (hall_matchings_on t ι') := begin classical, rw hall_matchings_on, let g : hall_matchings_on t ι' → (ι' → ι'.bUnion t), { rintro f i, refine ⟨f.val i, _⟩, rw mem_bUnion, exact ⟨i, i.property, f.property.2 i⟩ }, apply finite.of_injective g, intros f f' h, simp only [g, function.funext_iff, subtype.val_eq_coe] at h, ext a, exact h a, end /-- This is the version of **Hall's Marriage Theorem** in terms of indexed families of finite sets `t : ι → finset α`. It states that there is a set of distinct representatives if and only if every union of `k` of the sets has at least `k` elements. Recall that `s.bUnion t` is the union of all the sets `t i` for `i ∈ s`. This theorem is bootstrapped from `finset.all_card_le_bUnion_card_iff_exists_injective'`, which has the additional constraint that `ι` is a `fintype`. -/ theorem finset.all_card_le_bUnion_card_iff_exists_injective {ι : Type u} {α : Type v} [decidable_eq α] (t : ι → finset α) : (∀ (s : finset ι), s.card ≤ (s.bUnion t).card) ↔ (∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x) := begin split, { intro h, /- Set up the functor -/ haveI : ∀ (ι' : (finset ι)ᵒᵖ), nonempty ((hall_matchings_functor t).obj ι') := λ ι', hall_matchings_on.nonempty t h ι'.unop, classical, haveI : Π (ι' : (finset ι)ᵒᵖ), finite ((hall_matchings_functor t).obj ι') := begin intro ι', rw [hall_matchings_functor], apply_instance, end, /- Apply the compactness argument -/ obtain ⟨u, hu⟩ := nonempty_sections_of_finite_inverse_system (hall_matchings_functor t), /- Interpret the resulting section of the inverse limit -/ refine ⟨_, _, _⟩, { /- Build the matching function from the section -/ exact λ i, (u (opposite.op ({i} : finset ι))).val ⟨i, by simp only [opposite.unop_op, mem_singleton]⟩, }, { /- Show that it is injective -/ intros i i', have subi : ({i} : finset ι) ⊆ {i,i'} := by simp, have subi' : ({i'} : finset ι) ⊆ {i,i'} := by simp, have le : ∀ {s t : finset ι}, s ⊆ t → s ≤ t := λ _ _ h, h, rw [←hu (category_theory.hom_of_le (le subi)).op, ←hu (category_theory.hom_of_le (le subi')).op], let uii' := u (opposite.op ({i,i'} : finset ι)), exact λ h, subtype.mk_eq_mk.mp (uii'.property.1 h), }, { /- Show that it maps each index to the corresponding finite set -/ intro i, apply (u (opposite.op ({i} : finset ι))).property.2, }, }, { /- The reverse direction is a straightforward cardinality argument -/ rintro ⟨f, hf₁, hf₂⟩ s, rw ←finset.card_image_of_injective s hf₁, apply finset.card_le_of_subset, intro _, rw [finset.mem_image, finset.mem_bUnion], rintros ⟨x, hx, rfl⟩, exact ⟨x, hx, hf₂ x⟩, }, end /-- Given a relation such that the image of every singleton set is finite, then the image of every finite set is finite. -/ instance {α : Type u} {β : Type v} [decidable_eq β] (r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})] (A : finset α) : fintype (rel.image r A) := begin have h : rel.image r A = (A.bUnion (λ a, (rel.image r {a}).to_finset) : set β), { ext, simp [rel.image], }, rw [h], apply finset_coe.fintype, end /-- This is a version of **Hall's Marriage Theorem** in terms of a relation between types `α` and `β` such that `α` is finite and the image of each `x : α` is finite (it suffices for `β` to be finite; see `fintype.all_card_le_filter_rel_iff_exists_injective`). There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`. Note: if `[fintype β]`, then there exist instances for `[∀ (a : α), fintype (rel.image r {a})]`. -/ theorem fintype.all_card_le_rel_image_card_iff_exists_injective {α : Type u} {β : Type v} [decidable_eq β] (r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})] : (∀ (A : finset α), A.card ≤ fintype.card (rel.image r A)) ↔ (∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) := begin let r' := λ a, (rel.image r {a}).to_finset, have h : ∀ (A : finset α), fintype.card (rel.image r A) = (A.bUnion r').card, { intro A, rw ←set.to_finset_card, apply congr_arg, ext b, simp [rel.image], }, have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x, { simp [rel.image], }, simp only [h, h'], apply finset.all_card_le_bUnion_card_iff_exists_injective, end /-- This is a version of **Hall's Marriage Theorem** in terms of a relation to a finite type. There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`. It is like `fintype.all_card_le_rel_image_card_iff_exists_injective` but uses `finset.filter` rather than `rel.image`. -/ /- TODO: decidable_pred makes Yael sad. When an appropriate decidable_rel-like exists, fix it. -/ theorem fintype.all_card_le_filter_rel_iff_exists_injective {α : Type u} {β : Type v} [fintype β] (r : α → β → Prop) [∀ a, decidable_pred (r a)] : (∀ (A : finset α), A.card ≤ (univ.filter (λ (b : β), ∃ a ∈ A, r a b)).card) ↔ (∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) := begin haveI := classical.dec_eq β, let r' := λ a, univ.filter (λ b, r a b), have h : ∀ (A : finset α), (univ.filter (λ (b : β), ∃ a ∈ A, r a b)) = (A.bUnion r'), { intro A, ext b, simp, }, have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x, { simp, }, simp_rw [h, h'], apply finset.all_card_le_bUnion_card_iff_exists_injective, end
f155e5e845dcaf6853e4de492a790a3966e3a69d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/special_functions/pow/deriv.lean
a65165d8bd4ef4f3752448b26ae273906091f64b
[ "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
27,598
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.pow.continuity import analysis.special_functions.complex.log_deriv import analysis.calculus.extend_deriv import analysis.calculus.deriv.prod import analysis.special_functions.log.deriv import analysis.special_functions.trigonometric.deriv /-! # Derivatives of power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We also prove differentiability and provide derivatives for the power functions `x ^ y`. -/ noncomputable theory open_locale classical real topology nnreal ennreal filter open filter namespace complex lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_left_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, mul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_fderiv_at_cpow' {x y : ℂ} (hp : 0 < x.re ∨ x.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((y * x ^ (y - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (x ^ y * log x) • continuous_linear_map.snd ℂ ℂ ℂ) (x, y) := @has_strict_fderiv_at_cpow (x, y) hp lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section fderiv open complex variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf /-- Although `λ x, x ^ r` for fixed `r` is *not* complex-differentiable along the negative real line, it is still real-differentiable, and the derivative is what one would formally expect. -/ lemma has_deriv_at_of_real_cpow {x : ℝ} (hx : x ≠ 0) {r : ℂ} (hr : r ≠ -1) : has_deriv_at (λ y:ℝ, (y:ℂ) ^ (r + 1) / (r + 1)) (x ^ r) x := begin rw [ne.def, ←add_eq_zero_iff_eq_neg, ←ne.def] at hr, rcases lt_or_gt_of_ne hx.symm with hx | hx, { -- easy case : `0 < x` convert (((has_deriv_at_id (x:ℂ)).cpow_const _).div_const (r + 1)).comp_of_real, { rw [add_sub_cancel, id.def, mul_one, mul_comm, mul_div_cancel _ hr] }, { rw [id.def, of_real_re], exact or.inl hx } }, { -- harder case : `x < 0` have : ∀ᶠ (y:ℝ) in nhds x, (y:ℂ) ^ (r + 1) / (r + 1) = (-y:ℂ) ^ (r + 1) * exp (π * I * (r + 1)) / (r + 1), { refine filter.eventually_of_mem (Iio_mem_nhds hx) (λ y hy, _), rw of_real_cpow_of_nonpos (le_of_lt hy) }, refine has_deriv_at.congr_of_eventually_eq _ this, rw of_real_cpow_of_nonpos (le_of_lt hx), suffices : has_deriv_at (λ (y : ℝ), (-↑y) ^ (r + 1) * exp (↑π * I * (r + 1))) ((r + 1) * (-↑x) ^ r * exp (↑π * I * r)) x, { convert this.div_const (r + 1) using 1, conv_rhs { rw [mul_assoc, mul_comm, mul_div_cancel _ hr] } }, rw [mul_add ((π:ℂ) * _), mul_one, exp_add, exp_pi_mul_I, mul_comm (_ : ℂ) (-1 : ℂ), neg_one_mul], simp_rw [mul_neg, ←neg_mul, ←of_real_neg], suffices : has_deriv_at (λ (y : ℝ), (↑-y) ^ (r + 1)) (-(r + 1) * (↑-x) ^ r) x, { convert this.neg.mul_const _, ring }, suffices : has_deriv_at (λ (y : ℝ), (↑y) ^ (r + 1)) ((r + 1) * (↑-x) ^ r) (-x), { convert @has_deriv_at.scomp ℝ _ ℂ _ _ x ℝ _ _ _ _ _ _ _ _ this (has_deriv_at_neg x) using 1, rw [real_smul, of_real_neg 1, of_real_one], ring }, suffices : has_deriv_at (λ (y : ℂ), y ^ (r + 1)) ((r + 1) * (↑-x) ^ r) (↑-x), { exact this.comp_of_real }, conv in ((↑_) ^ _) { rw (by ring : r = (r + 1) - 1) }, convert (has_deriv_at_id ((-x : ℝ) : ℂ)).cpow_const _ using 1, { simp }, { left, rwa [id.def, of_real_re, neg_pos] } }, end end deriv namespace real variables {x y z : ℝ} /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `0 < p.fst`. -/ lemma has_strict_fderiv_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.1) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from (continuous_at_fst.eventually (lt_mem_nhds hp)).mono (λ p hp, rpow_def_of_pos hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne').mul has_strict_fderiv_at_snd).exp, rw [rpow_sub_one hp.ne', ← rpow_def_of_pos hp, smul_add, smul_smul, mul_div_left_comm, div_eq_mul_inv, smul_smul, smul_smul, mul_assoc, add_comm] end /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `p.fst < 0`. -/ lemma has_strict_fderiv_at_rpow_of_neg (p : ℝ × ℝ) (hp : p.1 < 0) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1 - exp (log p.1 * p.2) * sin (p.2 * π) * π) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2) * cos (x.2 * π)), from (continuous_at_fst.eventually (gt_mem_nhds hp)).mono (λ p hp, rpow_def_of_neg hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne).mul has_strict_fderiv_at_snd).exp.mul (has_strict_fderiv_at_snd.mul_const _).cos using 1, simp_rw [rpow_sub_one hp.ne, smul_add, ← add_assoc, smul_smul, ← add_smul, ← mul_assoc, mul_comm (cos _), ← rpow_def_of_neg hp], rw [div_eq_mul_inv, add_comm], congr' 2; ring end /-- The function `λ (x, y), x ^ y` is infinitely smooth at `(x, y)` unless `x = 0`. -/ lemma cont_diff_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) {n : ℕ∞} : cont_diff_at ℝ n (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin cases hp.lt_or_lt with hneg hpos, exacts [(((cont_diff_at_fst.log hneg.ne).mul cont_diff_at_snd).exp.mul (cont_diff_at_snd.mul cont_diff_at_const).cos).congr_of_eventually_eq ((continuous_at_fst.eventually (gt_mem_nhds hneg)).mono (λ p hp, rpow_def_of_neg hp _)), ((cont_diff_at_fst.log hpos.ne').mul cont_diff_at_snd).exp.congr_of_eventually_eq ((continuous_at_fst.eventually (lt_mem_nhds hpos)).mono (λ p hp, rpow_def_of_pos hp _))] end lemma differentiable_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : differentiable_at ℝ (λ p : ℝ × ℝ, p.1 ^ p.2) p := (cont_diff_at_rpow_of_ne p hp).differentiable_at le_rfl lemma _root_.has_strict_deriv_at.rpow {f g : ℝ → ℝ} {f' g' : ℝ} (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h : 0 < f x) : has_strict_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin convert (has_strict_fderiv_at_rpow_of_pos ((λ x, (f x, g x)) x) h).comp_has_strict_deriv_at _ (hf.prod hg) using 1, simp [mul_assoc, mul_comm, mul_left_comm] end lemma has_strict_deriv_at_rpow_const_of_ne {x : ℝ} (hx : x ≠ 0) (p : ℝ) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin cases hx.lt_or_lt with hx hx, { have := (has_strict_fderiv_at_rpow_of_neg (x, p) hx).comp_has_strict_deriv_at x ((has_strict_deriv_at_id x).prod (has_strict_deriv_at_const _ _)), convert this, simp }, { simpa using (has_strict_deriv_at_id x).rpow (has_strict_deriv_at_const x p) hx } end lemma has_strict_deriv_at_const_rpow {a : ℝ} (ha : 0 < a) (x : ℝ) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a) x := by simpa using (has_strict_deriv_at_const _ _).rpow (has_strict_deriv_at_id x) ha /-- This lemma says that `λ x, a ^ x` is strictly differentiable for `a < 0`. Note that these values of `a` are outside of the "official" domain of `a ^ x`, and we may redefine `a ^ x` for negative `a` if some other definition will be more convenient. -/ lemma has_strict_deriv_at_const_rpow_of_neg {a x : ℝ} (ha : a < 0) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a - exp (log a * x) * sin (x * π) * π) x := by simpa using (has_strict_fderiv_at_rpow_of_neg (a, x) ha).comp_has_strict_deriv_at x ((has_strict_deriv_at_const _ _).prod (has_strict_deriv_at_id _)) end real namespace real variables {z x y : ℝ} lemma has_deriv_at_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin rcases ne_or_eq x 0 with hx | rfl, { exact (has_strict_deriv_at_rpow_const_of_ne hx _).has_deriv_at }, replace h : 1 ≤ p := h.neg_resolve_left rfl, apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, (has_strict_deriv_at_rpow_const_of_ne hx p).has_deriv_at), exacts [continuous_at_id.rpow_const (or.inr (zero_le_one.trans h)), continuous_at_const.mul (continuous_at_id.rpow_const (or.inr (sub_nonneg.2 h)))] end lemma differentiable_rpow_const {p : ℝ} (hp : 1 ≤ p) : differentiable ℝ (λ x : ℝ, x ^ p) := λ x, (has_deriv_at_rpow_const (or.inr hp)).differentiable_at lemma deriv_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : deriv (λ x : ℝ, x ^ p) x = p * x ^ (p - 1) := (has_deriv_at_rpow_const h).deriv lemma deriv_rpow_const' {p : ℝ} (h : 1 ≤ p) : deriv (λ x : ℝ, x ^ p) = λ x, p * x ^ (p - 1) := funext $ λ x, deriv_rpow_const (or.inr h) lemma cont_diff_at_rpow_const_of_ne {x p : ℝ} {n : ℕ∞} (h : x ≠ 0) : cont_diff_at ℝ n (λ x, x ^ p) x := (cont_diff_at_rpow_of_ne (x, p) h).comp x (cont_diff_at_id.prod cont_diff_at_const) lemma cont_diff_rpow_const_of_le {p : ℝ} {n : ℕ} (h : ↑n ≤ p) : cont_diff ℝ n (λ x : ℝ, x ^ p) := begin induction n with n ihn generalizing p, { exact cont_diff_zero.2 (continuous_id.rpow_const (λ x, by exact_mod_cast or.inr h)) }, { have h1 : 1 ≤ p, from le_trans (by simp) h, rw [nat.cast_succ, ← le_sub_iff_add_le] at h, rw [cont_diff_succ_iff_deriv, deriv_rpow_const' h1], refine ⟨differentiable_rpow_const h1, cont_diff_const.mul (ihn h)⟩ } end lemma cont_diff_at_rpow_const_of_le {x p : ℝ} {n : ℕ} (h : ↑n ≤ p) : cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := (cont_diff_rpow_const_of_le h).cont_diff_at lemma cont_diff_at_rpow_const {x p : ℝ} {n : ℕ} (h : x ≠ 0 ∨ ↑n ≤ p) : cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := h.elim cont_diff_at_rpow_const_of_ne cont_diff_at_rpow_const_of_le lemma has_strict_deriv_at_rpow_const {x p : ℝ} (hx : x ≠ 0 ∨ 1 ≤ p) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := cont_diff_at.has_strict_deriv_at' (cont_diff_at_rpow_const (by rwa nat.cast_one)) (has_deriv_at_rpow_const hx) le_rfl end real section differentiability open real section fderiv variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f g : E → ℝ} {f' g' : E →L[ℝ] ℝ} {x : E} {s : set E} {c p : ℝ} {n : ℕ∞} lemma has_fderiv_within_at.rpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h : 0 < f x) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.rpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h : 0 < f x) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp x (hf.prod hg) lemma has_strict_fderiv_at.rpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h : 0 < f x) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).comp x (hf.prod hg) lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (h : f x ≠ 0) : differentiable_within_at ℝ (λ x, f x ^ g x) s x := (differentiable_at_rpow_of_ne (f x, g x) h).comp_differentiable_within_at x (hf.prod hg) lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (h : f x ≠ 0) : differentiable_at ℝ (λ x, f x ^ g x) x := (differentiable_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (h : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma differentiable.rpow (hf : differentiable ℝ f) (hg : differentiable ℝ g) (h : ∀ x, f x ≠ 0) : differentiable ℝ (λ x, f x ^ g x) := λ x, (hf x).rpow (hg x) (h x) lemma has_fderiv_within_at.rpow_const (hf : has_fderiv_within_at f f' s x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_within_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') s x := (has_deriv_at_rpow_const h).comp_has_fderiv_within_at x hf lemma has_fderiv_at.rpow_const (hf : has_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_deriv_at_rpow_const h).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.rpow_const (hf : has_strict_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_strict_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_strict_deriv_at_rpow_const h).comp_has_strict_fderiv_at x hf lemma differentiable_within_at.rpow_const (hf : differentiable_within_at ℝ f s x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_within_at ℝ (λ x, f x ^ p) s x := (hf.has_fderiv_within_at.rpow_const h).differentiable_within_at @[simp] lemma differentiable_at.rpow_const (hf : differentiable_at ℝ f x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_at ℝ (λ x, f x ^ p) x := (hf.has_fderiv_at.rpow_const h).differentiable_at lemma differentiable_on.rpow_const (hf : differentiable_on ℝ f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 1 ≤ p) : differentiable_on ℝ (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const (h x hx) lemma differentiable.rpow_const (hf : differentiable ℝ f) (h : ∀ x, f x ≠ 0 ∨ 1 ≤ p) : differentiable ℝ (λ x, f x ^ p) := λ x, (hf x).rpow_const (h x) lemma has_fderiv_within_at.const_rpow (hf : has_fderiv_within_at f f' s x) (hc : 0 < c) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_within_at x hf lemma has_fderiv_at.const_rpow (hf : has_fderiv_at f f' x) (hc : 0 < c) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_at x hf lemma has_strict_fderiv_at.const_rpow (hf : has_strict_fderiv_at f f' x) (hc : 0 < c) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).comp_has_strict_fderiv_at x hf lemma cont_diff_within_at.rpow (hf : cont_diff_within_at ℝ n f s x) (hg : cont_diff_within_at ℝ n g s x) (h : f x ≠ 0) : cont_diff_within_at ℝ n (λ x, f x ^ g x) s x := (cont_diff_at_rpow_of_ne (f x, g x) h).comp_cont_diff_within_at x (hf.prod hg) lemma cont_diff_at.rpow (hf : cont_diff_at ℝ n f x) (hg : cont_diff_at ℝ n g x) (h : f x ≠ 0) : cont_diff_at ℝ n (λ x, f x ^ g x) x := (cont_diff_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma cont_diff_on.rpow (hf : cont_diff_on ℝ n f s) (hg : cont_diff_on ℝ n g s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma cont_diff.rpow (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ x, f x ^ g x) := cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow hg.cont_diff_at (h x) lemma cont_diff_within_at.rpow_const_of_ne (hf : cont_diff_within_at ℝ n f s x) (h : f x ≠ 0) : cont_diff_within_at ℝ n (λ x, f x ^ p) s x := hf.rpow cont_diff_within_at_const h lemma cont_diff_at.rpow_const_of_ne (hf : cont_diff_at ℝ n f x) (h : f x ≠ 0) : cont_diff_at ℝ n (λ x, f x ^ p) x := hf.rpow cont_diff_at_const h lemma cont_diff_on.rpow_const_of_ne (hf : cont_diff_on ℝ n f s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_ne (h x hx) lemma cont_diff.rpow_const_of_ne (hf : cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ x, f x ^ p) := hf.rpow cont_diff_const h variable {m : ℕ} lemma cont_diff_within_at.rpow_const_of_le (hf : cont_diff_within_at ℝ m f s x) (h : ↑m ≤ p) : cont_diff_within_at ℝ m (λ x, f x ^ p) s x := (cont_diff_at_rpow_const_of_le h).comp_cont_diff_within_at x hf lemma cont_diff_at.rpow_const_of_le (hf : cont_diff_at ℝ m f x) (h : ↑m ≤ p) : cont_diff_at ℝ m (λ x, f x ^ p) x := by { rw ← cont_diff_within_at_univ at *, exact hf.rpow_const_of_le h } lemma cont_diff_on.rpow_const_of_le (hf : cont_diff_on ℝ m f s) (h : ↑m ≤ p) : cont_diff_on ℝ m (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_le h lemma cont_diff.rpow_const_of_le (hf : cont_diff ℝ m f) (h : ↑m ≤ p) : cont_diff ℝ m (λ x, f x ^ p) := cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow_const_of_le h end fderiv section deriv variables {f g : ℝ → ℝ} {f' g' x y p : ℝ} {s : set ℝ} lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h : 0 < f x) : has_deriv_within_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) s x := begin convert (hf.has_fderiv_within_at.rpow hg.has_fderiv_within_at h).has_deriv_within_at using 1, dsimp, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h : 0 < f x) : has_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow hg h end lemma has_deriv_within_at.rpow_const (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x) ^ (p - 1)) s x := begin convert (has_deriv_at_rpow_const hx).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_const (hf : has_deriv_at f f' x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_const hx end lemma deriv_within_rpow_const (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0 ∨ 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x) ^ p) s x = (deriv_within f s x) * p * (f x) ^ (p - 1) := (hf.has_deriv_within_at.rpow_const hx).deriv_within hxs @[simp] lemma deriv_rpow_const (hf : differentiable_at ℝ f x) (hx : f x ≠ 0 ∨ 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_const hx).deriv end deriv end differentiability section limits open real filter /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞`. -/ lemma tendsto_one_plus_div_rpow_exp (t : ℝ) : tendsto (λ (x : ℝ), (1 + t / x) ^ x) at_top (𝓝 (exp t)) := begin apply ((real.continuous_exp.tendsto _).comp (tendsto_mul_log_one_plus_div_at_top t)).congr' _, have h₁ : (1:ℝ)/2 < 1 := by linarith, have h₂ : tendsto (λ x : ℝ, 1 + t / x) at_top (𝓝 1) := by simpa using (tendsto_inv_at_top_zero.const_mul t).const_add 1, refine (eventually_ge_of_tendsto_gt h₁ h₂).mono (λ x hx, _), have hx' : 0 < 1 + t / x := by linarith, simp [mul_comm x, exp_mul, exp_log hx'], end /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞` for naturals `x`. -/ lemma tendsto_one_plus_div_pow_exp (t : ℝ) : tendsto (λ (x : ℕ), (1 + t / (x:ℝ)) ^ x) at_top (𝓝 (real.exp t)) := ((tendsto_one_plus_div_rpow_exp t).comp tendsto_coe_nat_at_top_at_top).congr (by simp) end limits
960b9be212a661f671cb614c70a9056580d39025
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world1/level2.lean
de09f89b8dd7b526582fd9c91d96573e747b3489
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
3,755
lean
import mynat.mul -- hide namespace mynat -- hide /- # World 1 : Tutorial world ## level 2: The rewrite (`rw`) tactic. The rewrite tactic is the way to "substitute in" the value of a variable. In general, if you have a hypothesis of the form `A = B`, and your goal mentions the left hand side `A` somewhere, then the `rewrite` tactic will replace the `A` in your goal with a `B`. Below is a theorem which cannot be proved using `refl` -- you need a rewrite first. Delete the sorry and take a look in the top right box at what we have. The variables $x$ and $y$ are natural numbers, and we have a proof `h` that $y = x + 7$. Our goal is to prove that $2y=2(x+7)$. This goal is obvious -- we just substitute in $y = x+7$ and we're done. In Lean, we do this substitution using the `rw` tactic. So start your proof with `rw h,` and then hit enter. **Don't forget the comma.** Did you see what happened to the goal? The goal doesn't close, but it *changes* from `⊢ 2 * y = 2 * (x + 7)` to `⊢ 2 * (x + 7) = 2 * (x + 7)`. We can just close this goal with `refl,` by writing it on the line after `rw h,`. Don't forget the comma, hit enter, and enjoy seeing the "Proof complete!" message in the top right window. The other reason you'll know you're done is that the bottom right window (the error window) becomes empty. -/ /- Lemma : no-side-bar If $x$ and $y$ are natural numbers, and $y=x+7$, then $2y=2(x+7)$. -/ lemma example2 (x y z : mynat) (h : y = x + 7) : 2 * y = 2 * (x + 7) := begin [less_leaky] rw h, refl end /- Tactic : rw The `rw` tactic is a way to do "substituting in". There are two distinct situations where use this tactics. 1) If `h : A = B` is a hypothesis (i.e., a proof of `A = B`) in your local context (the box in the top right) and if your goal contains one or more `A`s, then `rw h` will change them all to `B`'s. 2) The `rw` tactic will also work with proofs of theorems which are equalities (look for them in the drop down menu on the left, within Theorem Statements). For example, in world 1 level 4 we learn about `add_zero x : x + 0 = x`, and `rw add_zero` will change `x + 0` into `x` in your goal (or fail with an error if Lean cannot find `x + 0` in the goal). Important note: if `h` is not a proof of the form `A = B` or `A ↔ B` (for example if `h` is a function, an implication, or perhaps even a proposition itself rather than its proof), then `rw` is not the tactic you want to use. For example, `rw (P = Q)` is never correct: `P = Q` is the true-false statement itself, not the proof. If `h : P = Q` is its proof, then `rw h` will work. Pro tip 1: If `h : A = B` and you want to change `B`s to `A`s instead, try `rw ←h` (get the arrow with `\l`). ### Example: If it looks like this in the top right hand box: ``` x y : mynat h : x = z + z ⊢ succ (x + 0) = succ (z + z) ``` then `rw add_zero,` will change the goal into `⊢ succ x = succ (z + z)`, and then `rw h,` will change the goal into `⊢ succ (z + z) = succ (z + z)`, which can be solved with `refl,`. ### Example: You can use `rw` to change a hypothesis as well. For example, if your local context looks like this: ``` x y : mynat h1 : x = y + 3 h2 : 2 * y = x ⊢ y = 3 ``` then `rw h1 at h2` will turn `h2` into `h2 : 2 * y = y + 3`. -/ /- ## Exploring your proof. Click on `refl,` and then use the arrow keys to move your cursor around the proof. Go up and down and note that the goal changes -- indeed you can inspect Lean's "state" at each line of the proof (the hypotheses, and the goal). Try to figure out the exact place where the goal changes. The comma tells Lean "I've finished writing this tactic now, please process it." Lean ignores newlines, but pays great attention to commas. -/ end mynat -- hide
d0b959112bf2135441a28141eb8d5a93bdb07aea
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/bool/basic.lean
95d566b6ff73989178e07d17148e5b1d6ba520e9
[ "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
776
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.core /-! # Boolean operations -/ /-- `cond b x y` is `x` if `b = tt` and `y` otherwise. -/ @[inline] def {u} cond {a : Type u} : bool → a → a → a | tt x y := x | ff x y := y /-- Boolean OR -/ @[inline] def bor : bool → bool → bool | tt b := tt | ff b := b /-- Boolean AND -/ @[inline] def band : bool → bool → bool | tt b := b | ff b := ff /-- Boolean NOT -/ @[inline] def bnot : bool → bool | tt := ff | ff := tt /-- Boolean XOR -/ @[inline] def bxor : bool → bool → bool | tt ff := tt | ff tt := tt | _ _ := ff infixl ` || `:65 := bor infixl ` && `:70 := band
8cac0144b18d04a855f388c8091ef470d1428112
4376c25f060c13471bb89cdb12aeac1d53e53876
/src/espaces-metriques/custom/sequences.lean
c4f042113dd268e697e1afe54db1bbaab8c26c47
[ "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
6,463
lean
import .defs import algebra.pi_instances open espace_metrique open_locale classical section suites variables {X:Type} [espace_metrique X] variables {Y:Type} [espace_metrique Y] variables {Z:Type} [espace_metrique Z] variables {T: Type} [linear_order T] def strictement_croissante (x: ℕ → T) := ∀ p : ℕ, ∀ q > p, x p < x q def converge (x: ℕ → X) (l : X) := ∀ ε > 0, ∃ N, ∀ n ≥ N, ((d l (x n)) < ε) def diverge_inf (x: ℕ → ℕ) := ∀ A, ∃ N, ∀ n ≥ N, x n ≥ A def cauchy (x: ℕ → X) := ∀ ε > 0, ∃ N, ∀ p ≥ N, ∀ q ≥ N, ((d (x p) (x q)) < ε) -- Pour tout élément de l'espace, -- la suite est au plus à M de l'élément de l'espace. def bornee (x: ℕ → X) := ∀ y : X, ∃ M: ℝ, M > 0 ∧ (∀ n : ℕ, d (x n) y ≤ M) def suite_image (f : X → Y) (x : ℕ → X) (n: ℕ) := f (x n) def sous_suite (x: ℕ → X) (φ: ℕ → ℕ) (n: ℕ) := x (φ n) -- valeur d'adhérence. def adhere (x: ℕ → X) (l: X) := ∀ ε > 0, ∀ N : ℕ, ∃ p ≥ N, d l (x p) < ε def c_adhere (x: ℕ → X) (l: X) := ∀ N: ℕ, ∀ n: ℕ, ∃ p ≥ n, d l (x p) < 1 / (N + 1) def seq_adhere (x: ℕ → X) (l: X) := ∃ φ : ℕ → ℕ, strictement_croissante φ ∧ converge (sous_suite x φ) l lemma neg_converge {x: ℕ → ℝ} {l: ℝ}: converge x l → converge (-x) (-l) := begin intro cv, intros ε hε, obtain ⟨ N, hN ⟩ := cv ε hε, use N, intros n hn, simp, rw real.dist_eq, simp, rw ← real.dist_eq, rw sym, exact hN n hn, end lemma add_converge_add {x y: ℕ → ℝ} {a b: ℝ}: converge x a ∧ converge y b → converge (x + y) (a + b) := begin intro H, intros ε hε, obtain ⟨ N, hX ⟩ := H.1 (ε/2) (by linarith), obtain ⟨ M, hY ⟩ := H.2 (ε/2) (by linarith), use (max N M), intros n hn, rw real.dist_eq, calc abs (a + b - (x + y) n) = abs (a + b - (x n + y n)) : by simp ... = abs (a - x n + (b - y n)) : by rw add_sub_comm _ _ _ _ ... ≤ abs (a - x n) + abs (b - y n) : abs_add _ _ ... = d a (x n) + d b (y n) : by rw [← real.dist_eq a (x n), ← real.dist_eq b (y n)] ... < ε/2 + ε/2 : add_lt_add (hX n (le_of_max_le_left hn)) (hY n (le_of_max_le_right hn)) ... = ε : by simp, end lemma converge_of_dist_lt_one_div_succ {x: ℕ → X} {l: X}: (∀ n, d l (x n) ≤ 1 / (n + 1)) → converge x l := begin intro H, intros ε hε, obtain ⟨ N, hN ⟩ := exists_nat_one_div_lt hε, use N, intros n hn, calc d l (x n) ≤ 1 / (n + 1) : H n ... ≤ 1 / (N + 1) : nat.one_div_le_one_div hn ... < ε : hN end lemma countable_adhere_of_adhere {x: ℕ → X} {l: X}: adhere x l → c_adhere x l := begin intro adh, intros N n, obtain ⟨ p, ⟨ hp, hclose ⟩ ⟩ := adh (1/(N + 1)) (nat.one_div_pos_of_nat) n, use p, split, exact hp, exact hclose, end lemma st_croissante_of_succ {x: ℕ → T}: (∀ n, x (n + 1) > x n) → strictement_croissante x := begin intro H, intros p q hpq, induction q with q hq, linarith, by_cases (q > p), calc x p < x q : hq h ... < x (q + 1) : H q, push_neg at h, rw le_antisymm h (nat.le_of_lt_succ hpq), -- q = p. exact H p, end lemma seq_adhere_of_adhere {x: ℕ → X} {l: X}: adhere x l → seq_adhere x l := begin intro adh, choose Y hpos hdist using (countable_adhere_of_adhere adh), -- TODO: extraire R et démontrer un lemme type spec dessus. have R: ℕ → ℕ := well_founded.fix nat.lt_wf (λ n r, if n > 0 then ( Y n (nat.find ( let t := { k | Y n k > r (n - 1) (sorry)} in adh (1/(n + 1)) (sorry) (r (n - 1) (sorry) + 1) ))) --(1 + r (n - 1) (sorry))) -- plutôt que de prendre 1 + r (n - 1), il faudrait prendre min { k | Y n k > r (n - 1)} -- il existe forcément, puisque c'est une partie de N non vide -- en effet, adh fournit un N ≥ r (n - 1) + 1 tel que d l (x N) < 1 / (r(n - 1) + 2) < 1 / (N + 1) -- un tel N est dans l'ensemble en question, puisque Y n N < 1 / (n + 1) else ( Y 0 0 ) ), have Req: ∀ n ≥ 1, (∃ k: ℕ, R n = Y n k) ∧ R n > R (n - 1) := sorry, have R0: R 0 = Y 0 0 := sorry, use R, split, apply st_croissante_of_succ, intros p, cases p, simp, exact (Req 1 (by simp)).2, exact (Req (nat.succ p + 1) (by simp)).2, apply converge_of_dist_lt_one_div_succ, intro n, apply le_of_lt, cases n, simp, rw [sous_suite, R0], have := hdist 0 0, simp at this, exact this, obtain ⟨ k, Req ⟩ := (Req (nat.succ n) (sorry)).1, rw [sous_suite, Req], exact hdist _ _, end def identity_seq (n: ℕ) := n lemma diverge_of_identity_seq: diverge_inf identity_seq := begin intro A, use A, intros n hn, rw identity_seq, exact hn end lemma diverge_of_comparison_seq {φ: ℕ → ℕ} {x: ℕ → ℕ}: diverge_inf x → (∃ N, ∀ n ≥ N, φ n ≥ x n) → diverge_inf φ := begin intros hdivx hcomp, intro A, obtain ⟨ N, hdivx ⟩ := hdivx A, obtain ⟨ M, hcomp ⟩ := hcomp, use (max N M), intros n hn, calc φ n ≥ x n : hcomp n (le_of_max_le_right hn) ... ≥ A : hdivx n (le_of_max_le_left hn) end lemma pos_of_strictly_increasing_seq {φ: ℕ → ℕ}: strictement_croissante φ → ∀ n, φ n ≥ n := begin intro st, intro n, induction n with hn, simp, rw nat.succ_eq_add_one, calc φ (hn + 1) > φ hn : st hn (hn + 1) (lt_add_one hn) ... ≥ hn : n_ih end lemma diverge_of_strictly_increasing_seq {φ: ℕ → ℕ}: strictement_croissante φ → diverge_inf φ := begin intro st, apply diverge_of_comparison_seq (diverge_of_identity_seq), use 0, simp, exact pos_of_strictly_increasing_seq st, end lemma adhere_of_seq_adhere {x: ℕ → X} {l: X}: seq_adhere x l → adhere x l := begin intro sadh, obtain ⟨ φ, ⟨ hmon, hconv ⟩ ⟩ := sadh, intros ε hε N, obtain ⟨ P, hconv ⟩ := hconv ε hε, obtain ⟨ Q, hPhi ⟩ := diverge_of_strictly_increasing_seq hmon N, use (φ (max P Q)), split, exact hPhi _ (le_max_right _ _), exact hconv _ (le_max_left _ _), end lemma adhere_iff_seq_adhere {x: ℕ → X} {l: X}: adhere x l ↔ seq_adhere x l := begin split, exact seq_adhere_of_adhere, exact adhere_of_seq_adhere, end lemma generalized_extractor_of_seq_in_range (x: ℕ → X) (y: ℕ → X) (S: set X): S ⊆ (set.range x) → ∀ n, y n ∈ S → ∃ φ : ℕ → ℕ, y = sous_suite x φ := sorry end suites
778c9fd8048c80a62b37b967b201f65b40ab3e1c
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/standard/struc/binary.lean
13dd59a00a765b4e167cb0e942f11e6fbbd39a24
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,180
lean
---------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura ---------------------------------------------------------------------------------------------------- import logic.connectives.eq using eq_proofs namespace binary section parameter {A : Type} parameter f : A → A → A infixl `*`:75 := f abbreviation commutative := ∀a b, a*b = b*a abbreviation associative := ∀a b c, (a*b)*c = a*(b*c) end section parameter {A : Type} parameter {f : A → A → A} infixl `*`:75 := f hypothesis H_comm : commutative f hypothesis H_assoc : associative f theorem left_comm : ∀a b c, a*(b*c) = b*(a*c) := take a b c, calc a*(b*c) = (a*b)*c : (H_assoc _ _ _)⁻¹ ... = (b*a)*c : {H_comm _ _} ... = b*(a*c) : H_assoc _ _ _ theorem right_comm : ∀a b c, (a*b)*c = (a*c)*b := take a b c, calc (a*b)*c = a*(b*c) : H_assoc _ _ _ ... = a*(c*b) : {H_comm _ _} ... = (a*c)*b : (H_assoc _ _ _)⁻¹ end end
537073bf46eff4151ff22d7bd8a424b60f8931e2
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/order/lexicographic.lean
28e326d1a9e44cc84e2421977bab443361a06e39
[ "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
8,158
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Minchao Wu Lexicographic preorder / partial_order / linear_order / linear_order, for pairs and dependent pairs. -/ import tactic.basic universes u v /-- The cartesian product, equipped with the lexicographic order. -/ def lex (α : Type u) (β : Type v) := α × β variables {α : Type u} {β : Type v} instance [decidable_eq α] [decidable_eq β] : decidable_eq (lex α β) := prod.decidable_eq instance [inhabited α] [inhabited β] : inhabited (lex α β) := prod.inhabited /-- Dictionary / lexicographic ordering on pairs. -/ instance lex_has_le [preorder α] [preorder β] : has_le (lex α β) := { le := prod.lex (<) (≤) } instance lex_has_lt [preorder α] [preorder β] : has_lt (lex α β) := { lt := prod.lex (<) (<) } /-- Dictionary / lexicographic preorder for pairs. -/ instance lex_preorder [preorder α] [preorder β] : preorder (lex α β) := { le_refl := λ ⟨l, r⟩, by { right, apply le_refl }, le_trans := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁l, h₁r⟩ ⟨h₂l, h₂r⟩, { left, apply lt_trans, repeat { assumption } }, { left, assumption }, { left, assumption }, { right, apply le_trans, repeat { assumption } } end, lt_iff_le_not_le := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, split, { rintros (⟨_, _, _, _, hlt⟩ | ⟨_, _, _, hlt⟩), { split, { left, assumption }, { rintro ⟨l,r⟩, { apply lt_asymm hlt, assumption }, { apply lt_irrefl _ hlt } } }, { split, { right, rw lt_iff_le_not_le at hlt, exact hlt.1 }, { rintro ⟨l,r⟩, { apply lt_irrefl a₁, assumption }, { rw lt_iff_le_not_le at hlt, apply hlt.2, assumption } } } }, { rintros ⟨⟨h₁ll, h₁lr⟩, h₂r⟩, { left, assumption }, { right, rw lt_iff_le_not_le, split, { assumption }, { intro h, apply h₂r, right, exact h } } } end, .. lex_has_le, .. lex_has_lt } /-- Dictionary / lexicographic partial_order for pairs. -/ instance lex_partial_order [partial_order α] [partial_order β] : partial_order (lex α β) := { le_antisymm := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, _, _, hlt₁⟩ | ⟨_, _, _, hlt₁⟩) (⟨_, _, _, _, hlt₂⟩ | ⟨_, _, _, hlt₂⟩), { exfalso, exact lt_irrefl a₁ (lt_trans hlt₁ hlt₂) }, { exfalso, exact lt_irrefl a₁ hlt₁ }, { exfalso, exact lt_irrefl a₁ hlt₂ }, { have := le_antisymm hlt₁ hlt₂, simp [this] } end .. lex_preorder } /-- Dictionary / lexicographic linear_order for pairs. -/ instance lex_linear_order [linear_order α] [linear_order β] : linear_order (lex α β) := { le_total := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, rcases le_total a₁ a₂ with ha | ha; cases lt_or_eq_of_le ha with a_lt a_eq, -- Deal with the two goals with a₁ ≠ a₂ { left, left, exact a_lt }, swap, { right, left, exact a_lt }, -- Now deal with the two goals with a₁ = a₂ all_goals { subst a_eq, rcases le_total b₁ b₂ with hb | hb }, { left, right, exact hb }, { right, right, exact hb }, { left, right, exact hb }, { right, right, exact hb }, end, decidable_le := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, rcases linear_order.decidable_le a₁ a₂ with a_lt | a_le, { -- a₂ < a₁ left, rw not_le at a_lt, rintro ⟨l, r⟩, { apply lt_irrefl a₂, apply lt_trans, repeat { assumption } }, { apply lt_irrefl a₁, assumption } }, { -- a₁ ≤ a₂ by_cases h : a₁ = a₂, { rw h, rcases linear_order.decidable_le b₁ b₂ with b_lt | b_le, { -- b₂ < b₁ left, rw not_le at b_lt, rintro ⟨l, r⟩, { apply lt_irrefl a₂, assumption }, { apply lt_irrefl b₂, apply lt_of_lt_of_le, repeat { assumption } } }, -- b₁ ≤ b₂ { right, right, assumption } }, -- a₁ < a₂ { right, left, apply lt_of_le_of_ne, repeat { assumption } } } end, .. lex_partial_order }. variables {Z : α → Type v} /-- Dictionary / lexicographic ordering on dependent pairs. The 'pointwise' partial order `prod.has_le` doesn't make sense for dependent pairs, so it's safe to mark these as instances here. -/ instance dlex_has_le [preorder α] [∀ a, preorder (Z a)] : has_le (Σ' a, Z a) := { le := psigma.lex (<) (λ a, (≤)) } instance dlex_has_lt [preorder α] [∀ a, preorder (Z a)] : has_lt (Σ' a, Z a) := { lt := psigma.lex (<) (λ a, (<)) } /-- Dictionary / lexicographic preorder on dependent pairs. -/ instance dlex_preorder [preorder α] [∀ a, preorder (Z a)] : preorder (Σ' a, Z a) := { le_refl := λ ⟨l, r⟩, by { right, apply le_refl }, le_trans := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁l, h₁r⟩ ⟨h₂l, h₂r⟩, { left, apply lt_trans, repeat { assumption } }, { left, assumption }, { left, assumption }, { right, apply le_trans, repeat { assumption } } end, lt_iff_le_not_le := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, split, { rintros (⟨_, _, _, _, hlt⟩ | ⟨_, _, _, hlt⟩), { split, { left, assumption }, { rintro ⟨l,r⟩, { apply lt_asymm hlt, assumption }, { apply lt_irrefl _ hlt } } }, { split, { right, rw lt_iff_le_not_le at hlt, exact hlt.1 }, { rintro ⟨l,r⟩, { apply lt_irrefl a₁, assumption }, { rw lt_iff_le_not_le at hlt, apply hlt.2, assumption } } } }, { rintros ⟨⟨h₁ll, h₁lr⟩, h₂r⟩, { left, assumption }, { right, rw lt_iff_le_not_le, split, { assumption }, { intro h, apply h₂r, right, exact h } } } end, .. dlex_has_le, .. dlex_has_lt } /-- Dictionary / lexicographic partial_order for dependent pairs. -/ instance dlex_partial_order [partial_order α] [∀ a, partial_order (Z a)] : partial_order (Σ' a, Z a) := { le_antisymm := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, _, _, hlt₁⟩ | ⟨_, _, _, hlt₁⟩) (⟨_, _, _, _, hlt₂⟩ | ⟨_, _, _, hlt₂⟩), { exfalso, exact lt_irrefl a₁ (lt_trans hlt₁ hlt₂) }, { exfalso, exact lt_irrefl a₁ hlt₁ }, { exfalso, exact lt_irrefl a₁ hlt₂ }, { have := le_antisymm hlt₁ hlt₂, simp [this] } end .. dlex_preorder } /-- Dictionary / lexicographic linear_order for pairs. -/ instance dlex_linear_order [linear_order α] [∀ a, linear_order (Z a)] : linear_order (Σ' a, Z a) := { le_total := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, rcases le_total a₁ a₂ with ha | ha; cases lt_or_eq_of_le ha with a_lt a_eq, -- Deal with the two goals with a₁ ≠ a₂ { left, left, exact a_lt }, swap, { right, left, exact a_lt }, -- Now deal with the two goals with a₁ = a₂ all_goals { subst a_eq, rcases le_total b₁ b₂ with hb | hb }, { left, right, exact hb }, { right, right, exact hb }, { left, right, exact hb }, { right, right, exact hb }, end, decidable_le := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, rcases linear_order.decidable_le a₁ a₂ with a_lt | a_le, { -- a₂ < a₁ left, rw not_le at a_lt, rintro ⟨l, r⟩, { apply lt_irrefl a₂, apply lt_trans, repeat { assumption } }, { apply lt_irrefl a₁, assumption } }, { -- a₁ ≤ a₂ by_cases h : a₁ = a₂, { subst h, rcases linear_order.decidable_le b₁ b₂ with b_lt | b_le, { -- b₂ < b₁ left, rw not_le at b_lt, rintro ⟨l, r⟩, { apply lt_irrefl a₁, assumption }, { apply lt_irrefl b₂, apply lt_of_lt_of_le, repeat { assumption } } }, -- b₁ ≤ b₂ { right, right, assumption } }, -- a₁ < a₂ { right, left, apply lt_of_le_of_ne, repeat { assumption } } } end, .. dlex_partial_order }.
c5490408571caa6a6e356d6f0fdb8e5de01f278d
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/ring_theory/roots_of_unity.lean
1765cd85633ef0f0b521bc8f014f64e22b848511
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,324
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.nat.parity import data.polynomial.ring_division import group_theory.order_of_element import ring_theory.integral_domain import number_theory.divisors import data.zmod.basic import tactic.zify import field_theory.separable /-! # Roots of unity and primitive roots of unity We define roots of unity in the context of an arbitrary commutative monoid, as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative monoids, expressing that an element is a primitive root of unity. ## Main definitions * `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M` consisting of elements `x` that satisfy `x ^ n = 1`. * `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. * `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`. ## Main results * `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group. * `is_primitive_root.zmod_equiv_gpowers`: `zmod k` is equivalent to the subgroup generated by a primitive `k`-th root of unity. * `is_primitive_root.gpowers_eq`: in an integral domain, the subgroup generated by a primitive `k`-th root of unity is equal to the `k`-th roots of unity. * `is_primitive_root.card_primitive_roots`: if an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. ## Implementation details It is desirable that `roots_of_unity` is a subgroup, and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields. We therefore implement it as a subgroup of the units of a commutative monoid. We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`, because almost all lemmas need the positivity assumption, and in particular the type class instances for `fintype` and `is_cyclic`. On the other hand, for primitive roots of unity, it is desirable to have a predicate not just on units, but directly on elements of the ring/field. For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity in the complex numbers, without having to turn that number into a unit first. This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and `is_primitive_root.coe_units_iff` should provide the necessary glue. -/ open_locale classical big_operators noncomputable theory open polynomial open finset variables {M N G G₀ R S : Type*} variables [comm_monoid M] [comm_monoid N] [comm_group G] [comm_group_with_zero G₀] variables [integral_domain R] [integral_domain S] section roots_of_unity variables {k l : ℕ+} /-- `roots_of_unity k M` is the subgroup of elements `m : units M` that satisfy `m ^ k = 1` -/ def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup (units M) := { carrier := { ζ | ζ ^ (k : ℕ) = 1 }, one_mem' := one_pow _, mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *, inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, one_inv] at * } @[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : units M) : ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M := begin obtain ⟨d, rfl⟩ := h, intros ζ h, simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *, end lemma map_roots_of_unity (f : units M →* units N) (k : ℕ+) : (roots_of_unity k M).map f ≤ roots_of_unity k N := begin rintros _ ⟨ζ, h, rfl⟩, simp only [←monoid_hom.map_pow, *, mem_roots_of_unity, subgroup.mem_coe, monoid_hom.map_one] at * end lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : units R} : ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) := by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow] variables (k R) /-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`. This is implemented as equivalence of subtypes, because `roots_of_unity` is a subgroup of the group of units, whereas `nth_roots` is a multiset. -/ def roots_of_unity_equiv_nth_roots : roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} := begin refine { to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩, inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩, left_inv := _, right_inv := _ }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, all_goals { rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx, simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx, nat.sub_add_cancel (show 1 ≤ (k : ℕ), from k.one_le)] }, { show (_ : units R) ^ (k : ℕ) = 1, simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] } end variables {k R} @[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) : (roots_of_unity_equiv_nth_roots R k x : R) = x := rfl @[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) : ((roots_of_unity_equiv_nth_roots R k).symm x : R) = x := rfl variables (k R) instance roots_of_unity.fintype : fintype (roots_of_unity k R) := fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) := is_cyclic_of_subgroup_integral_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype) (units.ext.comp subtype.val_injective) lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k := calc fintype.card (roots_of_unity k R) = fintype.card {x // x ∈ nth_roots k (1 : R)} : fintype.card_congr (roots_of_unity_equiv_nth_roots R k) ... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.erase_dup_le _) ... = (nth_roots k (1 : R)).card : multiset.card_attach ... ≤ k : card_nth_roots k 1 end roots_of_unity /-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/ structure is_primitive_root (ζ : M) (k : ℕ) : Prop := (pow_eq_one : ζ ^ (k : ℕ) = 1) (dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l) section primitive_roots variables {k : ℕ} /-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity in the integral domain `R`. -/ def primitive_roots (k : ℕ) (R : Type*) [integral_domain R] : finset R := (nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k) @[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) : ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k := begin rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp], exact is_primitive_root.pow_eq_one end end primitive_roots namespace is_primitive_root variables {k l : ℕ} lemma iff_def (ζ : M) (k : ℕ) : is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) := ⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩ lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) : is_primitive_root ζ k := begin refine ⟨h1, _⟩, intros l hl, apply dvd_trans _ (k.gcd_dvd_right l), suffices : k.gcd l = k, { rw this }, rw eq_iff_le_not_lt, refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩, intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h', exact pow_gcd_eq_one _ h1 hl end section comm_monoid variables {ζ : M} (h : is_primitive_root ζ k) lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l := ⟨h.dvd_of_pow_eq_one l, by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩ lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ := begin apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)), rw [← pow_succ, nat.sub_add_cancel h0, h.pow_eq_one] end lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 := mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) : i = j := begin wlog hij : i ≤ j, apply le_antisymm hij, rw ← nat.sub_eq_zero_iff_le, apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt (nat.sub_le_self _ _) hj), apply h.dvd_of_pow_eq_one, rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj, ← pow_add, nat.sub_add_cancel hij, H, one_mul] end lemma one : is_primitive_root (1 : M) 1 := { pow_eq_one := pow_one _, dvd_of_pow_eq_one := λ l hl, one_dvd _ } @[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 := begin split, { intro h, rw [← pow_one ζ, h.pow_eq_one] }, { rintro rfl, exact one } end @[simp] lemma coe_units_iff {ζ : units M} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one] lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : k = 0, { subst k, simp only [*, pow_one, nat.coprime_zero_right] at * }, rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩, rw [← units.coe_pow], rw coe_units_iff at h ⊢, refine { pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow], dvd_of_pow_eq_one := _ }, intros l hl, apply h.dvd_of_pow_eq_one, rw [← pow_one ζ, ← gpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, gpow_add, mul_pow, ← gpow_coe_nat, ← gpow_mul, mul_right_comm], simp only [gpow_mul, hl, h.pow_eq_one, one_gpow, one_pow, one_mul, gpow_coe_nat] end lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) : is_primitive_root (ζ ^ i) k ↔ i.coprime k := begin refine ⟨_, h.pow_of_coprime i⟩, intro hi, obtain ⟨a, ha⟩ := i.gcd_dvd_left k, obtain ⟨b, hb⟩ := i.gcd_dvd_right k, suffices : b = k, { rwa [this, ← one_mul k, nat.mul_left_inj h0, eq_comm] at hb { occs := occurrences.pos [1] } }, rw [ha] at hi, rw [mul_comm] at hb, apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _), rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow] end end comm_monoid section comm_group variables {ζ : G} (h : is_primitive_root ζ k) lemma gpow_eq_one : ζ ^ (k : ℤ) = 1 := h.pow_eq_one lemma gpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [gpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← gpow_neg, ← hl', gpow_coe_nat, one_inv] } end lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, one_inv, eq_self_iff_true, inv_pow], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj, ← inv_pow, hl, one_inv] end } @[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h } lemma gpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff, ← gpow_neg, ← hi'], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end @[simp] lemma coe_subgroup_iff (H : subgroup G) {ζ : H} : is_primitive_root (ζ : G) k ↔ is_primitive_root ζ k := by simp only [iff_def, ← subgroup.coe_pow, ← H.coe_one, ← subtype.ext_iff] end comm_group section comm_group_with_zero variables {ζ : G₀} (h : is_primitive_root ζ k) lemma fpow_eq_one : ζ ^ (k : ℤ) = 1 := h.pow_eq_one lemma fpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [fpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj', ← fpow_neg, ← hl', fpow_coe_nat, inv_one] } end lemma inv' (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow'], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj', ← inv_pow', hl, inv_one] end } @[simp] lemma inv_iff' : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv' h⟩, intro h, rw [← inv_inv' ζ], exact inv' h } lemma fpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff', ← fpow_neg, ← hi'], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end end comm_group_with_zero section integral_domain variables {ζ : R} @[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ := begin rw [← finset.val_eq_zero, ← multiset.subset_zero, ← nth_roots_zero (1 : R), primitive_roots], simp only [finset.not_mem_empty, forall_const, forall_prop_of_false, multiset.to_finset_zero, finset.filter_true_of_mem, finset.empty_val, not_false_iff, multiset.zero_subset, nth_roots_zero] end @[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} := begin apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] }, { intros x hx, rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx, exact hx } end lemma neg_one (p : ℕ) [char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 := mk_of_lt (-1 : R) dec_trivial (by simp only [one_pow, neg_square]) $ begin intros l hl0 hl2, obtain rfl : l = 1, { unfreezingI { clear_dependent R p }, dec_trivial! }, simp only [pow_one, ne.def], intro h, suffices h2 : p ∣ 2, { have := char_p.char_ne_one R p, unfreezingI { clear_dependent R }, have aux := nat.le_of_dvd dec_trivial h2, revert this hp h2, revert p, dec_trivial }, simp only [← char_p.cast_eq_zero_iff R p, nat.cast_bit0, nat.cast_one], rw [bit0, ← h, neg_add_self] { occs := occurrences.pos [1] } end lemma eq_neg_one_of_two_right (h : is_primitive_root ζ 2) : ζ = -1 := begin apply (eq_or_eq_neg_of_pow_two_eq_pow_two ζ 1 _).resolve_left, { rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial }, { simp only [h.pow_eq_one, one_pow] } end end integral_domain section integral_domain variables {ζ : units R} (h : is_primitive_root ζ k) protected lemma mem_roots_of_unity {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n R := h.pow_eq_one /-- The (additive) monoid equivalence between `zmod k` and the powers of a primitive root of unity `ζ`. -/ def zmod_equiv_gpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.gpowers ζ) := add_equiv.of_bijective (add_monoid_hom.lift_of_surjective (int.cast_add_hom _) zmod.int_cast_surjective { to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.gpowers ζ), map_zero' := by { simp only [gpow_zero], refl }, map_add' := by { intros i j, simp only [gpow_add], refl } } (λ i hi, begin simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k, add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢, obtain ⟨i, rfl⟩ := hi, simp only [gpow_mul, h.pow_eq_one, one_gpow, gpow_coe_nat], refl end)) $ begin split, { rw add_monoid_hom.injective_iff, intros i hi, rw subtype.ext_iff at hi, have := (h.gpow_eq_one_iff_dvd _).mp hi, rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm], exact classical.some_spec (zmod.int_cast_surjective i) }, { rintro ⟨ξ, i, rfl⟩, refine ⟨int.cast_add_hom _ i, _⟩, rw [add_monoid_hom.lift_of_surjective_comp_apply], refl } end @[simp] lemma zmod_equiv_gpowers_apply_coe_int (i : ℤ) : h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) := begin apply add_monoid_hom.lift_of_surjective_comp_apply, intros j hj, simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k, add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hj ⊢, obtain ⟨j, rfl⟩ := hj, simp only [gpow_mul, h.pow_eq_one, one_gpow, gpow_coe_nat], refl end @[simp] lemma zmod_equiv_gpowers_apply_coe_nat (i : ℕ) : h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) := begin have : (i : zmod k) = (i : ℤ), by norm_cast, simp only [this, zmod_equiv_gpowers_apply_coe_int, gpow_coe_nat], refl end @[simp] lemma zmod_equiv_gpowers_symm_apply_gpow (i : ℤ) : h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i := by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_int] @[simp] lemma zmod_equiv_gpowers_symm_apply_gpow' (i : ℤ) : h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_gpowers_symm_apply_gpow i @[simp] lemma zmod_equiv_gpowers_symm_apply_pow (i : ℕ) : h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i := by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_nat] @[simp] lemma zmod_equiv_gpowers_symm_apply_pow' (i : ℕ) : h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_gpowers_symm_apply_pow i lemma gpowers_eq {k : ℕ+} {ζ : units R} (h : is_primitive_root ζ k) : subgroup.gpowers ζ = roots_of_unity k R := begin apply subgroup.ext', haveI : fact (0 < (k : ℕ)) := k.pos, haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_gpowers).to_equiv, refine @set.eq_of_subset_of_card_le (units R) (subgroup.gpowers ζ) (roots_of_unity k R) F (roots_of_unity.fintype R k) (subgroup.gpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _, calc fintype.card (roots_of_unity k R) ≤ k : card_roots_of_unity R k ... = fintype.card (zmod k) : (zmod.card k).symm ... = fintype.card (subgroup.gpowers ζ) : fintype.card_congr (h.zmod_equiv_gpowers).to_equiv end lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) : ∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ := begin obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.gpowers_eq] at hξ, have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos, let i := n % k, have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0), lift i to ℕ using hi0 with i₀ hi₀, refine ⟨i₀, _, _⟩, { zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 }, { have aux := h.gpow_eq_one, rw [← coe_coe] at aux, rw [← gpow_coe_nat, hi₀, ← int.mod_add_div n k, gpow_add, gpow_mul, aux, one_gpow, mul_one] } end lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) : ∃ i < k, ζ ^ i = ξ := begin obtain ⟨ζ, rfl⟩ := h.is_unit h0, obtain ⟨ξ, rfl⟩ := is_unit_of_pow_eq_one ξ k hξ h0, obtain ⟨k, rfl⟩ : ∃ k' : ℕ+, k = k' := ⟨⟨k, h0⟩, rfl⟩, simp only [← units.coe_pow, ← units.ext_iff], rw coe_units_iff at h, apply h.eq_pow_of_mem_roots_of_unity, rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one] end lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) : is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one, rw h.pow_iff_coprime k.pos at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) : is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0, rw h.pow_iff_coprime h0 at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin haveI : fact (0 < ↑n) := n.pos, let e := h.zmod_equiv_gpowers, haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ e.to_equiv, calc fintype.card (roots_of_unity n R) = fintype.card (subgroup.gpowers ζ) : fintype.card_congr $ by rw h.gpowers_eq ... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm ... = n : zmod.card n end lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin obtain ⟨ζ, hζ⟩ := h.is_unit n.pos, rw [← hζ, is_primitive_root.coe_units_iff] at h, exact h.card_roots_of_unity' end /-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n` if there is a primitive root of unity in `R`. -/ lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).card = n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.card_zero, nth_roots_zero] }, rw eq_iff_le_not_lt, use card_nth_roots n 1, { rw [not_lt], have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)} ≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.erase_dup_le _), rw multiset.card_attach at hcard, rw ← pnat.to_pnat'_coe hpos at hcard h ⊢, set m := nat.to_pnat' n, rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard, exact hcard } end /-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements if there is a primitive root of unity in `R`. -/ lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.nodup_zero, nth_roots_zero] }, apply (@multiset.erase_dup_eq_self R _ _).1, rw eq_iff_le_not_lt, split, { exact multiset.erase_dup_le (nth_roots n (1 : R)) }, { by_contra ha, replace ha := multiset.card_lt_of_lt ha, rw card_nth_roots h at ha, have hrw : (nth_roots n (1 : R)).erase_dup.card = fintype.card {x // x ∈ (nth_roots n (1 : R))}, { set fs := (⟨(nth_roots n (1 : R)).erase_dup, multiset.nodup_erase_dup _⟩ : finset R), rw [← finset.card_mk, ← fintype.card_of_subtype fs _], intro x, simp only [multiset.mem_erase_dup, finset.mem_mk] }, rw ← pnat.to_pnat'_coe hpos at h hrw ha, set m := nat.to_pnat' n, rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at ha, exact nat.lt_asymm ha ha } end @[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots_finset n R).card = n := by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots] open_locale nat /-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/ lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) (h0 : 0 < k) : (primitive_roots k R).card = φ k := begin symmetry, refine finset.card_congr (λ i _, ζ ^ i) _ _ _, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i - hi, rw mem_primitive_roots h0, exact h.pow_of_coprime i hi.symm }, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i j hi - hj - H, exact h.pow_inj hi hj H }, { simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ], intros ξ hξ, rw [mem_primitive_roots h0, h.is_primitive_root_iff h0] at hξ, rcases hξ with ⟨i, hin, hi, H⟩, exact ⟨i, ⟨hin, hi.symm⟩, H⟩ } end /-- The sets `primitive_roots k R` are pairwise disjoint. -/ lemma disjoint {k l : ℕ} (hk : 0 < k) (hl : 0 < l) (h : k ≠ l) : disjoint (primitive_roots k R) (primitive_roots l R) := begin intro z, simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots, hk, hl, iff_def], rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩, apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl] end /-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`, then there is a `b`-th primitive root of unity in `R`. -/ lemma pow {ζ : R} {n : ℕ} {a b : ℕ} (hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) : is_primitive_root (ζ ^ a) b := begin subst n, simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and], intros l hl, have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn }, rwa ← mul_dvd_mul_iff_left ha0, exact h.dvd_of_pow_eq_one _ hl end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bind_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors ↑n).bind (λ i, (primitive_roots i R)) := begin symmetry, apply finset.eq_of_subset_of_card_le, { intros x, simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), exists_prop, finset.mem_bind, finset.mem_filter, finset.mem_range, mem_nth_roots, finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff], rintro ⟨a, ⟨d, hd⟩, ha⟩, have hazero : 0 < a, { contrapose! hd with ha0, simp only [le_zero_iff_eq, zero_mul, *] at *, exact n.ne_zero }, rw mem_primitive_roots hazero at ha, rw [hd, pow_mul, ha.pow_eq_one, one_pow] }, { apply le_of_eq, rw [h.card_nth_roots_finset, finset.card_bind], { rw [← nat.sum_totient n, nat.filter_dvd_eq_divisors (pnat.ne_zero n), sum_congr rfl] { occs := occurrences.pos [1] }, simp only [finset.mem_filter, finset.mem_range, nat.mem_divisors], rintro k ⟨H, hk⟩, have hdvd := H, rcases H with ⟨d, hd⟩, rw mul_comm at hd, rw (h.pow n.pos hd).card_primitive_roots (pnat.pos_of_div_pos hdvd) }, { intros i hi j hj hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hi hj, exact disjoint (pnat.pos_of_div_pos hi) (pnat.pos_of_div_pos hj) hdiff } } end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bind_primitive_roots {ζ : R} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors n).bind (λ i, (primitive_roots i R)) := @nth_roots_one_eq_bind_primitive_roots' _ _ _ ⟨n, hpos⟩ h end integral_domain section minimal_polynomial open minimal_polynomial variables {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) include n μ h hpos /--`μ` is integral over `ℤ`. -/ lemma is_integral : is_integral ℤ μ := begin use (X ^ n - 1), split, { exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) }, { simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub, sub_self] } end variables [char_zero K] /--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/ lemma minimal_polynomial_dvd_X_pow_sub_one : minimal_polynomial (is_integral h hpos) ∣ X ^ n - 1 := begin apply integer_dvd (is_integral h hpos) (polynomial.monic.is_primitive (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm)), simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, ring_hom.eq_int_cast, int.cast_one, aeval_one, alg_hom.map_sub, sub_self] end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/ lemma separable_minimal_polynomial_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) : separable (map (int.cast_ring_hom (zmod p)) (minimal_polynomial (is_integral h hpos))) := begin have hdvd : (map (int.cast_ring_hom (zmod p)) (minimal_polynomial (is_integral h hpos))) ∣ X ^ n - 1, { simpa [map_pow, map_X, map_one, ring_hom.coe_of, map_sub] using ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))) (minimal_polynomial_dvd_X_pow_sub_one h hpos) }, refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero)) end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/ lemma squarefree_minimal_polynomial_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) : squarefree (map (int.cast_ring_hom (zmod p)) (minimal_polynomial (is_integral h hpos))) := (separable_minimal_polynomial_mod h hpos hdiv).squarefree end minimal_polynomial end is_primitive_root
14319454af6f829da48217d949a5bd429c2872c3
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/order/lattice.lean
ce3280b4a973be720e9d609d540c06a036b28aa4
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,282
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 Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy. -/ import order.basic set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ reserve infixl ` ⊓ `:70 reserve infixl ` ⊔ `:65 /-- Typeclass for the `⊔` (`\lub`) notation -/ class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) end prio section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := semilattice_sup.le_sup_left a b @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := semilattice_sup.le_sup_right a b theorem le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b := by finish theorem le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b := by finish theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ @[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := sup_eq_left.2 h @[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left @[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := sup_eq_right.2 h @[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := by finish theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := by finish theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := by finish theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by finish /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_mono (f : α → β) {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f := λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩ lemma sup_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h) @[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a := ⟨λ h, ⟨lt_of_le_of_lt le_sup_left h, lt_of_le_of_lt le_sup_right h⟩, λ h, sup_ind b c h.1 h.2⟩ @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; finish instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; finish instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by apply le_antisymm; finish instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) := suffices (∃b, ¬b ≤ a) → (∃b, a < b), by rwa [classical.or_iff_not_imp_left, classical.not_forall], assume ⟨b, hb⟩, ⟨a ⊔ b, lt_of_le_of_ne le_sup_left $ mt left_eq_sup.1 hb⟩ theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), cases A; cases B; injection this; congr' end lemma directed_of_sup {β : Type*} {r : β → β → Prop} {f : α → β} (hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₁) (f a₂)) : directed r f := assume x y, ⟨x ⊔ y, hf _ _ le_sup_left, hf _ _ le_sup_right⟩ end semilattice_sup section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) end prio section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := ⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩, assume ⟨h₁, h₂⟩, le_inf h₁ h₂⟩ @[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := inf_eq_left.2 h @[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left @[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := inf_eq_right.2 h @[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := by finish lemma inf_le_inf_right (a : α) {b c: α} (h : b ≤ c): b ⊓ a ≤ c ⊓ a := by finish lemma inf_le_inf_left (a : α) {b c: α} (h : b ≤ c): a ⊓ b ≤ a ⊓ c := by finish theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by finish lemma inf_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊓ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa inf_eq_left.2 h) (λ h, by rwa inf_eq_right.2 h) @[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c := ⟨λ h, ⟨lt_of_lt_of_le h inf_le_left, lt_of_lt_of_le h inf_le_right⟩, λ h, inf_ind b c h.1 h.2⟩ @[simp] theorem inf_idem : a ⊓ a = a := by apply le_antisymm; finish instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ theorem inf_comm : a ⊓ b = b ⊓ a := by apply le_antisymm; finish instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by apply le_antisymm; finish instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := by rw [← inf_assoc, ← inf_assoc, @inf_comm α _ a] lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) := suffices (∃b, ¬a ≤ b) → (∃b, b < a), by rwa [classical.or_iff_not_imp_left, classical.not_forall], assume ⟨b, hb⟩, have a ⊓ b ≠ a, from assume eq, hb $ eq ▸ inf_le_right, ⟨a ⊓ b, lt_of_le_of_ne inf_le_left ‹a ⊓ b ≠ a›⟩ theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), cases A; cases B; injection this; congr' end /-- An antimonotone function on an inf-semilattice is directed. -/ lemma directed_of_inf {r : β → β → Prop} {f : α → β} (hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f := assume x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ end semilattice_inf /- Lattices -/ section prio set_option default_priority 100 -- see Note [default priority] /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α end prio section lattice variables [lattice α] {a b c d : α} /- Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := by finish theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := by finish theorem inf_sup_self : a ⊓ (a ⊔ b) = a := le_antisymm (by finish) (by finish) theorem sup_inf_self : a ⊔ (a ⊓ b) = a := le_antisymm (by finish) (by finish) theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, resetI, cases A; cases B; injection SS; injection II; congr' end end lattice section prio set_option default_priority 100 -- see Note [default priority] /-- A distributive lattice is a lattice that satisfies any of four equivalent distribution properties (of sup over inf or inf over sup, on the left or right). A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) end prio section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y := calc x ≤ (y ⊓ z) ⊔ x : le_sup_right ... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x] ... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂ ... = y ⊔ (x ⊓ z) : sup_inf_left.symm ... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _ ... ≤ _ : sup_le (le_refl y) inf_le_left lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂)) (le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm)) end distrib_lattice /- Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } theorem sup_eq_max [decidable_linear_order α] {x y : α} : x ⊔ y = max x y := rfl theorem inf_eq_min [decidable_linear_order α] {x y : α} : x ⊓ y = min x y := rfl @[priority 100] -- see Note [lower instance priority] instance distrib_lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_left_of_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_right_of_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..lattice_of_decidable_linear_order } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance namespace monotone lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) end monotone namespace order_dual variable (α) instance [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩ instance [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩ instance [semilattice_inf α] : semilattice_sup (order_dual α) := { le_sup_left := @inf_le_left α _, le_sup_right := @inf_le_right α _, sup_le := assume a b c hca hcb, @le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance [semilattice_sup α] : semilattice_inf (order_dual α) := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } instance [lattice α] : lattice (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } instance [distrib_lattice α] : distrib_lattice (order_dual α) := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } end order_dual namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod
ff193b7a90704917defb87a08669885146845909
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/instances/rat_lemmas.lean
b8e6c0c7e4373d2735be0fdab82da77486e580ef
[ "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,247
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.instances.irrational import topology.instances.rat import topology.alexandroff /-! # Additional lemmas about the topology on rational numbers The structure of a metric space on `ℚ` (`rat.metric_space`) is introduced elsewhere, induced from `ℝ`. In this file we prove some properties of this topological space and its one-point compactification. ## Main statements - `rat.totally_disconnected_space`: `ℚ` is a totally disconnected space; - `rat.not_countably_generated_nhds_infty_alexandroff`: the filter of neighbourhoods of infinity in `alexandroff ℚ` is not countably generated. ## Notation - `ℚ∞` is used as a local notation for `alexandroff ℚ` -/ open set metric filter topological_space open_locale topological_space alexandroff local notation `ℚ∞` := alexandroff ℚ namespace rat variables {p q : ℚ} {s t : set ℚ} lemma interior_compact_eq_empty (hs : is_compact s) : interior s = ∅ := dense_embedding_coe_real.to_dense_inducing.interior_compact_eq_empty dense_irrational hs lemma dense_compl_compact (hs : is_compact s) : dense sᶜ := interior_eq_empty_iff_dense_compl.1 (interior_compact_eq_empty hs) instance cocompact_inf_nhds_ne_bot : ne_bot (cocompact ℚ ⊓ 𝓝 p) := begin refine (has_basis_cocompact.inf (nhds_basis_opens _)).ne_bot_iff.2 _, rintro ⟨s, o⟩ ⟨hs, hpo, ho⟩, rw inter_comm, exact (dense_compl_compact hs).inter_open_nonempty _ ho ⟨p, hpo⟩ end lemma not_countably_generated_cocompact : ¬is_countably_generated (cocompact ℚ) := begin introI H, rcases exists_seq_tendsto (cocompact ℚ ⊓ 𝓝 0) with ⟨x, hx⟩, rw tendsto_inf at hx, rcases hx with ⟨hxc, hx0⟩, obtain ⟨n, hn⟩ : ∃ n : ℕ, x n ∉ insert (0 : ℚ) (range x), from (hxc.eventually hx0.is_compact_insert_range.compl_mem_cocompact).exists, exact hn (or.inr ⟨n, rfl⟩) end lemma not_countably_generated_nhds_infty_alexandroff : ¬is_countably_generated (𝓝 (∞ : ℚ∞)) := begin introI, have : is_countably_generated (comap (coe : ℚ → ℚ∞) (𝓝 ∞)), by apply_instance, rw [alexandroff.comap_coe_nhds_infty, coclosed_compact_eq_cocompact] at this, exact not_countably_generated_cocompact this end lemma not_first_countable_topology_alexandroff : ¬first_countable_topology ℚ∞ := by { introI, exact not_countably_generated_nhds_infty_alexandroff infer_instance } lemma not_second_countable_topology_alexandroff : ¬second_countable_topology ℚ∞ := by { introI, exact not_first_countable_topology_alexandroff infer_instance } instance : totally_disconnected_space ℚ := begin refine ⟨λ s hsu hs x hx y hy, _⟩, clear hsu, by_contra' H : x ≠ y, wlog hlt : x < y := H.lt_or_lt using [x y, y x], rcases exists_irrational_btwn (rat.cast_lt.2 hlt) with ⟨z, hz, hxz, hzy⟩, have := hs.image coe continuous_coe_real.continuous_on, rw [is_preconnected_iff_ord_connected] at this, have : z ∈ coe '' s := this.out (mem_image_of_mem _ hx) (mem_image_of_mem _ hy) ⟨hxz.le, hzy.le⟩, exact hz (image_subset_range _ _ this) end end rat
078093d9e4f1a11fdaadf95a85f40bc565de062d
500f65bb93c499cd35c3254d894d762208cae042
/src/category_theory/monoidal/functor.lean
f2d49afd3f1a17643879d67b00b9a2453bd11d74
[ "Apache-2.0" ]
permissive
PatrickMassot/mathlib
c39dc0ff18bbde42f1c93a1642f6e429adad538c
45df75b3c9da159fe3192fa7f769dfbec0bd6bda
refs/heads/master
1,623,168,646,390
1,566,940,765,000
1,566,940,765,000
115,220,590
0
1
null
1,514,061,524,000
1,514,061,524,000
null
UTF-8
Lean
false
false
7,278
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.monoidal.category open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory section open monoidal_category variables (C : Type u₁) [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] (D : Type u₂) [category.{v₂} D] [𝒟 : monoidal_category.{v₂} D] include 𝒞 𝒟 /-- A lax monoidal functor is a functor `F : C ⥤ D` between monoidal categories, equipped with morphisms `ε : 𝟙 _D ⟶ F.obj (𝟙_ C)` and `μ X Y : F.obj X ⊗ F.obj Y ⟶ F.obj (X ⊗ Y)`, satisfying the the appropriate coherences. -/ structure lax_monoidal_functor extends C ⥤ D := -- unit morphism (ε : 𝟙_ D ⟶ obj (𝟙_ C)) -- tensorator (μ : Π X Y : C, (obj X) ⊗ (obj Y) ⟶ obj (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map f) ⊗ (map g)) ≫ μ Y Y' = μ X X' ≫ map (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (obj Z)) ≫ μ (X ⊗ Y) Z ≫ map (α_ X Y Z).hom = (α_ (obj X) (obj Y) (obj Z)).hom ≫ (𝟙 (obj X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (λ_ (obj X)).hom = (ε ⊗ 𝟙 (obj X)) ≫ μ (𝟙_ C) X ≫ map (λ_ X).hom . obviously) (right_unitality' : ∀ X : C, (ρ_ (obj X)).hom = (𝟙 (obj X) ⊗ ε) ≫ μ X (𝟙_ C) ≫ map (ρ_ X).hom . obviously) restate_axiom lax_monoidal_functor.μ_natural' attribute [simp] lax_monoidal_functor.μ_natural restate_axiom lax_monoidal_functor.left_unitality' attribute [simp] lax_monoidal_functor.left_unitality restate_axiom lax_monoidal_functor.right_unitality' attribute [simp] lax_monoidal_functor.right_unitality restate_axiom lax_monoidal_functor.associativity' attribute [simp] lax_monoidal_functor.associativity -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity /-- A monoidal functor is a lax monoidal functor for which the tensorator and unitor as isomorphisms. -/ structure monoidal_functor extends lax_monoidal_functor.{v₁ v₂} C D := (ε_is_iso : is_iso ε . obviously) (μ_is_iso : Π X Y : C, is_iso (μ X Y) . obviously) attribute [instance] monoidal_functor.ε_is_iso monoidal_functor.μ_is_iso variables {C D} def monoidal_functor.ε_iso (F : monoidal_functor.{v₁ v₂} C D) : tensor_unit D ≅ F.obj (tensor_unit C) := as_iso F.ε def monoidal_functor.μ_iso (F : monoidal_functor.{v₁ v₂} C D) (X Y : C) : (F.obj X) ⊗ (F.obj Y) ≅ F.obj (X ⊗ Y) := as_iso (F.μ X Y) end open monoidal_category namespace monoidal_functor section -- In order to express the tensorator as a natural isomorphism, -- we need to be in at least `Type 0`, so we have products. variables {C : Type u₁} [category.{v₁+1} C] [𝒞 : monoidal_category.{v₁+1} C] variables {D : Type u₂} [category.{v₂+1} D] [𝒟 : monoidal_category.{v₂+1} D] include 𝒞 𝒟 /-- The tensorator as a natural isomorphism. -/ def μ_nat_iso (F : monoidal_functor.{v₁+1 v₂+1} C D) : (functor.prod F.to_functor F.to_functor) ⋙ (tensor D) ≅ (tensor C) ⋙ F.to_functor := nat_iso.of_components (by { intros, apply F.μ_iso }) (by { intros, apply F.to_lax_monoidal_functor.μ_natural }) end section variables (C : Type u₁) [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] include 𝒞 /-- The identity monoidal functor. -/ def id : monoidal_functor.{v₁ v₁} C C := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, .. functor.id C } @[simp] lemma id_obj (X : C) : (monoidal_functor.id C).obj X = X := rfl @[simp] lemma id_map {X X' : C} (f : X ⟶ X') : (monoidal_functor.id C).map f = f := rfl @[simp] lemma id_ε : (monoidal_functor.id C).ε = 𝟙 _ := rfl @[simp] lemma id_μ (X Y) : (monoidal_functor.id C).μ X Y = 𝟙 _ := rfl end end monoidal_functor variables {C : Type u₁} [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] [𝒟 : monoidal_category.{v₂} D] variables {E : Type u₃} [category.{v₃} E] [ℰ : monoidal_category.{v₃} E] include 𝒞 𝒟 ℰ namespace lax_monoidal_functor variables (F : lax_monoidal_functor.{v₁ v₂} C D) (G : lax_monoidal_functor.{v₂ v₃} D E) -- The proofs here are horrendous; rewrite_search helps a lot. /-- The composition of two lax monoidal functors is again lax monoidal. -/ def comp : lax_monoidal_functor.{v₁ v₃} C E := { ε := G.ε ≫ (G.map F.ε), μ := λ X Y, G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y), μ_natural' := λ _ _ _ _ f g, begin simp only [functor.comp_map, assoc], rw [←category.assoc, lax_monoidal_functor.μ_natural, category.assoc, ←map_comp, ←map_comp, ←lax_monoidal_functor.μ_natural] end, associativity' := λ X Y Z, begin dsimp, rw id_tensor_comp, slice_rhs 3 4 { rw [← G.to_functor.map_id, G.μ_natural], }, slice_rhs 1 3 { rw ←G.associativity, }, rw comp_tensor_id, slice_lhs 2 3 { rw [← G.to_functor.map_id, G.μ_natural], }, rw [category.assoc, category.assoc, category.assoc, category.assoc, category.assoc, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, F.associativity], end, left_unitality' := λ X, begin dsimp, rw [G.left_unitality, comp_tensor_id, category.assoc, category.assoc], apply congr_arg, rw [F.left_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, right_unitality' := λ X, begin dsimp, rw [G.right_unitality, id_tensor_comp, category.assoc, category.assoc], apply congr_arg, rw [F.right_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, .. (F.to_functor) ⋙ (G.to_functor) }. @[simp] lemma comp_obj (X : C) : (F.comp G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map {X X' : C} (f : X ⟶ X') : (F.comp G).map f = (G.map (F.map f) : G.obj (F.obj X) ⟶ G.obj (F.obj X')) := rfl @[simp] lemma comp_ε : (F.comp G).ε = G.ε ≫ (G.map F.ε) := rfl @[simp] lemma comp_μ (X Y : C) : (F.comp G).μ X Y = G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y) := rfl end lax_monoidal_functor namespace monoidal_functor variables (F : monoidal_functor.{v₁ v₂} C D) (G : monoidal_functor.{v₂ v₃} D E) /-- The composition of two monoidal functors is again monoidal. -/ def comp : monoidal_functor.{v₁ v₃} C E := { ε_is_iso := by { dsimp, apply_instance }, μ_is_iso := by { dsimp, apply_instance }, .. (F.to_lax_monoidal_functor).comp (G.to_lax_monoidal_functor) }. end monoidal_functor end category_theory
f1394a1c381e536ff6308f82b0b81181f431e031
618003631150032a5676f229d13a079ac875ff77
/test/refine_struct.lean
bceed612412d4221890d04f06f3792a29916c392
[ "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,902
lean
import tactic.interactive import algebra.group.basic /-! `refine_struct` caused a variety of interesting problems, which were identified in https://github.com/leanprover-community/mathlib/pull/2251 and https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Need.20help.20with.20class.20instance.20resolution These tests are quite specific to testing the patch made in https://github.com/leanprover-community/mathlib/pull/2319 and are not a complete test suite for `refine_struct`. -/ instance pi_has_one {α : Type*} {β : α → Type*} [Π x, has_one (β x)] : has_one (Π x, β x) := by refine_struct { .. }; exact λ _, 1 open tactic run_cmd (do (declaration.defn _ _ _ b _ _) ← get_decl ``pi_has_one, -- Make sure that `eq.mpr` really doesn't occur in the body: when (b.list_constant.contains ``eq.mpr) $ fail "result generated by `refine_struct` contained an unnecessary `eq.mpr`", -- Make sure that `id` really doesn't occur in the body: when (b.list_constant.contains ``id) $ fail "result generated by `refine_struct` contained an unnecessary `id`") -- Next we check that fields defined for embedded structures are unfolded -- when seen by fields in the outer structure. structure foo (α : Type):= (a : α) structure bar (α : Type) extends foo α := (b : a = a) example : bar ℕ := begin refine_struct { a := 1, .. }, -- We're making sure that the goal is -- ⊢ 1 = 1 -- rather than -- ⊢ {a := 1}.a = {a := 1}.a guard_target 1 = 1, trivial end section variables {α : Type} [_inst : monoid α] include _inst example : true := begin have : group α, { refine_struct { .._inst }, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, }, trivial end end def my_foo {α} (x : semigroup α) (y : group α) : true := trivial example {α : Type} : true := begin have : true, { refine_struct (@my_foo α { .. } { .. } ), -- 9 goals guard_tags _field mul semigroup, admit, -- case semigroup, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc semigroup, admit, -- case semigroup, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field mul group, admit, -- case group, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc group, admit, -- case group, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field one group, admit, -- case group, one -- α : Type -- ⊢ α guard_tags _field one_mul group, admit, -- case group, one_mul -- α : Type -- ⊢ ∀ (a : α), 1 * a = a guard_tags _field mul_one group, admit, -- case group, mul_one -- α : Type -- ⊢ ∀ (a : α), a * 1 = a guard_tags _field inv group, admit, -- case group, inv -- α : Type -- ⊢ α → α guard_tags _field mul_left_inv group, admit, -- case group, mul_left_inv -- α : Type -- ⊢ ∀ (a : α), a⁻¹ * a = 1 }, trivial end def my_bar {α} (x : semigroup α) (y : group α) (i j : α) : α := i example {α : Type} : true := begin have : monoid α, { refine_struct { mul := my_bar { .. } { .. } }, guard_tags _field mul semigroup, admit, guard_tags _field mul_assoc semigroup, admit, guard_tags _field mul group, admit, guard_tags _field mul_assoc group, admit, guard_tags _field one group, admit, guard_tags _field one_mul group, admit, guard_tags _field mul_one group, admit, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, guard_tags _field mul_assoc monoid, admit, guard_tags _field one monoid, admit, guard_tags _field one_mul monoid, admit, guard_tags _field mul_one monoid, admit, }, trivial end
c3d8ed2fbcd8d23aac2b6a8532f6c740a61a2061
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/field_theory/finite_card.lean
96ba7c9e2124f1b703637ef0658e7893635f088a
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,109
lean
/- Copyright (c) 2019 Casper Putz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joey van Langen, Casper Putz -/ import algebra.char_p data.zmod.basic linear_algebra.basis universes u variables (α : Type u) [field α] [fintype α] namespace finite_field theorem card (p : ℕ) [char_p α p] : ∃ (n : ℕ+), nat.prime p ∧ fintype.card α = p^(n : ℕ) := have hp : nat.prime p, from char_p.char_is_prime α p, have V : vector_space (zmodp p hp) α, from {..zmod.to_module' α}, let ⟨n, h⟩ := @vector_space.card_fintype _ _ _ _ V _ _ in have hn : n > 0, from or.resolve_left (nat.eq_zero_or_pos n) (assume h0 : n = 0, have fintype.card α = 1, by rw[←nat.pow_zero (fintype.card _), ←h0]; exact h, have (1 : α) = 0, from (fintype.card_le_one_iff.mp (le_of_eq this)) 1 0, absurd this one_ne_zero), ⟨⟨n, hn⟩, hp, fintype.card_fin p ▸ h⟩ theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ fintype.card α = p^(n : ℕ) := let ⟨p, hc⟩ := char_p.exists α in ⟨p, @finite_field.card α _ _ p hc⟩ end finite_field
0db9fefd0f685509d6ca9f8a17a4bf82d73c13f2
26ac254ecb57ffcb886ff709cf018390161a9225
/src/category_theory/equivalence.lean
388619c0200a6795a92266f1c0f5a8912bae0ef4
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
16,951
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.fully_faithful import category_theory.whiskering import tactic.slice namespace category_theory open category_theory.functor nat_iso category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other words the composite `F ⟶ FGF ⟶ F` is the identity. The triangle equation is written as a family of equalities between morphisms, it is more complicated if we write it as an equality of natural transformations, because then we would have to insert natural transformations like `F ⟶ F1`. -/ structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] := mk' :: (functor : C ⥤ D) (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ functor ⋙ inverse) (counit_iso : inverse ⋙ functor ≅ 𝟭 D) (functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫ counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously) restate_axiom equivalence.functor_unit_iso_comp' infixr ` ≌ `:10 := equivalence variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] namespace equivalence abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv /- While these abbreviations are convenient, they also cause some trouble, preventing structure projections from unfolding. -/ @[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl @[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl @[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl @[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl @[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) := e.functor_unit_iso_comp X @[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) := begin erw [iso.inv_eq_inv (e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)], exact e.functor_unit_comp X end lemma functor_unit (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) = e.counit_inv.app (e.functor.obj X) := by { erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl } lemma counit_functor (e : C ≌ D) (X : C) : e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) := by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl } /-- The other triangle equality. The proof follows the following proof in Globular: http://globular.science/1905.001 -/ @[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) := begin rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp, ←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)), app_hom, app_inv], slice_lhs 2 3 { erw [e.unit.naturality] }, slice_lhs 1 2 { erw [e.unit.naturality] }, slice_lhs 4 4 { rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] }, slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality], erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] }, slice_lhs 3 4 { erw [e.unit_inv.naturality] }, slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 3 4 { erw [←e.unit_inv.naturality] }, slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality, (e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl end @[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) : e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) := begin erw [iso.inv_eq_inv (e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)], exact e.unit_inverse_comp Y end lemma unit_inverse (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) := by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl } lemma inverse_counit (e : C ≌ D) (Y : D) : e.inverse.map (e.counit.app Y) = e.unit_inv.app (e.inverse.obj Y) := by { erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y := (nat_iso.naturality_2 (e.counit_iso) f).symm @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y := (nat_iso.naturality_1 (e.unit_iso) f).symm section -- In this section we convert an arbitrary equivalence to a half-adjoint equivalence. variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) def adjointify_η : 𝟭 C ≅ F ⋙ G := calc 𝟭 C ≅ F ⋙ G : η ... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm ... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G) ... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G) ... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm ... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G) ... ≅ F ⋙ G : left_unitor (F ⋙ G) lemma adjointify_η_ε (X : C) : F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) := begin dsimp [adjointify_η], simp, have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this, rw [←assoc _ _ (F.map _)], have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this, have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this, rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this] end end protected definition mk (F : C ⥤ D) (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D := ⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ @[refl, simps] def refl : C ≌ C := ⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩ @[symm, simps] def symm (e : C ≌ D) : D ≌ C := ⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩ variables {E : Type u₃} [category.{v₃} E] @[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := { functor := e.functor ⋙ f.functor, inverse := f.inverse ⋙ e.inverse, unit_iso := begin refine iso.trans e.unit_iso _, exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) , end, counit_iso := begin refine iso.trans _ f.counit_iso, exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor) end, -- We wouldn't have need to give this proof if we'd used `equivalence.mk`, -- but we choose to avoid using that here, for the sake of good structure projection `simp` lemmas. functor_unit_iso_comp' := λ X, begin dsimp, rw [← f.functor.map_comp_assoc, e.functor.map_comp, functor_unit, fun_inv_map, iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_functor, ← functor.map_comp], erw [comp_id, iso.hom_inv_id_app, functor.map_id], end } def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor @[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) := by { dsimp [fun_inv_id_assoc], tidy } @[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) := by { dsimp [fun_inv_id_assoc], tidy } def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor @[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) := by { dsimp [inv_fun_id_assoc], tidy } @[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) := by { dsimp [inv_fun_id_assoc], tidy } section -- There's of course a monoid structure on `C ≌ C`, -- but let's not encourage using it. -- The power structure is nevertheless useful. /-- Powers of an auto-equivalence. -/ def pow (e : C ≌ C) : ℤ → (C ≌ C) | (int.of_nat 0) := equivalence.refl | (int.of_nat 1) := e | (int.of_nat (n+2)) := e.trans (pow (int.of_nat (n+1))) | (int.neg_succ_of_nat 0) := e.symm | (int.neg_succ_of_nat (n+1)) := e.symm.trans (pow (int.neg_succ_of_nat n)) instance : has_pow (C ≌ C) ℤ := ⟨pow⟩ @[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl @[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl @[simp] lemma pow_minus_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl -- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`. -- At this point, we haven't even defined the category of equivalences. end end equivalence /-- A functor that is part of a (half) adjoint equivalence -/ class is_equivalence (F : C ⥤ D) := mk' :: (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ F ⋙ inverse) (counit_iso : inverse ⋙ F ≅ 𝟭 D) (functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫ counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously) restate_axiom is_equivalence.functor_unit_iso_comp' namespace is_equivalence instance of_equivalence (F : C ≌ D) : is_equivalence F.functor := { ..F } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse := is_equivalence.of_equivalence F.symm open equivalence protected definition mk {F : C ⥤ D} (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F := ⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ end is_equivalence namespace functor def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := ⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso, is_equivalence.functor_unit_iso_comp⟩ instance is_equivalence_refl : is_equivalence (𝟭 C) := is_equivalence.of_equivalence equivalence.refl def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv := is_equivalence.of_equivalence F.as_equivalence.symm @[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.functor = F := rfl @[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.inverse = inv F := rfl @[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] : inv (inv F) = F := rfl def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ 𝟭 C := is_equivalence.unit_iso.symm def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ 𝟭 D := is_equivalence.counit_iso variables {E : Type u₃} [category.{v₃} E] instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace equivalence @[simp] lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl @[simp] lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl @[simp] lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E := by { cases E, congr, } @[simp] lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm := by { cases E, congr, } end equivalence namespace is_equivalence @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = F.inv_fun_id.hom.app X ≫ f ≫ F.inv_fun_id.inv.app Y := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = F.fun_inv_id.hom.app X ≫ f ≫ F.fun_inv_id.inv.app Y := begin erw [nat_iso.naturality_2], refl end -- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`, -- but these are the only ones I need for now. @[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.map (is_equivalence.unit_iso.hom.app Y) ≫ is_equivalence.counit_iso.hom.app (E.obj Y) = 𝟙 _ := equivalence.functor_unit_comp (E.as_equivalence) Y @[simp] lemma counit_inv_functor_comp (E : C ⥤ D) [is_equivalence E] (Y) : is_equivalence.counit_iso.inv.app (E.obj Y) ≫ E.map (is_equivalence.unit_iso.inv.app Y) = 𝟙 _ := eq_of_inv_eq_inv (functor_unit_comp _ _) end is_equivalence class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F.obj (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' namespace functor def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{v₁ v₂} F d def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F.obj (F.obj_preimage d) ≅ d := ess_surj.iso d end functor namespace equivalence def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (F.inv_fun_id.app Y) ⟩ @[priority 100] -- see Note [lower instance priority] instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { map_injective' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p end }. @[priority 100] -- see Note [lower instance priority] instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, F.fun_inv_id.inv.app X ≫ F.inv.map f ≫ F.fun_inv_id.hom.app Y, witness' := λ X Y f, F.inv.map_injective (by simpa only [is_equivalence.inv_fun_map, assoc, iso.hom_inv_id_app_assoc, iso.hom_inv_id_app] using comp_id _) } @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.map_injective, tidy end, map_comp' := λ X Y Z f g, by apply F.map_injective; simp } def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F := is_equivalence.mk (equivalence_inverse F) (nat_iso.of_components (λ X, (preimage_iso $ F.fun_obj_preimage_iso $ F.obj X).symm) (λ X Y f, by { apply F.map_injective, obviously })) (nat_iso.of_components (λ Y, F.fun_obj_preimage_iso Y) (by obviously)) @[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) : e.functor.map f = e.functor.map g ↔ f = g := begin split, { intro w, apply e.functor.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end @[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) : e.inverse.map f = e.inverse.map g ↔ f = g := begin split, { intro w, apply e.inverse.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end end equivalence end category_theory
12ac927bf0faced4963eab9543b74282e8cd28a5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Structure.lean
f7f46a462228c785fa99f75fcf80cf2b287043fa
[ "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
590
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 Additional helper methods that require `MetaM` infrastructure. -/ import Lean.Structure import Lean.Meta.AppBuilder namespace Lean.Meta def getStructureName (struct : Expr) : MetaM Name := match struct.getAppFn with | Expr.const declName .. => do unless isStructure (← getEnv) declName do throwError "'{declName}' is not a structure" return declName | _ => throwError "expected structure" end Lean.Meta
8760ddce3daddc7f7d676532ee54d9f34a75c00c
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/nat/choose/bounds.lean
433ee226684ad36f3181e2257c5ecb664af7a51d
[ "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
1,291
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Eric Rodriguez -/ import algebra.group_power.lemmas import algebra.order.field import data.nat.cast import data.nat.choose.basic /-! # Inequalities for binomial coefficients This file proves exponential bounds on binomial coefficients. We might want to add here the bounds `n^r/r^r ≤ n.choose r ≤ e^r n^r/r^r` in the future. ## Main declarations * `nat.choose_le_pow`: `n.choose r ≤ n^r / r!` * `nat.pow_le_choose`: `(n + 1 - r)^r / r! ≤ n.choose r`. Beware of the fishy ℕ-subtraction. -/ open_locale nat variables {α : Type*} [linear_ordered_field α] namespace nat lemma choose_le_pow (r n : ℕ) : (n.choose r : α) ≤ n^r / r! := begin rw le_div_iff', { norm_cast, rw ←nat.desc_factorial_eq_factorial_mul_choose, exact n.desc_factorial_le_pow r }, exact_mod_cast r.factorial_pos, end -- horrific casting is due to ℕ-subtraction lemma pow_le_choose (r n : ℕ) : ((n + 1 - r : ℕ)^r : α) / r! ≤ n.choose r := begin rw div_le_iff', { norm_cast, rw [←nat.desc_factorial_eq_factorial_mul_choose], exact n.pow_sub_le_desc_factorial r }, exact_mod_cast r.factorial_pos, end end nat
7f93f106910b736158e65eaff5ac8283fa2e45b8
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/bool.lean
09c8aa08aec651484c32740177d3f9cb595fccfe
[ "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
3,315
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.bool Author: Leonardo de Moura -/ import logic.eq open eq eq.ops decidable namespace bool local attribute bor [reducible] local attribute band [reducible] theorem dichotomy (b : bool) : b = ff ∨ b = tt := bool.cases_on b (or.inl rfl) (or.inr rfl) theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem eq_tt_of_ne_ff : ∀ {a : bool}, a ≠ ff → a = tt | @eq_tt_of_ne_ff tt H := rfl | @eq_tt_of_ne_ff ff H := absurd rfl H theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff | @eq_ff_of_ne_tt tt H := absurd rfl H | @eq_ff_of_ne_tt ff H := rfl theorem absurd_of_eq_ff_of_eq_tt {B : Prop} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := absurd (H₁⁻¹ ⬝ H₂) ff_ne_tt theorem tt_bor (a : bool) : bor tt a = tt := rfl notation a || b := bor a b theorem bor_tt (a : bool) : a || tt = tt := bool.cases_on a rfl rfl theorem ff_bor (a : bool) : ff || a = a := bool.cases_on a rfl rfl theorem bor_ff (a : bool) : a || ff = a := bool.cases_on a rfl rfl theorem bor_self (a : bool) : a || a = a := bool.cases_on a rfl rfl theorem bor.comm (a b : bool) : a || b = b || a := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) := match a with | ff := by rewrite *ff_bor | tt := by rewrite *tt_bor end theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ∨ b = tt := bool.rec_on a (assume H : ff || b = tt, have Hb : b = tt, from !ff_bor ▸ H, or.inr Hb) (assume H, or.inl rfl) theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by rewrite H theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := bool.rec_on a (by rewrite H) (by rewrite H) theorem ff_band (a : bool) : ff && a = ff := rfl theorem tt_band (a : bool) : tt && a = a := bool.cases_on a rfl rfl theorem band_ff (a : bool) : a && ff = ff := bool.cases_on a rfl rfl theorem band_tt (a : bool) : a && tt = a := bool.cases_on a rfl rfl theorem band_self (a : bool) : a && a = a := bool.cases_on a rfl rfl theorem band.comm (a b : bool) : a && b = b && a := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := match a with | ff := by rewrite *ff_band | tt := by rewrite *tt_band end theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := or.elim (dichotomy a) (assume H0 : a = ff, absurd (calc ff = ff && b : ff_band ... = a && b : H0 ... = tt : H) ff_ne_tt) (assume H1 : a = tt, H1) theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := by rewrite [H₁, H₂] theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := band_elim_left (!band.comm ⬝ H) theorem bnot_bnot (a : bool) : bnot (bnot a) = a := bool.cases_on a rfl rfl theorem bnot_false : bnot ff = tt := rfl theorem bnot_true : bnot tt = ff := rfl end bool
558e5f1b5894e72564a1e1c314ae1078a5e9fde2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/simple_module.lean
446b87382ecfdf3e7b358403d2bcdf2f81c2a2fa
[ "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
5,338
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import linear_algebra.basic import order.atoms /-! # Simple Modules ## Main Definitions * `is_simple_module` indicates that a module has no proper submodules (the only submodules are `⊥` and `⊤`). * `is_semisimple_module` indicates that every submodule has a complement, or equivalently, the module is a direct sum of simple modules. * A `division_ring` structure on the endomorphism ring of a simple module. ## Main Results * Schur's Lemma: `bijective_or_eq_zero` shows that a linear map between simple modules is either bijective or 0, leading to a `division_ring` structure on the endomorphism ring. ## TODO * Artin-Wedderburn Theory * Unify with the work on Schur's Lemma in a category theory context -/ variables (R : Type*) [ring R] (M : Type*) [add_comm_group M] [module R M] /-- A module is simple when it has only two submodules, `⊥` and `⊤`. -/ abbreviation is_simple_module := (is_simple_order (submodule R M)) /-- A module is semisimple when every submodule has a complement, or equivalently, the module is a direct sum of simple modules. -/ abbreviation is_semisimple_module := (is_complemented (submodule R M)) -- Making this an instance causes the linter to complain of "dangerous instances" theorem is_simple_module.nontrivial [is_simple_module R M] : nontrivial M := ⟨⟨0, begin have h : (⊥ : submodule R M) ≠ ⊤ := bot_ne_top, contrapose! h, ext, simp [submodule.mem_bot,submodule.mem_top, h x], end⟩⟩ variables {R} {M} {m : submodule R M} {N : Type*} [add_comm_group N] [module R N] theorem is_simple_module_iff_is_atom : is_simple_module R m ↔ is_atom m := begin rw ← set.is_simple_order_Iic_iff_is_atom, apply order_iso.is_simple_order_iff, exact submodule.map_subtype.rel_iso m, end namespace is_simple_module variable [hm : is_simple_module R m] @[simp] lemma is_atom : is_atom m := is_simple_module_iff_is_atom.1 hm end is_simple_module theorem is_semisimple_of_Sup_simples_eq_top (h : Sup {m : submodule R M | is_simple_module R m} = ⊤) : is_semisimple_module R M := is_complemented_of_Sup_atoms_eq_top (by simp_rw [← h, is_simple_module_iff_is_atom]) namespace is_semisimple_module variable [is_semisimple_module R M] theorem Sup_simples_eq_top : Sup {m : submodule R M | is_simple_module R m} = ⊤ := begin simp_rw is_simple_module_iff_is_atom, exact Sup_atoms_eq_top, end instance is_semisimple_submodule {m : submodule R M} : is_semisimple_module R m := begin have f : submodule R m ≃o set.Iic m := submodule.map_subtype.rel_iso m, exact f.is_complemented_iff.2 is_modular_lattice.is_complemented_Iic, end end is_semisimple_module theorem is_semisimple_iff_top_eq_Sup_simples : Sup {m : submodule R M | is_simple_module R m} = ⊤ ↔ is_semisimple_module R M := ⟨is_semisimple_of_Sup_simples_eq_top, by { introI, exact is_semisimple_module.Sup_simples_eq_top }⟩ namespace linear_map theorem injective_or_eq_zero [is_simple_module R M] (f : M →ₗ[R] N) : function.injective f ∨ f = 0 := begin rw [← ker_eq_bot, ← ker_eq_top], apply eq_bot_or_eq_top, end theorem injective_of_ne_zero [is_simple_module R M] {f : M →ₗ[R] N} (h : f ≠ 0) : function.injective f := f.injective_or_eq_zero.resolve_right h theorem surjective_or_eq_zero [is_simple_module R N] (f : M →ₗ[R] N) : function.surjective f ∨ f = 0 := begin rw [← range_eq_top, ← range_eq_bot, or_comm], apply eq_bot_or_eq_top, end theorem surjective_of_ne_zero [is_simple_module R N] {f : M →ₗ[R] N} (h : f ≠ 0) : function.surjective f := f.surjective_or_eq_zero.resolve_right h /-- **Schur's Lemma** for linear maps between (possibly distinct) simple modules -/ theorem bijective_or_eq_zero [is_simple_module R M] [is_simple_module R N] (f : M →ₗ[R] N) : function.bijective f ∨ f = 0 := begin by_cases h : f = 0, { right, exact h }, exact or.intro_left _ ⟨injective_of_ne_zero h, surjective_of_ne_zero h⟩, end theorem bijective_of_ne_zero [is_simple_module R M] [is_simple_module R N] {f : M →ₗ[R] N} (h : f ≠ 0): function.bijective f := f.bijective_or_eq_zero.resolve_right h /-- Schur's Lemma makes the endomorphism ring of a simple module a division ring. -/ noncomputable instance _root_.module.End.division_ring [decidable_eq (module.End R M)] [is_simple_module R M] : division_ring (module.End R M) := { inv := λ f, if h : f = 0 then 0 else (linear_map.inverse f (equiv.of_bijective _ (bijective_of_ne_zero h)).inv_fun (equiv.of_bijective _ (bijective_of_ne_zero h)).left_inv (equiv.of_bijective _ (bijective_of_ne_zero h)).right_inv), exists_pair_ne := ⟨0, 1, begin haveI := is_simple_module.nontrivial R M, have h := exists_pair_ne M, contrapose! h, intros x y, simp_rw [ext_iff, one_apply, zero_apply] at h, rw [← h x, h y], end⟩, mul_inv_cancel := begin intros a a0, change (a * (dite _ _ _)) = 1, ext, rw [dif_neg a0, mul_eq_comp, one_apply, comp_apply], exact (equiv.of_bijective _ (bijective_of_ne_zero a0)).right_inv x, end, inv_zero := dif_pos rfl, .. (module.End.ring : ring (module.End R M))} end linear_map
a2149e6c5a499bed38f5c2b5d4c500e96ef2012a
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/limits/set.hlean
3d2d2c2eab04cb9d79f71de90e323897fe828d5d
[ "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
4,198
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer The category of sets is complete and cocomplete -/ import .colimits ..constructions.set hit.set_quotient open eq functor is_trunc sigma pi sigma.ops trunc set_quotient namespace category local attribute category.to_precategory [unfold 2] definition is_complete_set_cone.{u v w} [constructor] (I : Precategory.{v w}) (F : I ⇒ set.{max u v w}) : cone_obj F := begin fapply cone_obj.mk, { fapply trunctype.mk, { exact Σ(s : Π(i : I), trunctype.carrier (F i)), Π{i j : I} (f : i ⟶ j), F f (s i) = (s j)}, { with_options [elaborator.ignore_instances true] -- TODO: fix ( refine is_trunc_sigma _ _; ( apply is_trunc_pi); ( intro s; refine is_trunc_pi _ _; intro i; refine is_trunc_pi _ _; intro j; refine is_trunc_pi _ _; intro f; apply is_trunc_eq))}}, { fapply nat_trans.mk, { intro i x, esimp at x, exact x.1 i}, { intro i j f, esimp, apply eq_of_homotopy, intro x, esimp at x, induction x with s p, esimp, apply p}} end definition is_complete_set.{u v w} [instance] : is_complete.{(max u v w)+1 (max u v w) v w} set := begin intro I F, fapply has_terminal_object.mk, { exact is_complete_set_cone.{u v w} I F}, { intro c, esimp at *, induction c with X η, induction η with η p, esimp at *, fapply is_contr.mk, { fapply cone_hom.mk, { intro x, esimp at *, fapply sigma.mk, { intro i, exact η i x}, { intro i j f, exact ap10 (p f) x}}, { intro i, reflexivity}}, { esimp, intro h, induction h with f q, apply cone_hom_eq, esimp at *, apply eq_of_homotopy, intro x, fapply sigma_eq: esimp, { apply eq_of_homotopy, intro i, exact (ap10 (q i) x)⁻¹}, { with_options [elaborator.ignore_instances true] -- TODO: fix ( refine is_hprop.elimo _ _ _; refine is_trunc_pi _ _; intro i; refine is_trunc_pi _ _; intro j; refine is_trunc_pi _ _; intro f; apply is_trunc_eq)}}} end definition is_cocomplete_set_cone_rel.{u v w} [unfold 3 4] (I : Precategory.{v w}) (F : I ⇒ set.{max u v w}ᵒᵖ) : (Σ(i : I), trunctype.carrier (F i)) → (Σ(i : I), trunctype.carrier (F i)) → hprop.{max u v w} := begin intro v w, induction v with i x, induction w with j y, fapply trunctype.mk, { exact ∃(f : i ⟶ j), to_fun_hom F f y = x}, { exact _} end definition is_cocomplete_set_cone.{u v w} [constructor] (I : Precategory.{v w}) (F : I ⇒ set.{max u v w}ᵒᵖ) : cone_obj F := begin fapply cone_obj.mk, { fapply trunctype.mk, { apply set_quotient (is_cocomplete_set_cone_rel.{u v w} I F)}, { apply is_hset_set_quotient}}, { fapply nat_trans.mk, { intro i x, esimp, apply class_of, exact ⟨i, x⟩}, { intro i j f, esimp, apply eq_of_homotopy, intro y, apply eq_of_rel, esimp, exact exists.intro f idp}} end -- TODO: change this after induction tactic for trunc/set_quotient is implemented definition is_cocomplete_set.{u v w} [instance] : is_cocomplete.{(max u v w)+1 (max u v w) v w} set := begin intro I F, fapply has_terminal_object.mk, { exact is_cocomplete_set_cone.{u v w} I F}, { intro c, esimp at *, induction c with X η, induction η with η p, esimp at *, fapply is_contr.mk, { fapply cone_hom.mk, { refine set_quotient.elim _ _, { intro v, induction v with i x, exact η i x}, { intro v w r, induction v with i x, induction w with j y, esimp at *, refine trunc.elim_on r _, clear r, intro u, induction u with f q, exact ap (η i) q⁻¹ ⬝ ap10 (p f) y}}, { intro i, reflexivity}}, { esimp, intro h, induction h with f q, apply cone_hom_eq, esimp at *, apply eq_of_homotopy, refine set_quotient.rec _ _, { intro v, induction v with i x, esimp, exact (ap10 (q i) x)⁻¹}, { intro v w r, apply is_hprop.elimo}}}, end end category
0ce33790f01b62797bcf818ffe262e0590e22946
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/deprecated/subfield.lean
6ad8ddc8595eaabaca0e897c8ffe70f54bba2d6a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,951
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.deprecated.subring import Mathlib.algebra.group_with_zero.power import Mathlib.PostPort universes u_1 l u_2 namespace Mathlib class is_subfield {F : Type u_1} [field F] (S : set F) extends is_subring S where inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S protected instance is_subfield.field {F : Type u_1} [field F] (S : set F) [is_subfield S] : field ↥S := let cr_inst : comm_ring ↥S := subset.comm_ring; field.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry (fun (x : ↥S) => { val := ↑x⁻¹, property := sorry }) sorry sorry sorry theorem is_subfield.pow_mem {F : Type u_1} [field F] {a : F} {n : ℤ} {s : set F} [is_subfield s] (h : a ∈ s) : a ^ n ∈ s := int.cases_on n (fun (n : ℕ) => is_submonoid.pow_mem h) fun (n : ℕ) => is_subfield.inv_mem (is_submonoid.pow_mem h) protected instance univ.is_subfield {F : Type u_1} [field F] : is_subfield set.univ := is_subfield.mk fun (x : F) (ᾰ : x ∈ set.univ) => trivial /- note: in the next two declarations, if we let type-class inference figure out the instance `ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ protected instance preimage.is_subfield {F : Type u_1} [field F] {K : Type u_2} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (⇑f ⁻¹' s) := is_subfield.mk fun (a : F) (ha : coe_fn f a ∈ s) => (fun (this : coe_fn f (a⁻¹) ∈ s) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f (a⁻¹) ∈ s)) (ring_hom.map_inv f a))) (is_subfield.inv_mem ha)) protected instance image.is_subfield {F : Type u_1} [field F] {K : Type u_2} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (⇑f '' s) := is_subfield.mk fun (a : K) (_x : a ∈ ⇑f '' s) => sorry protected instance range.is_subfield {F : Type u_1} [field F] {K : Type u_2} [field K] (f : F →+* K) : is_subfield (set.range ⇑f) := eq.mpr (id (Eq._oldrec (Eq.refl (is_subfield (set.range ⇑f))) (Eq.symm set.image_univ))) (image.is_subfield f set.univ) namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure {F : Type u_1} [field F] (S : set F) : set F := set_of fun (x : F) => ∃ (y : F), ∃ (H : y ∈ ring.closure S), ∃ (z : F), ∃ (H : z ∈ ring.closure S), y / z = x theorem ring_closure_subset {F : Type u_1} [field F] {S : set F} : ring.closure S ⊆ closure S := fun (x : F) (hx : x ∈ ring.closure S) => Exists.intro x (Exists.intro hx (Exists.intro 1 (Exists.intro is_submonoid.one_mem (div_one x)))) protected instance closure.is_submonoid {F : Type u_1} [field F] {S : set F} : is_submonoid (closure S) := sorry protected instance closure.is_subfield {F : Type u_1} [field F] {S : set F} : is_subfield (closure S) := sorry theorem mem_closure {F : Type u_1} [field F] {S : set F} {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset (ring.mem_closure ha) theorem subset_closure {F : Type u_1} [field F] {S : set F} : S ⊆ closure S := fun (_x : F) => mem_closure theorem closure_subset {F : Type u_1} [field F] {S : set F} {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := sorry theorem closure_subset_iff {F : Type u_1} [field F] (s : set F) (t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := { mp := set.subset.trans subset_closure, mpr := closure_subset } theorem closure_mono {F : Type u_1} [field F] {s : set F} {t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset (set.subset.trans H subset_closure) end field theorem is_subfield_Union_of_directed {F : Type u_1} [field F] {ι : Type u_2} [hι : Nonempty ι] (s : ι → set F) [∀ (i : ι), is_subfield (s i)] (directed : ∀ (i j : ι), ∃ (k : ι), s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (set.Union fun (i : ι) => s i) := sorry protected instance is_subfield.inter {F : Type u_1} [field F] (S₁ : set F) (S₂ : set F) [is_subfield S₁] [is_subfield S₂] : is_subfield (S₁ ∩ S₂) := is_subfield.mk fun (x : F) (hx : x ∈ S₁ ∩ S₂) => { left := is_subfield.inv_mem (and.left hx), right := is_subfield.inv_mem (and.right hx) } protected instance is_subfield.Inter {F : Type u_1} [field F] {ι : Sort u_2} (S : ι → set F) [h : ∀ (y : ι), is_subfield (S y)] : is_subfield (set.Inter S) := is_subfield.mk fun (x : F) (hx : x ∈ set.Inter S) => iff.mpr set.mem_Inter fun (y : ι) => is_subfield.inv_mem (iff.mp set.mem_Inter hx y)
92e4291ebc624bafd4791abfd24152681d0dfa9a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/matchEqs.lean
6fab337f2e263ea6bb4d5545a7f7a16b5f379753
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,483
lean
import Lean syntax (name := test) "test%" ident : command open Lean.Elab open Lean.Elab.Command @[command_elab test] def elabTest : CommandElab := fun stx => do let id ← resolveGlobalConstNoOverloadWithInfo stx[1] liftTermElabM none do Lean.Meta.Match.mkEquationsFor id return () def f (xs ys : List String) : Nat := match xs, ys with | [], [] => 0 | _, ["abc"] => 1 | _, x::xs => xs.length | _, _ => 2 def h (x y : Nat) : Nat := match x, y with | 10000, _ => 0 | 10001, _ => 5 | _, 20000 => 4 | x+1, _ => 3 | Nat.zero, y+1 => 44 | _, _ => 1 theorem ex1 : h 10000 1 = 0 := rfl theorem ex2 : h 10002 1 = 3 := rfl -- set_option trace.Meta.debug true -- set_option pp.proofs true -- set_option trace.Meta.debug truen set_option trace.Meta.Match.matchEqs true in test% f.match_1 #check @f.match_1.eq_1 #check @f.match_1.eq_2 #check @f.match_1.eq_3 #check @f.match_1.eq_4 #check @f.match_1.splitter test% h.match_1 #check @h.match_1.eq_1 #check @h.match_1.eq_2 #check @h.match_1.eq_3 #check @h.match_1.eq_4 #check @h.match_1.eq_5 #check @h.match_1.eq_6 #check @h.match_1.splitter def g (xs ys : List (Nat × String)) : Nat := match xs, ys with | _, [(a,b)] => 0 | [(c, d)], _ => 1 | _, _ => 2 set_option pp.analyze false set_option pp.proofs true set_option trace.Meta.Match.matchEqs true in test% g.match_1 #check @g.match_1.eq_1 #check @g.match_1.eq_2 #check @g.match_1.eq_3 #check @g.match_1.splitter
52dab5ca9d8adde89b26e5e0d03005f1bae117d8
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/n_ary.lean
153dcbd3b092dbdb851a59c45636133656cb0b53
[ "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,892
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.filter.basic /-! # N-ary maps of filter This file defines the binary and ternary maps of filters. This is mostly useful to define pointwise operations on filters. ## Main declarations * `filter.map₂`: Binary map of filters. * `filter.map₃`: Ternary map of filters. ## Notes This file is very similar to the n-ary section of `data.set.basic` and to `data.finset.n_ary`. Please keep them in sync. -/ open function set open_locale filter namespace filter variables {α α' β β' γ γ' δ δ' ε ε' : Type*} {m : α → β → γ} {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {h h₁ h₂ : filter γ} {s s₁ s₂ : set α} {t t₁ t₂ : set β} {u : set γ} {v : set δ} {a : α} {b : β} {c : γ} /-- The image of a binary function `m : α → β → γ` as a function `filter α → filter β → filter γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def map₂ (m : α → β → γ) (f : filter α) (g : filter β) : filter γ := { sets := {s | ∃ u v, u ∈ f ∧ v ∈ g ∧ image2 m u v ⊆ s}, univ_sets := ⟨univ, univ, univ_sets _, univ_sets _, subset_univ _⟩, sets_of_superset := λ s t hs hst, Exists₂.imp (λ u v, and.imp_right $ and.imp_right $ λ h, subset.trans h hst) hs, inter_sets := λ s t, begin simp only [exists_prop, mem_set_of_eq, subset_inter_iff], rintro ⟨s₁, s₂, hs₁, hs₂, hs⟩ ⟨t₁, t₂, ht₁, ht₂, ht⟩, exact ⟨s₁ ∩ t₁, s₂ ∩ t₂, inter_sets f hs₁ ht₁, inter_sets g hs₂ ht₂, (image2_subset (inter_subset_left _ _) $ inter_subset_left _ _).trans hs, (image2_subset (inter_subset_right _ _) $ inter_subset_right _ _).trans ht⟩, end } @[simp] lemma mem_map₂_iff : u ∈ map₂ m f g ↔ ∃ s t, s ∈ f ∧ t ∈ g ∧ image2 m s t ⊆ u := iff.rfl lemma image2_mem_map₂ (hs : s ∈ f) (ht : t ∈ g) : image2 m s t ∈ map₂ m f g := ⟨_, _, hs, ht, subset.rfl⟩ lemma map_prod_eq_map₂ (m : α → β → γ) (f : filter α) (g : filter β) : filter.map (λ p : α × β, m p.1 p.2) (f ×ᶠ g) = map₂ m f g := begin ext s, split, { intro hmem, rw filter.mem_map_iff_exists_image at hmem, obtain ⟨s', hs', hsub⟩ := hmem, rw filter.mem_prod_iff at hs', obtain ⟨t, ht, t', ht', hsub'⟩ := hs', refine ⟨t, t', ht, ht', _⟩, rw ← set.image_prod, exact subset_trans (set.image_subset (λ (p : α × β), m p.fst p.snd) hsub') hsub }, { intro hmem, rw mem_map₂_iff at hmem, obtain ⟨t, t', ht, ht', hsub⟩ := hmem, rw ← set.image_prod at hsub, rw filter.mem_map_iff_exists_image, exact ⟨t ×ˢ t', filter.prod_mem_prod ht ht', hsub⟩ }, end lemma map_prod_eq_map₂' (m : α × β → γ) (f : filter α) (g : filter β) : filter.map m (f ×ᶠ g) = map₂ (λ a b, m (a, b)) f g := by { refine eq.trans _ (map_prod_eq_map₂ (curry m) f g), ext, simp } -- lemma image2_mem_map₂_iff (hm : injective2 m) : image2 m s t ∈ map₂ m f g ↔ s ∈ f ∧ t ∈ g := -- ⟨by { rintro ⟨u, v, hu, hv, h⟩, rw image2_subset_image2_iff hm at h, -- exact ⟨mem_of_superset hu h.1, mem_of_superset hv h.2⟩ }, λ h, image2_mem_map₂ h.1 h.2⟩ lemma map₂_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : map₂ m f₁ g₁ ≤ map₂ m f₂ g₂ := λ _ ⟨s, t, hs, ht, hst⟩, ⟨s, t, hf hs, hg ht, hst⟩ lemma map₂_mono_left (h : g₁ ≤ g₂) : map₂ m f g₁ ≤ map₂ m f g₂ := map₂_mono subset.rfl h lemma map₂_mono_right (h : f₁ ≤ f₂) : map₂ m f₁ g ≤ map₂ m f₂ g := map₂_mono h subset.rfl @[simp] lemma le_map₂_iff {h : filter γ} : h ≤ map₂ m f g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → image2 m s t ∈ h := ⟨λ H s hs t ht, H $ image2_mem_map₂ hs ht, λ H u ⟨s, t, hs, ht, hu⟩, mem_of_superset (H hs ht) hu⟩ @[simp] lemma map₂_bot_left : map₂ m ⊥ g = ⊥ := empty_mem_iff_bot.1 ⟨∅, univ, trivial, univ_mem, (image2_empty_left).subset⟩ @[simp] lemma map₂_bot_right : map₂ m f ⊥ = ⊥ := empty_mem_iff_bot.1 ⟨univ, ∅, univ_mem, trivial, (image2_empty_right).subset⟩ @[simp] lemma map₂_eq_bot_iff : map₂ m f g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := begin simp only [←empty_mem_iff_bot, mem_map₂_iff, subset_empty_iff, image2_eq_empty_iff], split, { rintro ⟨s, t, hs, ht, rfl | rfl⟩, { exact or.inl hs }, { exact or.inr ht } }, { rintro (h | h), { exact ⟨_, _, h, univ_mem, or.inl rfl⟩ }, { exact ⟨_, _, univ_mem, h, or.inr rfl⟩ } } end @[simp] lemma map₂_ne_bot_iff : (map₂ m f g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := by { simp_rw ne_bot_iff, exact map₂_eq_bot_iff.not.trans not_or_distrib } lemma ne_bot.map₂ (hf : f.ne_bot) (hg : g.ne_bot) : (map₂ m f g).ne_bot := map₂_ne_bot_iff.2 ⟨hf, hg⟩ lemma ne_bot.of_map₂_left (h : (map₂ m f g).ne_bot) : f.ne_bot := (map₂_ne_bot_iff.1 h).1 lemma ne_bot.of_map₂_right (h : (map₂ m f g).ne_bot) : g.ne_bot := (map₂_ne_bot_iff.1 h).2 lemma map₂_sup_left : map₂ m (f₁ ⊔ f₂) g = map₂ m f₁ g ⊔ map₂ m f₂ g := begin ext u, split, { rintro ⟨s, t, ⟨h₁, h₂⟩, ht, hu⟩, exact ⟨mem_of_superset (image2_mem_map₂ h₁ ht) hu, mem_of_superset (image2_mem_map₂ h₂ ht) hu⟩ }, { rintro ⟨⟨s₁, t₁, hs₁, ht₁, hu₁⟩, s₂, t₂, hs₂, ht₂, hu₂⟩, refine ⟨s₁ ∪ s₂, t₁ ∩ t₂, union_mem_sup hs₁ hs₂, inter_mem ht₁ ht₂, _⟩, rw image2_union_left, exact union_subset ((image2_subset_left $ inter_subset_left _ _).trans hu₁) ((image2_subset_left $ inter_subset_right _ _).trans hu₂) } end lemma map₂_sup_right : map₂ m f (g₁ ⊔ g₂) = map₂ m f g₁ ⊔ map₂ m f g₂ := begin ext u, split, { rintro ⟨s, t, hs, ⟨h₁, h₂⟩, hu⟩, exact ⟨mem_of_superset (image2_mem_map₂ hs h₁) hu, mem_of_superset (image2_mem_map₂ hs h₂) hu⟩ }, { rintro ⟨⟨s₁, t₁, hs₁, ht₁, hu₁⟩, s₂, t₂, hs₂, ht₂, hu₂⟩, refine ⟨s₁ ∩ s₂, t₁ ∪ t₂, inter_mem hs₁ hs₂, union_mem_sup ht₁ ht₂, _⟩, rw image2_union_right, exact union_subset ((image2_subset_right $ inter_subset_left _ _).trans hu₁) ((image2_subset_right $ inter_subset_right _ _).trans hu₂) } end lemma map₂_inf_subset_left : map₂ m (f₁ ⊓ f₂) g ≤ map₂ m f₁ g ⊓ map₂ m f₂ g := le_inf (map₂_mono_right inf_le_left) (map₂_mono_right inf_le_right) lemma map₂_inf_subset_right : map₂ m f (g₁ ⊓ g₂) ≤ map₂ m f g₁ ⊓ map₂ m f g₂ := le_inf (map₂_mono_left inf_le_left) (map₂_mono_left inf_le_right) @[simp] lemma map₂_pure_left : map₂ m (pure a) g = g.map (λ b, m a b) := filter.ext $ λ u, ⟨λ ⟨s, t, hs, ht, hu⟩, mem_of_superset (image_mem_map ht) ((image_subset_image2_right $ mem_pure.1 hs).trans hu), λ h, ⟨{a}, _, singleton_mem_pure, h, by rw [image2_singleton_left, image_subset_iff]⟩⟩ @[simp] lemma map₂_pure_right : map₂ m f (pure b) = f.map (λ a, m a b) := filter.ext $ λ u, ⟨λ ⟨s, t, hs, ht, hu⟩, mem_of_superset (image_mem_map hs) ((image_subset_image2_left $ mem_pure.1 ht).trans hu), λ h, ⟨_, {b}, h, singleton_mem_pure, by rw [image2_singleton_right, image_subset_iff]⟩⟩ lemma map₂_pure : map₂ m (pure a) (pure b) = pure (m a b) := by rw [map₂_pure_right, map_pure] lemma map₂_swap (m : α → β → γ) (f : filter α) (g : filter β) : map₂ m f g = map₂ (λ a b, m b a) g f := by { ext u, split; rintro ⟨s, t, hs, ht, hu⟩; refine ⟨t, s, ht, hs, by rwa image2_swap⟩ } @[simp] lemma map₂_left (h : g.ne_bot) : map₂ (λ x y, x) f g = f := begin ext u, refine ⟨_, λ hu, ⟨_, _, hu, univ_mem, (image2_left $ h.nonempty_of_mem univ_mem).subset⟩⟩, rintro ⟨s, t, hs, ht, hu⟩, rw image2_left (h.nonempty_of_mem ht) at hu, exact mem_of_superset hs hu, end @[simp] lemma map₂_right (h : f.ne_bot) : map₂ (λ x y, y) f g = g := by rw [map₂_swap, map₂_left h] /-- The image of a ternary function `m : α → β → γ → δ` as a function `filter α → filter β → filter γ → filter δ`. Mathematically this should be thought of as the image of the corresponding function `α × β × γ → δ`. -/ def map₃ (m : α → β → γ → δ) (f : filter α) (g : filter β) (h : filter γ) : filter δ := { sets := {s | ∃ u v w, u ∈ f ∧ v ∈ g ∧ w ∈ h ∧ image3 m u v w ⊆ s}, univ_sets := ⟨univ, univ, univ, univ_sets _, univ_sets _, univ_sets _, subset_univ _⟩, sets_of_superset := λ s t hs hst, Exists₃.imp (λ u v w, and.imp_right $ and.imp_right $ and.imp_right $ λ h, subset.trans h hst) hs, inter_sets := λ s t, begin simp only [exists_prop, mem_set_of_eq, subset_inter_iff], rintro ⟨s₁, s₂, s₃, hs₁, hs₂, hs₃, hs⟩ ⟨t₁, t₂, t₃, ht₁, ht₂, ht₃, ht⟩, exact ⟨s₁ ∩ t₁, s₂ ∩ t₂, s₃ ∩ t₃, inter_mem hs₁ ht₁, inter_mem hs₂ ht₂, inter_mem hs₃ ht₃, (image3_mono (inter_subset_left _ _) (inter_subset_left _ _) $ inter_subset_left _ _).trans hs, (image3_mono (inter_subset_right _ _) (inter_subset_right _ _) $ inter_subset_right _ _).trans ht⟩, end } lemma map₂_map₂_left (m : δ → γ → ε) (n : α → β → δ) : map₂ m (map₂ n f g) h = map₃ (λ a b c, m (n a b) c) f g h := begin ext w, split, { rintro ⟨s, t, ⟨u, v, hu, hv, hs⟩, ht, hw⟩, refine ⟨u, v, t, hu, hv, ht, _⟩, rw ←image2_image2_left, exact (image2_subset_right hs).trans hw }, { rintro ⟨s, t, u, hs, ht, hu, hw⟩, exact ⟨_, u, image2_mem_map₂ hs ht, hu, by rwa image2_image2_left⟩ } end lemma map₂_map₂_right (m : α → δ → ε) (n : β → γ → δ) : map₂ m f (map₂ n g h) = map₃ (λ a b c, m a (n b c)) f g h := begin ext w, split, { rintro ⟨s, t, hs, ⟨u, v, hu, hv, ht⟩, hw⟩, refine ⟨s, u, v, hs, hu, hv, _⟩, rw ←image2_image2_right, exact (image2_subset_left ht).trans hw }, { rintro ⟨s, t, u, hs, ht, hu, hw⟩, exact ⟨s, _, hs, image2_mem_map₂ ht hu, by rwa image2_image2_right⟩ } end lemma map_map₂ (m : α → β → γ) (n : γ → δ) : (map₂ m f g).map n = map₂ (λ a b, n (m a b)) f g := filter.ext $ λ u, exists₂_congr $ λ s t, by rw [←image_subset_iff, image_image2] lemma map₂_map_left (m : γ → β → δ) (n : α → γ) : map₂ m (f.map n) g = map₂ (λ a b, m (n a) b) f g := begin ext u, split, { rintro ⟨s, t, hs, ht, hu⟩, refine ⟨_, t, hs, ht, _⟩, rw ←image2_image_left, exact (image2_subset_right $ image_preimage_subset _ _).trans hu }, { rintro ⟨s, t, hs, ht, hu⟩, exact ⟨_, t, image_mem_map hs, ht, by rwa image2_image_left⟩ } end lemma map₂_map_right (m : α → γ → δ) (n : β → γ) : map₂ m f (g.map n) = map₂ (λ a b, m a (n b)) f g := by rw [map₂_swap, map₂_map_left, map₂_swap] /-! ### Algebraic replacement rules A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations to the associativity, commutativity, distributivity, ... of `filter.map₂` of those operations. The proof pattern is `map₂_lemma operation_lemma`. For example, `map₂_comm mul_comm` proves that `map₂ (*) f g = map₂ (*) g f` in a `comm_semigroup`. -/ lemma map₂_assoc {m : δ → γ → ε} {n : α → β → δ} {m' : α → ε' → ε} {n' : β → γ → ε'} {h : filter γ} (h_assoc : ∀ a b c, m (n a b) c = m' a (n' b c)) : map₂ m (map₂ n f g) h = map₂ m' f (map₂ n' g h) := by simp only [map₂_map₂_left, map₂_map₂_right, h_assoc] lemma map₂_comm {n : β → α → γ} (h_comm : ∀ a b, m a b = n b a) : map₂ m f g = map₂ n g f := (map₂_swap _ _ _).trans $ by simp_rw h_comm lemma map₂_left_comm {m : α → δ → ε} {n : β → γ → δ} {m' : α → γ → δ'} {n' : β → δ' → ε} (h_left_comm : ∀ a b c, m a (n b c) = n' b (m' a c)) : map₂ m f (map₂ n g h) = map₂ n' g (map₂ m' f h) := by { rw [map₂_swap m', map₂_swap m], exact map₂_assoc (λ _ _ _, h_left_comm _ _ _) } lemma map₂_right_comm {m : δ → γ → ε} {n : α → β → δ} {m' : α → γ → δ'} {n' : δ' → β → ε} (h_right_comm : ∀ a b c, m (n a b) c = n' (m' a c) b) : map₂ m (map₂ n f g) h = map₂ n' (map₂ m' f h) g := by { rw [map₂_swap n, map₂_swap n'], exact map₂_assoc (λ _ _ _, h_right_comm _ _ _) } lemma map_map₂_distrib {n : γ → δ} {m' : α' → β' → δ} {n₁ : α → α'} {n₂ : β → β'} (h_distrib : ∀ a b, n (m a b) = m' (n₁ a) (n₂ b)) : (map₂ m f g).map n = map₂ m' (f.map n₁) (g.map n₂) := by simp_rw [map_map₂, map₂_map_left, map₂_map_right, h_distrib] /-- Symmetric of `filter.map₂_map_left_comm`. -/ lemma map_map₂_distrib_left {n : γ → δ} {m' : α' → β → δ} {n' : α → α'} (h_distrib : ∀ a b, n (m a b) = m' (n' a) b) : (map₂ m f g).map n = map₂ m' (f.map n') g := map_map₂_distrib h_distrib /-- Symmetric of `filter.map_map₂_right_comm`. -/ lemma map_map₂_distrib_right {n : γ → δ} {m' : α → β' → δ} {n' : β → β'} (h_distrib : ∀ a b, n (m a b) = m' a (n' b)) : (map₂ m f g).map n = map₂ m' f (g.map n') := map_map₂_distrib h_distrib /-- Symmetric of `filter.map_map₂_distrib_left`. -/ lemma map₂_map_left_comm {m : α' → β → γ} {n : α → α'} {m' : α → β → δ} {n' : δ → γ} (h_left_comm : ∀ a b, m (n a) b = n' (m' a b)) : map₂ m (f.map n) g = (map₂ m' f g).map n' := (map_map₂_distrib_left $ λ a b, (h_left_comm a b).symm).symm /-- Symmetric of `filter.map_map₂_distrib_right`. -/ lemma map_map₂_right_comm {m : α → β' → γ} {n : β → β'} {m' : α → β → δ} {n' : δ → γ} (h_right_comm : ∀ a b, m a (n b) = n' (m' a b)) : map₂ m f (g.map n) = (map₂ m' f g).map n' := (map_map₂_distrib_right $ λ a b, (h_right_comm a b).symm).symm lemma map_map₂_antidistrib {n : γ → δ} {m' : β' → α' → δ} {n₁ : β → β'} {n₂ : α → α'} (h_antidistrib : ∀ a b, n (m a b) = m' (n₁ b) (n₂ a)) : (map₂ m f g).map n = map₂ m' (g.map n₁) (f.map n₂) := by { rw map₂_swap m, exact map_map₂_distrib (λ _ _, h_antidistrib _ _) } /-- Symmetric of `filter.map₂_map_left_anticomm`. -/ lemma map_map₂_antidistrib_left {n : γ → δ} {m' : β' → α → δ} {n' : β → β'} (h_antidistrib : ∀ a b, n (m a b) = m' (n' b) a) : (map₂ m f g).map n = map₂ m' (g.map n') f := map_map₂_antidistrib h_antidistrib /-- Symmetric of `filter.map_map₂_right_anticomm`. -/ lemma map_map₂_antidistrib_right {n : γ → δ} {m' : β → α' → δ} {n' : α → α'} (h_antidistrib : ∀ a b, n (m a b) = m' b (n' a)) : (map₂ m f g).map n = map₂ m' g (f.map n') := map_map₂_antidistrib h_antidistrib /-- Symmetric of `filter.map_map₂_antidistrib_left`. -/ lemma map₂_map_left_anticomm {m : α' → β → γ} {n : α → α'} {m' : β → α → δ} {n' : δ → γ} (h_left_anticomm : ∀ a b, m (n a) b = n' (m' b a)) : map₂ m (f.map n) g = (map₂ m' g f).map n' := (map_map₂_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm /-- Symmetric of `filter.map_map₂_antidistrib_right`. -/ lemma map_map₂_right_anticomm {m : α → β' → γ} {n : β → β'} {m' : β → α → δ} {n' : δ → γ} (h_right_anticomm : ∀ a b, m a (n b) = n' (m' b a)) : map₂ m f (g.map n) = (map₂ m' g f).map n' := (map_map₂_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm end filter
5762e1e5c15c09d3b0b38310e3248f4bc0f3232c
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/uintCtors.lean
60354218c8d69ac7316ede597279afb092d9c825
[ "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
1,397
lean
def UInt32.ofNatCore' (n : Nat) (h : Less n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } #eval UInt32.ofNatCore' 10 (by decide) def UInt64.ofNatCore' (n : Nat) (h : Less n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } #eval UInt64.ofNatCore' 3 (by decide) #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt8 } #eval (3 : UInt8).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt16 } #eval (3 : UInt16).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt32 } #eval (3 : UInt32).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt64 } #eval (3 : UInt64).val #eval toString $ { val := { val := 3, isLt := (match USize.size, usizeSzEq with | _, Or.inl rfl => (by decide) | _, Or.inr rfl => (by decide)) } : USize } #eval (3 : USize).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt8 } #eval (4 : UInt8).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt16 } #eval (4 : UInt16).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt32 } #eval (4 : UInt32).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt64 } #eval (4 : UInt64).val #eval toString $ { val := { val := 4, isLt := (match USize.size, usizeSzEq with | _, Or.inl rfl => (by decide) | _, Or.inr rfl => (by decide)) } : USize } #eval (4 : USize).val
08724a23af78a761db24ff566c360548bed1dd90
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/group_action/defs.lean
3c33d0fd4a8ede573084257913a3d1c8e4c028f9
[ "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
39,816
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov -/ import algebra.group.type_tags import algebra.group.commute import algebra.hom.group import algebra.opposites import logic.embedding.basic /-! # Definitions of group actions This file defines a hierarchy of group action type-classes on top of the previously defined notation classes `has_smul` and its additive version `has_vadd`: * `mul_action M α` and its additive version `add_action G P` are typeclasses used for actions of multiplicative and additive monoids and groups; they extend notation classes `has_smul` and `has_vadd` that are defined in `algebra.group.defs`; * `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`. The hierarchy is extended further by `module`, defined elsewhere. Also provided are typeclasses for faithful and transitive actions, and typeclasses regarding the interaction of different group actions, * `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`; * `is_scalar_tower M N α` (no additive version). * `is_central_scalar M α` (no additive version). ## Notation - `a • b` is used as notation for `has_smul.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. ## Tags group action -/ variables {M N G A B α β γ δ : Type*} open function (injective surjective) /-! ### Faithful actions -/ /-- Typeclass for faithful actions. -/ class has_faithful_vadd (G : Type*) (P : Type*) [has_vadd G P] : Prop := (eq_of_vadd_eq_vadd : ∀ {g₁ g₂ : G}, (∀ p : P, g₁ +ᵥ p = g₂ +ᵥ p) → g₁ = g₂) /-- Typeclass for faithful actions. -/ @[to_additive] class has_faithful_smul (M : Type*) (α : Type*) [has_smul M α] : Prop := (eq_of_smul_eq_smul : ∀ {m₁ m₂ : M}, (∀ a : α, m₁ • a = m₂ • a) → m₁ = m₂) export has_faithful_smul (eq_of_smul_eq_smul) has_faithful_vadd (eq_of_vadd_eq_vadd) @[to_additive] lemma smul_left_injective' [has_smul M α] [has_faithful_smul M α] : function.injective ((•) : M → α → α) := λ m₁ m₂ h, has_faithful_smul.eq_of_smul_eq_smul (congr_fun h) /-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/ @[priority 910, -- see Note [lower instance priority] to_additive "See also `add_monoid.to_add_action`"] instance has_mul.to_has_smul (α : Type*) [has_mul α] : has_smul α α := ⟨(*)⟩ @[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl /-- Type class for additive monoid actions. -/ @[ext, protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p) (add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p)) /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[ext, protect_proj, to_additive] class mul_action (α : Type*) (β : Type*) [monoid α] extends has_smul α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) /-! ### (Pre)transitive action `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y` (or `g +ᵥ x = y` for an additive action). A transitive action should furthermore have `α` nonempty. In this section we define typeclasses `mul_action.is_pretransitive` and `add_action.is_pretransitive` and provide `mul_action.exists_smul_eq`/`add_action.exists_vadd_eq`, `mul_action.surjective_smul`/`add_action.surjective_vadd` as public interface to access this property. We do not provide typeclasses `*_action.is_transitive`; users should assume `[mul_action.is_pretransitive M α] [nonempty α]` instead. -/ /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g +ᵥ x = y`. A transitive action should furthermore have `α` nonempty. -/ class add_action.is_pretransitive (M α : Type*) [has_vadd M α] : Prop := (exists_vadd_eq : ∀ x y : α, ∃ g : M, g +ᵥ x = y) /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y`. A transitive action should furthermore have `α` nonempty. -/ @[to_additive] class mul_action.is_pretransitive (M α : Type*) [has_smul M α] : Prop := (exists_smul_eq : ∀ x y : α, ∃ g : M, g • x = y) namespace mul_action variables (M) {α} [has_smul M α] [is_pretransitive M α] @[to_additive] lemma exists_smul_eq (x y : α) : ∃ m : M, m • x = y := is_pretransitive.exists_smul_eq x y @[to_additive] lemma surjective_smul (x : α) : surjective (λ c : M, c • x) := exists_smul_eq M x /-- The regular action of a group on itself is transitive. -/ @[to_additive "The regular action of a group on itself is transitive."] instance regular.is_pretransitive [group G] : is_pretransitive G G := ⟨λ x y, ⟨y * x⁻¹, inv_mul_cancel_right _ _⟩⟩ end mul_action /-! ### Scalar tower and commuting actions -/ /-- A typeclass mixin saying that two additive actions on the same space commute. -/ class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop := (vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a)) /-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/ @[to_additive] class smul_comm_class (M N α : Type*) [has_smul M α] [has_smul N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm) vadd_comm_class (vadd_comm) /-- Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring `R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring. To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or `(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and `add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate the typeclass, which is still sufficient to recover a `≃+` or `→+` structure. An example of where this is used is `linear_map.prod_equiv`. -/ library_note "bundled maps over different rings" /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ @[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_smul M α] [has_smul N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ /-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ add_decl_doc vadd_comm_class.symm @[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `vadd_assoc_class M N α` states that the additive action of `M` on `α` is determined by the additive actions of `M` on `N` and `N` on `α`. -/ class vadd_assoc_class (M N α : Type*) [has_vadd M N] [has_vadd N α] [has_vadd M α] : Prop := (vadd_assoc : ∀ (x : M) (y : N) (z : α), (x +ᵥ y) +ᵥ z = x +ᵥ (y +ᵥ z)) /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ @[to_additive] class is_scalar_tower (M N α : Type*) [has_smul M N] [has_smul N α] [has_smul M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp, to_additive] lemma smul_assoc {M N} [has_smul M N] [has_smul N α] [has_smul M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z @[to_additive] instance semigroup.is_scalar_tower [semigroup α] : is_scalar_tower α α α := ⟨mul_assoc⟩ /-- A typeclass indicating that the right (aka `add_opposite`) and left actions by `M` on `α` are equal, that is that `M` acts centrally on `α`. This can be thought of as a version of commutativity for `+ᵥ`. -/ class is_central_vadd (M α : Type*) [has_vadd M α] [has_vadd Mᵃᵒᵖ α] : Prop := (op_vadd_eq_vadd : ∀ (m : M) (a : α), add_opposite.op m +ᵥ a = m +ᵥ a) /-- A typeclass indicating that the right (aka `mul_opposite`) and left actions by `M` on `α` are equal, that is that `M` acts centrally on `α`. This can be thought of as a version of commutativity for `•`. -/ @[to_additive] class is_central_scalar (M α : Type*) [has_smul M α] [has_smul Mᵐᵒᵖ α] : Prop := (op_smul_eq_smul : ∀ (m : M) (a : α), mul_opposite.op m • a = m • a) @[to_additive] lemma is_central_scalar.unop_smul_eq_smul {M α : Type*} [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] (m : Mᵐᵒᵖ) (a : α) : (mul_opposite.unop m) • a = m • a := mul_opposite.rec (by exact λ m, (is_central_scalar.op_smul_eq_smul _ _).symm) m export is_central_vadd (op_vadd_eq_vadd unop_vadd_eq_vadd) export is_central_scalar (op_smul_eq_smul unop_smul_eq_smul) -- these instances are very low priority, as there is usually a faster way to find these instances @[priority 50, to_additive] instance smul_comm_class.op_left [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] [has_smul N α] [smul_comm_class M N α] : smul_comm_class Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m a, smul_comm]⟩ @[priority 50, to_additive] instance smul_comm_class.op_right [has_smul M α] [has_smul N α] [has_smul Nᵐᵒᵖ α] [is_central_scalar N α] [smul_comm_class M N α] : smul_comm_class M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n (m • a), ←unop_smul_eq_smul n a, smul_comm]⟩ @[priority 50, to_additive] instance is_scalar_tower.op_left [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] [has_smul M N] [has_smul Mᵐᵒᵖ N] [is_central_scalar M N] [has_smul N α] [is_scalar_tower M N α] : is_scalar_tower Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m n, smul_assoc]⟩ @[priority 50, to_additive] instance is_scalar_tower.op_right [has_smul M α] [has_smul M N] [has_smul N α] [has_smul Nᵐᵒᵖ α] [is_central_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n a, ←unop_smul_eq_smul (m • n) a, mul_opposite.unop_smul, smul_assoc]⟩ namespace has_smul variables [has_smul M α] /-- Auxiliary definition for `has_smul.comp`, `mul_action.comp_hom`, `distrib_mul_action.comp_hom`, `module.comp_hom`, etc. -/ @[simp, to_additive /-" Auxiliary definition for `has_vadd.comp`, `add_action.comp_hom`, etc. "-/] def comp.smul (g : N → M) (n : N) (a : α) : α := g n • a variables (α) /-- An action of `M` on `α` and a function `N → M` induces an action of `N` on `α`. See note [reducible non-instances]. Since this is reducible, we make sure to go via `has_smul.comp.smul` to prevent typeclass inference unfolding too far. -/ @[reducible, to_additive /-" An additive action of `M` on `α` and a function `N → M` induces an additive action of `N` on `α` "-/] def comp (g : N → M) : has_smul N α := { smul := has_smul.comp.smul g } variables {α} /-- Given a tower of scalar actions `M → α → β`, if we use `has_smul.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100, to_additive "Given a tower of additive actions `M → α → β`, if we use `has_smul.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables."] lemma comp.is_scalar_tower [has_smul M β] [has_smul α β] [is_scalar_tower M α β] (g : N → M) : (by haveI := comp α g; haveI := comp β g; exact is_scalar_tower N α β) := by exact {smul_assoc := λ n, @smul_assoc _ _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100, to_additive "This cannot be an instance because it can cause infinite loops whenever the `has_vadd` arguments are still metavariables."] lemma comp.smul_comm_class [has_smul β α] [smul_comm_class M β α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class N β α) := by exact {smul_comm := λ n, @smul_comm _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100, to_additive "This cannot be an instance because it can cause infinite loops whenever the `has_vadd` arguments are still metavariables."] lemma comp.smul_comm_class' [has_smul β α] [smul_comm_class β M α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class β N α) := by exact {smul_comm := λ _ n, @smul_comm _ _ _ _ _ _ _ (g n) } end has_smul section /-- Note that the `smul_comm_class α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive, nolint to_additive_doc] lemma mul_smul_comm [has_mul β] [has_smul α β] [smul_comm_class α β β] (s : α) (x y : β) : x * (s • y) = s • (x * y) := (smul_comm s x y).symm /-- Note that the `is_scalar_tower α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive, nolint to_additive_doc] lemma smul_mul_assoc [has_mul β] [has_smul α β] [is_scalar_tower α β β] (r : α) (x y : β) : (r • x) * y = r • (x * y) := smul_assoc r x y @[to_additive] lemma smul_smul_smul_comm [has_smul α β] [has_smul α γ] [has_smul β δ] [has_smul α δ] [has_smul γ δ] [is_scalar_tower α β δ] [is_scalar_tower α γ δ] [smul_comm_class β γ δ] (a : α) (b : β) (c : γ) (d : δ) : (a • b) • (c • d) = (a • c) • b • d := by { rw [smul_assoc, smul_assoc, smul_comm b], apply_instance } variables [has_smul M α] @[to_additive] lemma commute.smul_right [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute a (r • b) := (mul_smul_comm _ _ _).trans ((congr_arg _ h).trans $ (smul_mul_assoc _ _ _).symm) @[to_additive] lemma commute.smul_left [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute (r • a) b := (h.symm.smul_right r).symm end section ite variables [has_smul M α] (p : Prop) [decidable p] @[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl @[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite section variables [monoid M] [mul_action M α] @[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (M) @[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _ /-- `has_smul` version of `one_mul_eq_id` -/ @[to_additive "`has_vadd` version of `zero_add_eq_id`"] lemma one_smul_eq_id : ((•) (1 : M) : α → α) = id := funext $ one_smul _ /-- `has_smul` version of `comp_mul_left` -/ @[to_additive "`has_vadd` version of `comp_add_left`"] lemma comp_smul_left (a₁ a₂ : M) : (•) a₁ ∘ (•) a₂ = ((•) (a₁ * a₂) : α → α) := funext $ λ _, (mul_smul _ _ _).symm variables {M} /-- Pullback a multiplicative action along an injective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."] protected def function.injective.mul_action [has_smul M β] (f : β → α) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."] protected def function.surjective.mul_action [has_smul M β] (f : α → β) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.distrib_mul_action_left` and `function.surjective.module_left`. -/ @[reducible, to_additive "Push forward the action of `R` on `M` along a compatible surjective map `f : R →+ S`."] def function.surjective.mul_action_left {R S M : Type*} [monoid R] [mul_action R M] [monoid S] [has_smul S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : mul_action S M := { smul := (•), one_smul := λ b, by rw [← f.map_one, hsmul, one_smul], mul_smul := hf.forall₂.mpr $ λ a b x, by simp only [← f.map_mul, hsmul, mul_smul] } section variables (M) /-- The regular action of a monoid on itself by left multiplication. This is promoted to a module by `semiring.to_module`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance monoid.to_mul_action : mul_action M M := { smul := (*), one_smul := one_mul, mul_smul := mul_assoc } /-- The regular action of a monoid on itself by left addition. This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/ add_decl_doc add_monoid.to_add_action @[to_additive] instance is_scalar_tower.left : is_scalar_tower M M α := ⟨λ x y z, mul_smul x y z⟩ variables {M} /-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are usually satisfied by `algebra M α`. -/ @[to_additive, nolint to_additive_doc] lemma smul_mul_smul [has_mul α] (r s : M) (x y : α) [is_scalar_tower M α α] [smul_comm_class M α α] : (r • x) * (s • y) = (r * s) • (x * y) := by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] end namespace mul_action variables (M α) /-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/ @[to_additive] def to_fun : α ↪ (M → α) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩ /-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/ add_decl_doc add_action.to_fun variables {M α} @[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y := rfl variable (α) /-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce a multiplicative action of `N` on `α`. See note [reducible non-instances]. -/ @[reducible, to_additive] def comp_hom [monoid N] (g : N →* M) : mul_action N α := { smul := has_smul.comp.smul g, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } /-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce an additive action of `N` on `α`. See note [reducible non-instances]. -/ add_decl_doc add_action.comp_hom end mul_action end section compatible_scalar @[simp, to_additive] lemma smul_one_smul {M} (N) [monoid N] [has_smul M N] [mul_action N α] [has_smul M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] @[simp, to_additive] lemma smul_one_mul {M N} [mul_one_class N] [has_smul M N] [is_scalar_tower M N N] (x : M) (y : N) : (x • 1) * y = x • y := by rw [smul_mul_assoc, one_mul] @[simp, to_additive] lemma mul_smul_one {M N} [mul_one_class N] [has_smul M N] [smul_comm_class M N N] (x : M) (y : N) : y * (x • 1) = x • y := by rw [← smul_eq_mul, ← smul_comm, smul_eq_mul, mul_one] @[to_additive] lemma is_scalar_tower.of_smul_one_mul {M N} [monoid N] [has_smul M N] (h : ∀ (x : M) (y : N), (x • (1 : N)) * y = x • y) : is_scalar_tower M N N := ⟨λ x y z, by rw [← h, smul_eq_mul, mul_assoc, h, smul_eq_mul]⟩ @[to_additive] lemma smul_comm_class.of_mul_smul_one {M N} [monoid N] [has_smul M N] (H : ∀ (x : M) (y : N), y * (x • (1 : N)) = x • y) : smul_comm_class M N N := ⟨λ x y z, by rw [← H x z, smul_eq_mul, ← H, smul_eq_mul, mul_assoc]⟩ /-- If the multiplicative action of `M` on `N` is compatible with multiplication on `N`, then `λ x, x • 1` is a monoid homomorphism from `M` to `N`. -/ @[to_additive "If the additive action of `M` on `N` is compatible with addition on `N`, then `λ x, x +ᵥ 0` is an additive monoid homomorphism from `M` to `N`.", simps] def smul_one_hom {M N} [monoid M] [monoid N] [mul_action M N] [is_scalar_tower M N N] : M →* N := { to_fun := λ x, x • 1, map_one' := one_smul _ _, map_mul' := λ x y, by rw [smul_one_mul, smul_smul] } end compatible_scalar /-- Typeclass for scalar multiplication that preserves `0` on the right. -/ class smul_zero_class (M A : Type*) [has_zero A] extends has_smul M A := (smul_zero : ∀ (a : M), a • (0 : A) = 0) section smul_zero variables [has_zero A] [smul_zero_class M A] @[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 := smul_zero_class.smul_zero _ /-- Pullback a zero-preserving scalar multiplication along an injective zero-preserving map. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.smul_zero_class [has_zero B] [has_smul M B] (f : zero_hom B A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : smul_zero_class M B := { smul := (•), smul_zero := λ c, hf $ by simp only [smul, map_zero, smul_zero] } /-- Pushforward a zero-preserving scalar multiplication along a zero-preserving map. See note [reducible non-instances]. -/ @[reducible] protected def zero_hom.smul_zero_class [has_zero B] [has_smul M B] (f : zero_hom A B) (smul : ∀ (c : M) x, f (c • x) = c • f x) : smul_zero_class M B := { smul := (•), smul_zero := λ c, by simp only [← map_zero f, ← smul, smul_zero] } /-- Push forward the multiplication of `R` on `M` along a compatible surjective map `f : R → S`. See also `function.surjective.distrib_mul_action_left`. -/ @[reducible] def function.surjective.smul_zero_class_left {R S M : Type*} [has_zero M] [smul_zero_class R M] [has_smul S M] (f : R → S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : smul_zero_class S M := { smul := (•), smul_zero := hf.forall.mpr $ λ c, by rw [hsmul, smul_zero] } variable (A) /-- Compose a `smul_zero_class` with a function, with scalar multiplication `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def smul_zero_class.comp_fun (f : N → M) : smul_zero_class N A := { smul := has_smul.comp.smul f, smul_zero := λ x, smul_zero (f x) } /-- Each element of the scalars defines a zero-preserving map. -/ @[simps] def smul_zero_class.to_zero_hom (x : M) : zero_hom A A := { to_fun := (•) x, map_zero' := smul_zero x } end smul_zero /-- Typeclass for scalar multiplication that preserves `0` and `+` on the right. This is exactly `distrib_mul_action` without the `mul_action` part. -/ @[ext] class distrib_smul (M A : Type*) [add_zero_class A] extends smul_zero_class M A := (smul_add : ∀ (a : M) (x y : A), a • (x + y) = a • x + a • y) section distrib_smul variables [add_zero_class A] [distrib_smul M A] theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_smul.smul_add _ _ _ /-- Pullback a distributive scalar multiplication along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_smul [add_zero_class B] [has_smul M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_smul M B := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, map_add, smul_add], .. hf.smul_zero_class f.to_zero_hom smul } /-- Pushforward a distributive scalar multiplication along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_smul [add_zero_class B] [has_smul M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_smul M B := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← map_add] }, .. f.to_zero_hom.smul_zero_class smul } /-- Push forward the multiplication of `R` on `M` along a compatible surjective map `f : R → S`. See also `function.surjective.distrib_mul_action_left`. -/ @[reducible] def function.surjective.distrib_smul_left {R S M : Type*} [add_zero_class M] [distrib_smul R M] [has_smul S M] (f : R → S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : distrib_smul S M := { smul := (•), smul_add := hf.forall.mpr $ λ c x y, by simp only [hsmul, smul_add], .. hf.smul_zero_class_left f hsmul } variable (A) /-- Compose a `distrib_smul` with a function, with scalar multiplication `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_smul.comp_fun (f : N → M) : distrib_smul N A := { smul := has_smul.comp.smul f, smul_add := λ x, smul_add (f x), .. smul_zero_class.comp_fun A f } /-- Each element of the scalars defines a additive monoid homomorphism. -/ @[simps] def distrib_smul.to_add_monoid_hom (x : M) : A →+ A := { to_fun := (•) x, map_add' := smul_add x, .. smul_zero_class.to_zero_hom A x } end distrib_smul /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ @[ext] class distrib_mul_action (M A : Type*) [monoid M] [add_monoid A] extends mul_action M A := (smul_zero : ∀ (a : M), a • (0 : A) = 0) (smul_add : ∀ (a : M) (x y : A), a • (x + y) = a • x + a • y) section variables [monoid M] [add_monoid A] [distrib_mul_action M A] @[priority 100] -- See note [lower instance priority] instance distrib_mul_action.to_distrib_smul : distrib_smul M A := { ..‹distrib_mul_action M A› } /-! Since Lean 3 does not have definitional eta for structures, we have to make sure that the definition of `distrib_mul_action.to_distrib_smul` was done correctly, and the two paths from `distrib_mul_action` to `has_smul` are indeed definitionally equal. -/ example : (distrib_mul_action.to_mul_action.to_has_smul : has_smul M A) = distrib_mul_action.to_distrib_smul.to_has_smul := rfl /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_mul_action [add_monoid B] [has_smul M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), .. hf.distrib_smul f smul, .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_mul_action [add_monoid B] [has_smul M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), .. hf.distrib_smul f smul, .. hf.mul_action f smul } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.mul_action_left` and `function.surjective.module_left`. -/ @[reducible] def function.surjective.distrib_mul_action_left {R S M : Type*} [monoid R] [add_monoid M] [distrib_mul_action R M] [monoid S] [has_smul S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : distrib_mul_action S M := { smul := (•), .. hf.distrib_smul_left f hsmul, .. hf.mul_action_left f hsmul } variable (A) /-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_mul_action.comp_hom [monoid N] (f : N →* M) : distrib_mul_action N A := { smul := has_smul.comp.smul f, .. distrib_smul.comp_fun A f, .. mul_action.comp_hom A f } /-- Each element of the monoid defines a additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_hom (x : M) : A →+ A := distrib_smul.to_add_monoid_hom A x variables (M) /-- Each element of the monoid defines an additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_End : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom A, map_one' := add_monoid_hom.ext $ one_smul M, map_mul' := λ x y, add_monoid_hom.ext $ mul_smul x y } instance add_monoid.nat_smul_comm_class : smul_comm_class ℕ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_nsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_monoid.nat_smul_comm_class' : smul_comm_class M ℕ A := smul_comm_class.symm _ _ _ end section variables [monoid M] [add_group A] [distrib_mul_action M A] instance add_group.int_smul_comm_class : smul_comm_class ℤ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_zsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_group.int_smul_comm_class' : smul_comm_class M ℤ A := smul_comm_class.symm _ _ _ @[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero_left $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end /-- Typeclass for multiplicative actions on multiplicative structures. This generalizes conjugation actions. -/ @[ext] class mul_distrib_mul_action (M : Type*) (A : Type*) [monoid M] [monoid A] extends mul_action M A := (smul_mul : ∀ (r : M) (x y : A), r • (x * y) = (r • x) * (r • y)) (smul_one : ∀ (r : M), r • (1 : A) = 1) export mul_distrib_mul_action (smul_one) section variables [monoid M] [monoid A] [mul_distrib_mul_action M A] theorem smul_mul' (a : M) (b₁ b₂ : A) : a • (b₁ * b₂) = (a • b₁) * (a • b₂) := mul_distrib_mul_action.smul_mul _ _ _ /-- Pullback a multiplicative distributive multiplicative action along an injective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.mul_distrib_mul_action [monoid B] [has_smul M B] (f : B →* A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, hf $ by simp only [smul, f.map_mul, smul_mul'], smul_one := λ c, hf $ by simp only [smul, f.map_one, smul_one], .. hf.mul_action f smul } /-- Pushforward a multiplicative distributive multiplicative action along a surjective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.mul_distrib_mul_action [monoid B] [has_smul M B] (f : A →* B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_mul', ← smul, ← f.map_mul] }, smul_one := λ c, by simp only [← f.map_one, ← smul, smul_one], .. hf.mul_action f smul } variable (A) /-- Compose a `mul_distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def mul_distrib_mul_action.comp_hom [monoid N] (f : N →* M) : mul_distrib_mul_action N A := { smul := has_smul.comp.smul f, smul_one := λ x, smul_one (f x), smul_mul := λ x, smul_mul' (f x), .. mul_action.comp_hom A f } /-- Scalar multiplication by `r` as a `monoid_hom`. -/ def mul_distrib_mul_action.to_monoid_hom (r : M) : A →* A := { to_fun := (•) r, map_one' := smul_one r, map_mul' := smul_mul' r } variable {A} @[simp] lemma mul_distrib_mul_action.to_monoid_hom_apply (r : M) (x : A) : mul_distrib_mul_action.to_monoid_hom A r x = r • x := rfl variables (M A) /-- Each element of the monoid defines a monoid homomorphism. -/ @[simps] def mul_distrib_mul_action.to_monoid_End : M →* monoid.End A := { to_fun := mul_distrib_mul_action.to_monoid_hom A, map_one' := monoid_hom.ext $ one_smul M, map_mul' := λ x y, monoid_hom.ext $ mul_smul x y } end section variables [monoid M] [group A] [mul_distrib_mul_action M A] @[simp] theorem smul_inv' (r : M) (x : A) : r • (x⁻¹) = (r • x)⁻¹ := (mul_distrib_mul_action.to_monoid_hom A r).map_inv x theorem smul_div' (r : M) (x y : A) : r • (x / y) = (r • x) / (r • y) := map_div (mul_distrib_mul_action.to_monoid_hom A r) x y end variable (α) /-- The monoid of endomorphisms. Note that this is generalized by `category_theory.End` to categories other than `Type u`. -/ protected def function.End := α → α instance : monoid (function.End α) := { one := id, mul := (∘), mul_assoc := λ f g h, rfl, mul_one := λ f, rfl, one_mul := λ f, rfl, } instance : inhabited (function.End α) := ⟨1⟩ variable {α} /-- The tautological action by `function.End α` on `α`. This is generalized to bundled endomorphisms by: * `equiv.perm.apply_mul_action` * `add_monoid.End.apply_distrib_mul_action` * `add_aut.apply_distrib_mul_action` * `mul_aut.apply_mul_distrib_mul_action` * `ring_hom.apply_distrib_mul_action` * `linear_equiv.apply_distrib_mul_action` * `linear_map.apply_module` * `ring_hom.apply_mul_semiring_action` * `alg_equiv.apply_mul_semiring_action` -/ instance function.End.apply_mul_action : mul_action (function.End α) α := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma function.End.smul_def (f : function.End α) (a : α) : f • a = f a := rfl /-- `function.End.apply_mul_action` is faithful. -/ instance function.End.apply_has_faithful_smul : has_faithful_smul (function.End α) α := ⟨λ x y, funext⟩ /-- The tautological action by `add_monoid.End α` on `α`. This generalizes `function.End.apply_mul_action`. -/ instance add_monoid.End.apply_distrib_mul_action [add_monoid α] : distrib_mul_action (add_monoid.End α) α := { smul := ($), smul_zero := add_monoid_hom.map_zero, smul_add := add_monoid_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma add_monoid.End.smul_def [add_monoid α] (f : add_monoid.End α) (a : α) : f • a = f a := rfl /-- `add_monoid.End.apply_distrib_mul_action` is faithful. -/ instance add_monoid.End.apply_has_faithful_smul [add_monoid α] : has_faithful_smul (add_monoid.End α) α := ⟨add_monoid_hom.ext⟩ /-- The monoid hom representing a monoid action. When `M` is a group, see `mul_action.to_perm_hom`. -/ def mul_action.to_End_hom [monoid M] [mul_action M α] : M →* function.End α := { to_fun := (•), map_one' := funext (one_smul M), map_mul' := λ x y, funext (mul_smul x y) } /-- The monoid action induced by a monoid hom to `function.End α` See note [reducible non-instances]. -/ @[reducible] def mul_action.of_End_hom [monoid M] (f : M →* function.End α) : mul_action M α := mul_action.comp_hom α f /-- The tautological additive action by `additive (function.End α)` on `α`. -/ instance add_action.function_End : add_action (additive (function.End α)) α := { vadd := ($), zero_vadd := λ _, rfl, add_vadd := λ _ _ _, rfl } /-- The additive monoid hom representing an additive monoid action. When `M` is a group, see `add_action.to_perm_hom`. -/ def add_action.to_End_hom [add_monoid M] [add_action M α] : M →+ additive (function.End α) := { to_fun := (+ᵥ), map_zero' := funext (zero_vadd M), map_add' := λ x y, funext (add_vadd x y) } /-- The additive action induced by a hom to `additive (function.End α)` See note [reducible non-instances]. -/ @[reducible] def add_action.of_End_hom [add_monoid M] (f : M →+ additive (function.End α)) : add_action M α := add_action.comp_hom α f /-! ### `additive`, `multiplicative` -/ section open additive multiplicative instance additive.has_vadd [has_smul α β] : has_vadd (additive α) β := ⟨λ a, (•) (to_mul a)⟩ instance multiplicative.has_smul [has_vadd α β] : has_smul (multiplicative α) β := ⟨λ a, (+ᵥ) (to_add a)⟩ @[simp] lemma to_mul_smul [has_smul α β] (a) (b : β) : (to_mul a : α) • b = a +ᵥ b := rfl @[simp] lemma of_mul_vadd [has_smul α β] (a : α) (b : β) : of_mul a +ᵥ b = a • b := rfl @[simp] lemma to_add_vadd [has_vadd α β] (a) (b : β) : (to_add a : α) +ᵥ b = a • b := rfl @[simp] lemma of_add_smul [has_vadd α β] (a : α) (b : β) : of_add a • b = a +ᵥ b := rfl instance additive.add_action [monoid α] [mul_action α β] : add_action (additive α) β := { zero_vadd := mul_action.one_smul, add_vadd := mul_action.mul_smul } instance multiplicative.mul_action [add_monoid α] [add_action α β] : mul_action (multiplicative α) β := { one_smul := add_action.zero_vadd, mul_smul := add_action.add_vadd } instance additive.add_action_is_pretransitive [monoid α] [mul_action α β] [mul_action.is_pretransitive α β] : add_action.is_pretransitive (additive α) β := ⟨@mul_action.exists_smul_eq α _ _ _⟩ instance multiplicative.add_action_is_pretransitive [add_monoid α] [add_action α β] [add_action.is_pretransitive α β] : mul_action.is_pretransitive (multiplicative α) β := ⟨@add_action.exists_vadd_eq α _ _ _⟩ instance additive.vadd_comm_class [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : vadd_comm_class (additive α) (additive β) γ := ⟨@smul_comm α β _ _ _ _⟩ instance multiplicative.smul_comm_class [has_vadd α γ] [has_vadd β γ] [vadd_comm_class α β γ] : smul_comm_class (multiplicative α) (multiplicative β) γ := ⟨@vadd_comm α β _ _ _ _⟩ end
5579f14fd7e9dd3164e4975b1af2cd9d033f8944
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/compactly_generated.lean
10087eaa9b51402e6ad312a8112072aa5757aba2
[ "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
22,965
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import tactic.tfae import order.atoms import order.order_iso_nat import order.sup_indep import order.zorn import data.finset.order import data.finite.default /-! # Compactness properties for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define three especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `complete_lattice.is_compact_element` * `complete_lattice.is_compactly_generated` ## Main results The main result is that the following four conditions are equivalent for a complete lattice: * `well_founded (>)` * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `∀ k, complete_lattice.is_compact_element k` This is demonstrated by means of the following four lemmas: * `complete_lattice.well_founded.is_Sup_finite_compact` * `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact` * `complete_lattice.is_sup_closed_compact.well_founded` * `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact` We also show well-founded lattices are compactly generated (`complete_lattice.compactly_generated_of_well_founded`). ## References - [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu] ## Tags complete lattice, well-founded, compact -/ variables {α : Type*} [complete_lattice α] namespace complete_lattice variables (α) /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b ∈ s, a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id /-- An element `k` of a complete lattice is said to be compact if any set with `Sup` above `k` has a finite subset with `Sup` above `k`. Such an element is also called "finite" or "S-compact". -/ def is_compact_element {α : Type*} [complete_lattice α] (k : α) := ∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id lemma {u} is_compact_element_iff {α : Type u} [complete_lattice α] (k : α) : complete_lattice.is_compact_element k ↔ ∀ (ι : Type u) (s : ι → α), k ≤ supr s → ∃ t : finset ι, k ≤ t.sup s := begin classical, split, { intros H ι s hs, obtain ⟨t, ht, ht'⟩ := H (set.range s) hs, have : ∀ x : t, ∃ i, s i = x := λ x, ht x.prop, choose f hf using this, refine ⟨finset.univ.image f, ht'.trans _⟩, { rw finset.sup_le_iff, intros b hb, rw ← (show s (f ⟨b, hb⟩) = id b, from hf _), exact finset.le_sup (finset.mem_image_of_mem f $ finset.mem_univ ⟨b, hb⟩) } }, { intros H s hs, obtain ⟨t, ht⟩ := H s coe (by { delta supr, rwa subtype.range_coe }), refine ⟨t.image coe, by simp, ht.trans _⟩, rw finset.sup_le_iff, exact λ x hx, @finset.le_sup _ _ _ _ _ id _ (finset.mem_image_of_mem coe hx) } end /-- An element `k` is compact if and only if any directed set with `Sup` above `k` already got above `k` at some point in the set. -/ theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) : is_compact_element k ↔ ∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x := begin classical, split, { intros hk s hne hdir hsup, obtain ⟨t, ht⟩ := hk s hsup, -- certainly every element of t is below something in s, since ↑t ⊆ s. have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, le_rfl⟩, obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s, exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, { intros hk s hsup, -- Consider the set of finite joins of elements of the (plain) set s. let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id }, -- S is directed, nonempty, and still has sup above k. have dir_US : directed_on (≤) S, { rintros x ⟨c, hc⟩ y ⟨d, hd⟩, use x ⊔ y, split, { use c ∪ d, split, { simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], }, { simp only [hc.right, hd.right, finset.sup_union], }, }, simp only [and_self, le_sup_left, le_sup_right], }, have sup_S : Sup s ≤ Sup S, { apply Sup_le_Sup, intros x hx, use {x}, simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton, set.singleton_subset_iff], }, have Sne : S.nonempty, { suffices : ⊥ ∈ S, from set.nonempty_of_mem this, use ∅, simp only [set.empty_subset, finset.coe_empty, finset.sup_empty, eq_self_iff_true, and_self], }, -- Now apply the defn of compact and finish. obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S), obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS, use t, exact ⟨htS, by rwa ←htsup⟩, }, end lemma is_compact_element.exists_finset_of_le_supr {k : α} (hk : is_compact_element k) {ι : Type*} (f : ι → α) (h : k ≤ ⨆ i, f i) : ∃ s : finset ι, k ≤ ⨆ i ∈ s, f i := begin classical, let g : finset ι → α := λ s, ⨆ i ∈ s, f i, have h1 : directed_on (≤) (set.range g), { rintros - ⟨s, rfl⟩ - ⟨t, rfl⟩, exact ⟨g (s ∪ t), ⟨s ∪ t, rfl⟩, supr_le_supr_of_subset (finset.subset_union_left s t), supr_le_supr_of_subset (finset.subset_union_right s t)⟩ }, have h2 : k ≤ Sup (set.range g), { exact h.trans (supr_le (λ i, le_Sup_of_le ⟨{i}, rfl⟩ (le_supr_of_le i (le_supr_of_le (finset.mem_singleton_self i) le_rfl)))) }, obtain ⟨-, ⟨s, rfl⟩, hs⟩ := (is_compact_element_iff_le_of_directed_Sup_le α k).mp hk (set.range g) (set.range_nonempty g) h1 h2, exact ⟨s, hs⟩, end /-- A compact element `k` has the property that any directed set lying strictly below `k` has its Sup strictly below `k`. -/ lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α} (hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s) (hbelow : ∀ x ∈ s, x < k) : Sup s < k := begin rw is_compact_element_iff_le_of_directed_Sup_le at hk, by_contradiction, have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le), replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩, obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le, obtain hxk := hbelow x hxs, exact hxk.ne (hxk.le.antisymm hkx), end lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α} (s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) := begin classical, rw is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, change f with id ∘ f, rw ←finset.sup_finset_image, apply finset.sup_le_of_le_directed d hemp hdir, rintros x hx, obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx, specialize h p hps, rw is_compact_element_iff_le_of_directed_Sup_le at h, specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup), simpa only [exists_prop], end lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_id_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin refine rel_embedding.well_founded_iff_no_descending_seq.mpr ⟨λ a, _⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x ⟨m, hm⟩ y ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply rel_hom_class.map_sup a, }, end lemma is_Sup_finite_compact_iff_all_elements_compact : is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) := begin refine ⟨λ h k s hs, _, λ h s, _⟩, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h s, use [t, hts], rwa ←htsup, }, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl), have : Sup s = t.sup id, { suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption }, simp only [id.def, finset.sup_le_iff], intros x hx, exact le_Sup (hts hx) }, use [t, hts, this] }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α, ∀ k : α, is_compact_element k] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ _root_.well_founded.is_sup_closed_compact variables {α} lemma well_founded.finite_of_set_independent (h : well_founded ((>) : α → α → Prop)) {s : set α} (hs : set_independent s) : s.finite := begin classical, refine set.not_infinite.mp (λ contra, _), obtain ⟨t, ht₁, ht₂⟩ := well_founded.is_Sup_finite_compact α h s, replace contra : ∃ (x : α), x ∈ s ∧ x ≠ ⊥ ∧ x ∉ t, { have : (s \ (insert ⊥ t : finset α)).infinite := contra.diff (finset.finite_to_set _), obtain ⟨x, hx₁, hx₂⟩ := this.nonempty, exact ⟨x, hx₁, by simpa [not_or_distrib] using hx₂⟩, }, obtain ⟨x, hx₀, hx₁, hx₂⟩ := contra, replace hs : x ⊓ Sup s = ⊥, { have := hs.mono (by simp [ht₁, hx₀, -set.union_singleton] : ↑t ∪ {x} ≤ s) (by simp : x ∈ _), simpa [disjoint, hx₂, ← t.sup_id_eq_Sup, ← ht₂] using this, }, apply hx₁, rw [← hs, eq_comm, inf_eq_left], exact le_Sup hx₀, end lemma well_founded.finite_of_independent (hwf : well_founded ((>) : α → α → Prop)) {ι : Type*} {t : ι → α} (ht : independent t) (h_ne_bot : ∀ i, t i ≠ ⊥) : finite ι := begin haveI := (well_founded.finite_of_set_independent hwf ht.set_independent_range).to_subtype, exact finite.of_injective_finite_range (ht.injective h_ne_bot), end end complete_lattice /-- A complete lattice is said to be compactly generated if any element is the `Sup` of compact elements. -/ class is_compactly_generated (α : Type*) [complete_lattice α] : Prop := (exists_Sup_eq : ∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x) section variables {α} [is_compactly_generated α] {a b : α} {s : set α} @[simp] lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b := begin rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩, exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)), end @[simp] theorem Sup_compact_eq_top : Sup {a : α | complete_lattice.is_compact_element a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_compact_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ /-- This property is sometimes referred to as `α` being upper continuous. -/ theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s): a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b := le_antisymm (begin rw le_iff_compact_le_imp, by_cases hs : s.nonempty, { intros c hc hcinf, rw le_inf_iff at hcinf, rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc, rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩, exact (le_inf hcinf.1 cd).trans (le_supr₂ d ds) }, { rw set.not_nonempty_iff_eq_empty at hs, simp [hs] } end) supr_inf_le_inf_Sup /-- This property is equivalent to `α` being upper continuous. -/ theorem inf_Sup_eq_supr_inf_sup_finset : a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) := le_antisymm (begin rw le_iff_compact_le_imp, intros c hc hcinf, rw le_inf_iff at hcinf, rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩, exact (le_inf hcinf.1 ht2).trans (le_supr₂ t ht1), end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_id_eq_Sup t).symm ▸ (Sup_le_Sup h))) theorem complete_lattice.set_independent_iff_finite {s : set α} : complete_lattice.set_independent s ↔ ∀ t : finset α, ↑t ⊆ s → complete_lattice.set_independent (↑t : set α) := ⟨λ hs t ht, hs.mono ht, λ h a ha, begin rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot], intro t, rw [supr_eq_bot, finset.sup_id_eq_Sup], intro ht, classical, have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot, { rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h', exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) }, { rw [finset.coe_insert, set.insert_subset], exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ } end⟩ lemma complete_lattice.set_independent_Union_of_directed {η : Type*} {s : η → set α} (hs : directed (⊆) s) (h : ∀ i, complete_lattice.set_independent (s i)) : complete_lattice.set_independent (⋃ i, s i) := begin by_cases hη : nonempty η, { resetI, rw complete_lattice.set_independent_iff_finite, intros t ht, obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht, obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset, exact (h i).mono (set.subset.trans hI $ set.Union₂_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { rintros a ⟨_, ⟨i, _⟩, _⟩, exfalso, exact hη ⟨i⟩, }, end lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, complete_lattice.set_independent a) : complete_lattice.set_independent (⋃₀ s) := by rw set.sUnion_eq_Union; exact complete_lattice.set_independent_Union_of_directed hs.directed_coe (by simpa using h) end namespace complete_lattice lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) : is_compactly_generated α := begin rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h, -- x is the join of the set of compact elements {x} exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩, end /-- A compact element `k` has the property that any `b < k` lies below a "maximal element below `k`", which is to say `[⊥, k]` is coatomic. -/ theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) : is_coatomic (set.Iic k) := ⟨λ ⟨b, hbk⟩, begin by_cases htriv : b = k, { left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], }, right, obtain ⟨a, a₀, ba, h⟩ := zorn_nonempty_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv), { refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩, cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le, exact lt_irrefl _ hck, }, { intros S SC cC I IS, by_cases hS : S.nonempty, { exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, }, exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, }, end⟩ lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α := (@order_iso.Iic_top α _ _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h) end complete_lattice section variables [is_modular_lattice α] [is_compactly_generated α] @[priority 100] instance is_atomic_of_complemented_lattice [complemented_lattice α] : is_atomic α := ⟨λ b, begin by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥}, { left, rw [← Sup_compact_le_eq b, Sup_eq_bot], exact h }, { rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩, right, have hc' := complete_lattice.Iic_coatomic_of_compact_element hc, rw ← is_atomic_iff_is_coatomic at hc', haveI := hc', obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c), { exfalso, apply hcbot, simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con, exact con }, rw [← subtype.coe_le_coe, subtype.coe_mk] at hac, exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ }, end⟩ /-- See Lemma 5.1, Călugăreanu -/ @[priority 100] instance is_atomistic_of_complemented_lattice [complemented_lattice α] : is_atomistic α := ⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin symmetry, have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right), apply (lt_or_eq_of_le hle).resolve_left (λ con, _), obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b), obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c, { exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) }, { apply ha.1, rw eq_bot_iff, apply le_trans (le_inf _ hac) hc.1, rw [← subtype.coe_le_coe, subtype.coe_mk], exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ } end, λ _, and.left⟩⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem complemented_lattice_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : complemented_lattice α := ⟨λ b, begin obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn_subset {s : set α | complete_lattice.set_independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _, { refine ⟨Sup s, le_of_eq b_inf_Sup_s, h.symm.trans_le $ Sup_le_iff.2 $ λ a ha, _⟩, rw ← inf_eq_left, refine (ha.le_iff.mp inf_le_left).resolve_left (λ con, ha.1 _), rw [eq_bot_iff, ← con], refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right), rw ← disjoint_iff at *, have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right, rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _), { exact set.mem_union_right _ (set.mem_singleton _) }, { rw [set.mem_union, set.mem_singleton_iff] at hx, by_cases xa : x = a, { simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) }, { have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a}, { simp only [set.union_singleton], rw set.insert_diff_of_not_mem, rw set.mem_singleton_iff, exact ne.symm xa }, rw [h, Sup_union, Sup_singleton], apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left (a_dis_Sup_s.mono_right _).symm, rw [← Sup_insert, set.insert_diff_singleton, set.insert_eq_of_mem (hx.resolve_right xa)] } }, { rw [Sup_union, Sup_singleton, ← disjoint_iff], exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm }, { rw [set.mem_union, set.mem_singleton_iff] at hx, cases hx, { exact s_atoms x hx }, { rw hx, exact ha } } }, { intros c hc1 hc2, refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on (λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩, { rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot], { intro i, rw supr_eq_bot, intro hi, obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi, exact (hc1 xc).2.1 }, { rw directed_on_image, refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } }, { rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩, exact (hc1 sc).2.2 a as } } end⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem complemented_lattice_of_is_atomistic [is_atomistic α] : complemented_lattice α := complemented_lattice_of_Sup_atoms_eq_top Sup_atoms_eq_top theorem complemented_lattice_iff_is_atomistic : complemented_lattice α ↔ is_atomistic α := begin split; introsI, { exact is_atomistic_of_complemented_lattice }, { exact complemented_lattice_of_is_atomistic } end end
be5f3f1dcb9d05ccdb4c316f36e32b9d70e0ced1
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/multiset.lean
be51f573db71a76f573bdde3f06a56bc99988ca3
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
126,127
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `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.perm.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 /- 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 /- 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 ((perm_cons a).2 p)) notation a :: b := cons a b 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, eq_singleton_of_perm $ (perm_app_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 [perm_cons] @[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` failes 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, list.rec_heq_of_perm h (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 $ mem_of_perm e) 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 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_of_forall_not_mem H; refl 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 /- 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 /- multiset order -/ /-- `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₂, subset_of_subperm 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, subperm_of_sublist $ nil_sublist l 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], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ 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 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- 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 (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[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 -/ @[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⟩ /- add -/ /-- 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 $ perm_app p₁ 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_app_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_app_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_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 α } @[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] 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 @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append 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⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, ..multiset.ordered_cancel_comm_monoid } /- 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).symm).symm, 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.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ 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 (erase_perm_erase a p)) @[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] 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] 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] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_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 @[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 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, subperm_of_sublist (erase_sublist a l) @[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, subperm_of_sublist (erase_sublist_erase _ h) 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)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- 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 (perm_map f p)) @[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 @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[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) := by refine_struct {..}; simp @[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 _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj 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 _ _ _ @[simp] 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, subperm_of_sublist $ map_sublist_map f h @[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⟩ /- 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, foldl_eq_of_perm H p 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, foldr_eq_of_perm H p 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` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] 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 multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] 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 α → α) := by refine_struct {..}; simp @[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 multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] 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 multiset.sum_map_sum_map] 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]) lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) : (s.map f).prod = f s.prod := multiset.induction_on s (by simp [is_monoid_hom.map_one f]) (by simp [is_monoid_hom.map_mul f] {contextual := tt}) lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) : (s.map f).sum = f s.sum := multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f]) (by simp [is_add_monoid_hom.map_add f] {contextual := tt}) attribute [to_additive multiset.sum_hom] multiset.prod_hom /- 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) /- 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, -map_const, 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 {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 multiset.sum_bind] 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 -/ /-- 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 @[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 -/ 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 @[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 ((mem_of_perm pp).1 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 $ perm_pmap f pp @[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 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 $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ 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₂; 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]) /- inter -/ /-- `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 $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ 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₂, subperm_of_sublist $ bag_inter_sublist_left _ _ 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.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] 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 /- 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 (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[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 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, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[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 filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h 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 h⟩ @[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 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] /- filter_map -/ /-- `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 $perm_filter_map f h) @[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 (p : α → Prop) [decidable_pred p] : 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 (p : α → Prop) [decidable_pred p] (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, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- diagonal -/ theorem revzip_powerset_aux {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end def diagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem diagonal_coe (l : list α) : @diagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem diagonal_coe' (l : list α) : @diagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' @[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} : (s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t := quotient.induction_on t $ λ l, begin simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩ end @[simp] theorem diagonal_map_fst (s : multiset α) : (diagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_map_snd (s : multiset α) : (diagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl @[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) = map (prod.map id (cons a)) (diagonal s) + map (prod.map (cons a) id) (diagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_diagonal (s : multiset α) : card (diagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← diagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((diagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[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 @[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 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 α → ℕ) := by refine_struct {..}; simp theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[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_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ 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 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] end /- count -/ 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] 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_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_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] 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') 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 @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[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] 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_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) 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 {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 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 @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 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 [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ 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`. -/ 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) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff 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 (assume a b, 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 injective_map {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 -/ /-- `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₂ @[simp] 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] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] 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 := disjoint_comm.trans $ by simp [disjoint_append_left] @[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 := disjoint_comm.trans $ by simp [disjoint_cons_left] 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) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `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⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- 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 $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_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 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 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, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ @[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₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) 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 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 /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton @[simp] theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := congr_arg coe $ list.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := congr_arg coe $ list.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := congr_arg coe $ list.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_ge n m l end Ico end multiset
1691fdc0afd85c1c31f0ddca739add6993d869dc
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170323-equality-for-inductive-types.lean
885d1dfede6fcfd2cd54d8771986ee20f1dc2fcf
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
1,915
lean
open tactic open smt_tactic meta def smt_eblast : tactic unit := using_smt $ intros >> try dsimp >> try simp >> try eblast notation `♮` := by abstract { smt_eblast } universe variables u v structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) (identity : Π X : Obj, Hom X X) (compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z) (left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f) universe variables u1 v1 u2 v2 u3 v3 structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C^.Obj → D^.Obj) (onMorphisms : Π { X Y : C^.Obj }, C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y)) (identities : ∀ (X : C^.Obj), onMorphisms (C^.identity X) = D^.identity (onObjects X)) (functoriality : ∀ { X Y Z : C^.Obj } (f : C^.Hom X Y) (g : C^.Hom Y Z), onMorphisms (C^.compose f g) = D^.compose (onMorphisms f) (onMorphisms g)) attribute [simp,ematch] Functor.identities attribute [simp,ematch] Functor.functoriality @[reducible] definition IdentityFunctor ( C: Category.{u1 v1} ) : Functor C C := { onObjects := id, onMorphisms := λ _ _ f, f, identities := ♮, functoriality := ♮ } @[reducible] definition FunctorComposition { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } ( F : Functor C D ) ( G : Functor D E ) : Functor C E := { onObjects := λ X, G^.onObjects (F^.onObjects X), onMorphisms := λ _ _ f, G^.onMorphisms (F^.onMorphisms f), identities := ♮, functoriality := ♮ } @[reducible] definition CategoryOfCategoriesAndFunctors : Category := { Obj := Category.{u1 v1}, Hom := λ C D, Functor C D, identity := λ C, IdentityFunctor C, compose := λ _ _ _ F G, FunctorComposition F G, left_identity := begin intros, dsimp, trivial end }
dd924330424b56bc5e11be285107964c36548183
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Range.lean
13f71eb3ed56da54aba1c18cd3f8a55659640ac5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
3,334
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.Meta namespace Std -- We put `Range` in `Init` because we want the notation `[i:j]` without importing `Std` -- We don't put `Range` in the top-level namespace to avoid collisions with user defined types structure Range where start : Nat := 0 stop : Nat step : Nat := 1 instance : Membership Nat Range where mem i r := r.start ≤ i ∧ i < r.stop namespace Range universe u v @[inline] protected def forIn {β : Type u} {m : Type u → Type v} [Monad m] (range : Range) (init : β) (f : Nat → β → m (ForInStep β)) : m β := -- pass `stop` and `step` separately so the `range` object can be eliminated through inlining let rec @[specialize] loop (fuel i stop step : Nat) (b : β) : m β := do if i ≥ stop then return b else match fuel with | 0 => pure b | fuel+1 => match (← f i b) with | ForInStep.done b => pure b | ForInStep.yield b => loop fuel (i + step) stop step b loop range.stop range.start range.stop range.step init instance : ForIn m Range Nat where forIn := Range.forIn @[inline] protected def forIn' {β : Type u} {m : Type u → Type v} [Monad m] (range : Range) (init : β) (f : (i : Nat) → i ∈ range → β → m (ForInStep β)) : m β := let rec @[specialize] loop (start stop step : Nat) (f : (i : Nat) → start ≤ i ∧ i < stop → β → m (ForInStep β)) (fuel i : Nat) (hl : start ≤ i) (b : β) : m β := do if hu : i < stop then match fuel with | 0 => pure b | fuel+1 => match (← f i ⟨hl, hu⟩ b) with | ForInStep.done b => pure b | ForInStep.yield b => loop start stop step f fuel (i + step) (Nat.le_trans hl (Nat.le_add_right ..)) b else return b loop range.start range.stop range.step f range.stop range.start (Nat.le_refl ..) init instance : ForIn' m Range Nat inferInstance where forIn' := Range.forIn' @[inline] protected def forM {m : Type u → Type v} [Monad m] (range : Range) (f : Nat → m PUnit) : m PUnit := let rec @[specialize] loop (fuel i stop step : Nat) : m PUnit := do if i ≥ stop then pure ⟨⟩ else match fuel with | 0 => pure ⟨⟩ | fuel+1 => f i; loop fuel (i + step) stop step loop range.stop range.start range.stop range.step instance : ForM m Range Nat where forM := Range.forM syntax:max "[" withoutPosition(":" term) "]" : term syntax:max "[" withoutPosition(term ":" term) "]" : term syntax:max "[" withoutPosition(":" term ":" term) "]" : term syntax:max "[" withoutPosition(term ":" term ":" term) "]" : term macro_rules | `([ : $stop]) => `({ stop := $stop : Range }) | `([ $start : $stop ]) => `({ start := $start, stop := $stop : Range }) | `([ $start : $stop : $step ]) => `({ start := $start, stop := $stop, step := $step : Range }) | `([ : $stop : $step ]) => `({ stop := $stop, step := $step : Range }) end Range end Std theorem Membership.mem.upper {i : Nat} {r : Std.Range} (h : i ∈ r) : i < r.stop := by simp [Membership.mem] at h exact h.2 theorem Membership.mem.lower {i : Nat} {r : Std.Range} (h : i ∈ r) : r.start ≤ i := by simp [Membership.mem] at h exact h.1
d6697509965d12c6ae0ad7cffef990f177475c02
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/quandle_auto.lean
82ef10efdb7c995b1eb028ec3f3cfb9d16f86860
[]
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
23,500
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.zmod.basic import Mathlib.data.equiv.mul_add import Mathlib.tactic.group import Mathlib.PostPort universes u l u_1 u_2 u_3 namespace Mathlib /-! # Racks and Quandles This file defines racks and quandles, algebraic structures for sets that bijectively act on themselves with a self-distributivity property. If `R` is a rack and `act : R → (R ≃ R)` is the self-action, then the self-distributivity is, equivalently, that ``` act (act x y) = act x * act y * (act x)⁻¹ ``` where multiplication is composition in `R ≃ R` as a group. Quandles are racks such that `act x x = x` for all `x`. One example of a quandle (not yet in mathlib) is the action of a Lie algebra on itself, defined by `act x y = Ad (exp x) y`. Quandles and racks were independently developed by multiple mathematicians. David Joyce introduced quandles in his thesis [Joyce1982] to define an algebraic invariant of knot and link complements that is analogous to the fundamental group of the exterior, and he showed that the quandle associated to an oriented knot is invariant up to orientation-reversed mirror image. Racks were used by Fenn and Rourke for framed codimension-2 knots and links.[FennRourke1992] The name "rack" came from wordplay by Conway and Wraith for the "wrack and ruin" of forgetting everything but the conjugation operation for a group. ## Main definitions * `shelf` is a type with a self-distributive action * `rack` is a shelf whose action for each element is invertible * `quandle` is a rack whose action for an element fixes that element * `quandle.conj` defines a quandle of a group acting on itself by conjugation. * `shelf_hom` is homomorphisms of shelves, racks, and quandles. * `rack.envel_group` gives the universal group the rack maps to as a conjugation quandle. * `rack.opp` gives the rack with the action replaced by its inverse. ## Main statements * `rack.envel_group` is left adjoint to `quandle.conj` (`to_envel_group.map`). The universality statements are `to_envel_group.univ` and `to_envel_group.univ_uniq`. ## Notation The following notation is localized in `quandles`: * `x ◃ y` is `shelf.act x y` * `x ◃⁻¹ y` is `rack.inv_act x y` * `S →◃ S'` is `shelf_hom S S'` Use `open_locale quandles` to use these. ## Todo * If g is the Lie algebra of a Lie group G, then (x ◃ y) = Ad (exp x) x forms a quandle * If X is a symmetric space, then each point has a corresponding involution that acts on X, forming a quandle. * Alexander quandle with `a ◃ b = t * b + (1 - t) * b`, with `a` and `b` elements of a module over Z[t,t⁻¹]. * If G is a group, H a subgroup, and z in H, then there is a quandle `(G/H;z)` defined by `yH ◃ xH = yzy⁻¹xH`. Every homogeneous quandle (i.e., a quandle Q whose automorphism group acts transitively on Q as a set) is isomorphic to such a quandle. There is a generalization to this arbitrary quandles in [Joyce's paper (Theorem 7.2)][Joyce1982]. ## Tags rack, quandle -/ /-- A *shelf* is a structure with a self-distributive binary operation. The binary operation is regarded as a left action of the type on itself. -/ class shelf (α : Type u) where act : α → α → α self_distrib : ∀ {x y z : α}, act x (act y z) = act (act x y) (act x z) /-- The type of homomorphisms between shelves. This is also the notion of rack and quandle homomorphisms. -/ structure shelf_hom (S₁ : Type u_1) (S₂ : Type u_2) [shelf S₁] [shelf S₂] where to_fun : S₁ → S₂ map_act' : ∀ {x y : S₁}, to_fun (shelf.act x y) = shelf.act (to_fun x) (to_fun y) /-- A *rack* is an automorphic set (a set with an action on itself by bijections) that is self-distributive. It is a shelf such that each element's action is invertible. The notations `x ◃ y` and `x ◃⁻¹ y` denote the action and the inverse action, respectively, and they are right associative. -/ class rack (α : Type u) extends shelf α where inv_act : α → α → α left_inv : ∀ (x : α), function.left_inverse (inv_act x) (shelf.act x) right_inv : ∀ (x : α), function.right_inverse (inv_act x) (shelf.act x) namespace rack theorem self_distrib {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : shelf.act x (shelf.act y z) = shelf.act (shelf.act x y) (shelf.act x z) := shelf.self_distrib /-- A rack acts on itself by equivalences. -/ def act {R : Type u_1} [rack R] (x : R) : R ≃ R := equiv.mk (shelf.act x) (inv_act x) (left_inv x) (right_inv x) @[simp] theorem act_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (act x) y = shelf.act x y := rfl @[simp] theorem act_symm_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (equiv.symm (act x)) y = inv_act x y := rfl @[simp] theorem inv_act_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (act x⁻¹) y = inv_act x y := rfl @[simp] theorem inv_act_act_eq {R : Type u_1} [rack R] (x : R) (y : R) : inv_act x (shelf.act x y) = y := left_inv x y @[simp] theorem act_inv_act_eq {R : Type u_1} [rack R] (x : R) (y : R) : shelf.act x (inv_act x y) = y := right_inv x y theorem left_cancel {R : Type u_1} [rack R] (x : R) {y : R} {y' : R} : shelf.act x y = shelf.act x y' ↔ y = y' := { mp := equiv.injective (act x), mpr := fun (ᾰ : y = y') => Eq._oldrec (Eq.refl (shelf.act x y)) ᾰ } theorem left_cancel_inv {R : Type u_1} [rack R] (x : R) {y : R} {y' : R} : inv_act x y = inv_act x y' ↔ y = y' := { mp := equiv.injective (equiv.symm (act x)), mpr := fun (ᾰ : y = y') => Eq._oldrec (Eq.refl (inv_act x y)) ᾰ } theorem self_distrib_inv {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : inv_act x (inv_act y z) = inv_act (inv_act x y) (inv_act x z) := sorry /-- The *adjoint action* of a rack on itself is `op'`, and the adjoint action of `x ◃ y` is the conjugate of the action of `y` by the action of `x`. It is another way to understand the self-distributivity axiom. This is used in the natural rack homomorphism `to_conj` from `R` to `conj (R ≃ R)` defined by `op'`. -/ theorem ad_conj {R : Type u_1} [rack R] (x : R) (y : R) : act (shelf.act x y) = act x * act y * (act x⁻¹) := sorry /-- The opposite rack, swapping the roles of `◃` and `◃⁻¹`. -/ protected instance opposite_rack {R : Type u_1} [rack R] : rack (Rᵒᵖ) := mk (fun (x y : Rᵒᵖ) => opposite.op (shelf.act (opposite.unop x) (opposite.unop y))) sorry sorry @[simp] theorem op_act_op_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (opposite.op x) (opposite.op y) = opposite.op (inv_act x y) := rfl @[simp] theorem op_inv_act_op_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (opposite.op x) (opposite.op y) = opposite.op (shelf.act x y) := rfl @[simp] theorem self_act_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (shelf.act x x) y = shelf.act x y := sorry @[simp] theorem self_inv_act_inv_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (inv_act x x) y = inv_act x y := sorry @[simp] theorem self_act_inv_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (shelf.act x x) y = inv_act x y := sorry @[simp] theorem self_inv_act_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (inv_act x x) y = shelf.act x y := sorry theorem self_act_eq_iff_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act x x = shelf.act y y ↔ x = y := sorry theorem self_inv_act_eq_iff_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act x x = inv_act y y ↔ x = y := sorry /-- The map `x ↦ x ◃ x` is a bijection. (This has applications for the regular isotopy version of the Reidemeister I move for knot diagrams.) -/ def self_apply_equiv (R : Type u_1) [rack R] : R ≃ R := equiv.mk (fun (x : R) => shelf.act x x) (fun (x : R) => inv_act x x) sorry sorry /-- An involutory rack is one for which `rack.op R x` is an involution for every x. -/ def is_involutory (R : Type u_1) [rack R] := ∀ (x : R), function.involutive (shelf.act x) theorem involutory_inv_act_eq_act {R : Type u_1} [rack R] (h : is_involutory R) (x : R) (y : R) : inv_act x y = shelf.act x y := eq.mpr (id (Eq._oldrec (Eq.refl (inv_act x y = shelf.act x y)) (Eq.symm (propext (left_cancel x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (shelf.act x (inv_act x y) = shelf.act x (shelf.act x y))) (right_inv x y))) (Eq.symm (function.involutive.left_inverse (h x) y))) /-- An abelian rack is one for which the mediality axiom holds. -/ def is_abelian (R : Type u_1) [rack R] := ∀ (x y z w : R), shelf.act (shelf.act x y) (shelf.act z w) = shelf.act (shelf.act x z) (shelf.act y w) /-- Associative racks are uninteresting. -/ theorem assoc_iff_id {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : shelf.act x (shelf.act y z) = shelf.act (shelf.act x y) z ↔ shelf.act x z = z := sorry end rack namespace shelf_hom protected instance has_coe_to_fun {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] : has_coe_to_fun (shelf_hom S₁ S₂) := has_coe_to_fun.mk (fun (x : shelf_hom S₁ S₂) => S₁ → S₂) to_fun @[simp] theorem to_fun_eq_coe {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] (f : shelf_hom S₁ S₂) : to_fun f = ⇑f := rfl @[simp] theorem map_act {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] (f : shelf_hom S₁ S₂) {x : S₁} {y : S₁} : coe_fn f (shelf.act x y) = shelf.act (coe_fn f x) (coe_fn f y) := map_act' f /-- The identity homomorphism -/ def id (S : Type u_1) [shelf S] : shelf_hom S S := mk id sorry protected instance inhabited (S : Type u_1) [shelf S] : Inhabited (shelf_hom S S) := { default := id S } /-- The composition of shelf homomorphisms -/ def comp {S₁ : Type u_1} {S₂ : Type u_2} {S₃ : Type u_3} [shelf S₁] [shelf S₂] [shelf S₃] (g : shelf_hom S₂ S₃) (f : shelf_hom S₁ S₂) : shelf_hom S₁ S₃ := mk (to_fun g ∘ to_fun f) sorry @[simp] theorem comp_apply {S₁ : Type u_1} {S₂ : Type u_2} {S₃ : Type u_3} [shelf S₁] [shelf S₂] [shelf S₃] (g : shelf_hom S₂ S₃) (f : shelf_hom S₁ S₂) (x : S₁) : coe_fn (comp g f) x = coe_fn g (coe_fn f x) := rfl end shelf_hom /-- A quandle is a rack such that each automorphism fixes its corresponding element. -/ class quandle (α : Type u_1) extends rack α where fix : ∀ {x : α}, shelf.act x x = x namespace quandle @[simp] theorem fix_inv {Q : Type u_1} [quandle Q] {x : Q} : rack.inv_act x x = x := sorry protected instance opposite_quandle {Q : Type u_1} [quandle Q] : quandle (Qᵒᵖ) := mk sorry /-- The conjugation quandle of a group. Each element of the group acts by the corresponding inner automorphism. -/ def conj (G : Type u_1) := G protected instance conj.quandle (G : Type u_1) [group G] : quandle (conj G) := mk sorry @[simp] theorem conj_act_eq_conj {G : Type u_1} [group G] (x : conj G) (y : conj G) : shelf.act x y = x * y * (x⁻¹) := rfl theorem conj_swap {G : Type u_1} [group G] (x : conj G) (y : conj G) : shelf.act x y = y ↔ shelf.act y x = x := sorry /-- `conj` is functorial -/ def conj.map {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G →* H) : shelf_hom (conj G) (conj H) := shelf_hom.mk ⇑f sorry protected instance shelf_hom.has_lift {G : Type u_1} {H : Type u_2} [group G] [group H] : has_lift (G →* H) (shelf_hom (conj G) (conj H)) := has_lift.mk conj.map /-- The dihedral quandle. This is the conjugation quandle of the dihedral group restrict to flips. Used for Fox n-colorings of knots. -/ def dihedral (n : ℕ) := zmod n /-- The operation for the dihedral quandle. It does not need to be an equivalence because it is an involution (see `dihedral_act.inv`). -/ def dihedral_act (n : ℕ) (a : zmod n) : zmod n → zmod n := fun (b : zmod n) => bit0 1 * a - b theorem dihedral_act.inv (n : ℕ) (a : zmod n) : function.involutive (dihedral_act n a) := sorry protected instance dihedral.quandle (n : ℕ) : quandle (dihedral n) := mk sorry end quandle namespace rack /-- This is the natural rack homomorphism to the conjugation quandle of the group `R ≃ R` that acts on the rack. -/ def to_conj (R : Type u_1) [rack R] : shelf_hom R (quandle.conj (R ≃ R)) := shelf_hom.mk act ad_conj /-! ### Universal enveloping group of a rack The universal enveloping group `envel_group R` of a rack `R` is the universal group such that every rack homomorphism `R →◃ conj G` is induced by a unique group homomorphism `envel_group R →* G`. For quandles, Joyce called this group `AdConj R`. The `envel_group` functor is left adjoint to the `conj` forgetful functor, and the way we construct the enveloping group is via a technique that should work for left adjoints of forgetful functors in general. It involves thinking a little about 2-categories, but the payoff is that the map `envel_group R →* G` has a nice description. Let's think of a group as being a one-object category. The first step is to define `pre_envel_group`, which gives formal expressions for all the 1-morphisms and includes the unit element, elements of `R`, multiplication, and inverses. To introduce relations, the second step is to define `pre_envel_group_rel'`, which gives formal expressions for all 2-morphisms between the 1-morphisms. The 2-morphisms include associativity, multiplication by the unit, multiplication by inverses, compatibility with multiplication and inverses (`congr_mul` and `congr_inv`), the axioms for an equivalence relation, and, importantly, the relationship between conjugation and the rack action (see `rack.ad_conj`). None of this forms a 2-category yet, for example due to lack of associativity of `trans`. The `pre_envel_group_rel` relation is a `Prop`-valued version of `pre_envel_group_rel'`, and making it `Prop`-valued essentially introduces enough 3-isomorphisms so that every pair of compatible 2-morphisms is isomorphic. Now, while composition in `pre_envel_group` does not strictly satisfy the category axioms, `pre_envel_group` and `pre_envel_group_rel'` do form a weak 2-category. Since we just want a 1-category, the last step is to quotient `pre_envel_group` by `pre_envel_group_rel'`, and the result is the group `envel_group`. For a homomorphism `f : R →◃ conj G`, how does `envel_group.map f : envel_group R →* G` work? Let's think of `G` as being a 2-category with one object, a 1-morphism per element of `G`, and a single 2-morphism called `eq.refl` for each 1-morphism. We define the map using a "higher `quotient.lift`" -- not only do we evaluate elements of `pre_envel_group` as expressions in `G` (this is `to_envel_group.map_aux`), but we evaluate elements of `pre_envel_group'` as expressions of 2-morphisms of `G` (this is `to_envel_group.map_aux.well_def`). That is to say, `to_envel_group.map_aux.well_def` recursively evaluates formal expressions of 2-morphisms as equality proofs in `G`. Now that all morphisms are accounted for, the map descends to a homomorphism `envel_group R →* G`. Note: `Type`-valued relations are not common. The fact it is `Type`-valued is what makes `to_envel_group.map_aux.well_def` have well-founded recursion. -/ /-- Free generators of the enveloping group. -/ inductive pre_envel_group (R : Type u) where | unit : pre_envel_group R | incl : R → pre_envel_group R | mul : pre_envel_group R → pre_envel_group R → pre_envel_group R | inv : pre_envel_group R → pre_envel_group R protected instance pre_envel_group.inhabited (R : Type u) : Inhabited (pre_envel_group R) := { default := pre_envel_group.unit } /-- Relations for the enveloping group. This is a type-valued relation because `to_envel_group.map_aux.well_def` inducts on it to show `to_envel_group.map` is well-defined. The relation `pre_envel_group_rel` is the `Prop`-valued version, which is used to define `envel_group` itself. -/ inductive pre_envel_group_rel' (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Type u where | refl : {a : pre_envel_group R} → pre_envel_group_rel' R a a | symm : {a b : pre_envel_group R} → pre_envel_group_rel' R a b → pre_envel_group_rel' R b a | trans : {a b c : pre_envel_group R} → pre_envel_group_rel' R a b → pre_envel_group_rel' R b c → pre_envel_group_rel' R a c | congr_mul : {a b a' b' : pre_envel_group R} → pre_envel_group_rel' R a a' → pre_envel_group_rel' R b b' → pre_envel_group_rel' R (pre_envel_group.mul a b) (pre_envel_group.mul a' b') | congr_inv : {a a' : pre_envel_group R} → pre_envel_group_rel' R a a' → pre_envel_group_rel' R (pre_envel_group.inv a) (pre_envel_group.inv a') | assoc : (a b c : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.mul a b) c) (pre_envel_group.mul a (pre_envel_group.mul b c)) | one_mul : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul pre_envel_group.unit a) a | mul_one : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul a pre_envel_group.unit) a | mul_left_inv : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.inv a) a) pre_envel_group.unit | act_incl : (x y : R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.mul (pre_envel_group.incl x) (pre_envel_group.incl y)) (pre_envel_group.inv (pre_envel_group.incl x))) (pre_envel_group.incl (shelf.act x y)) protected instance pre_envel_group_rel'.inhabited (R : Type u) [rack R] : Inhabited (pre_envel_group_rel' R pre_envel_group.unit pre_envel_group.unit) := { default := pre_envel_group_rel'.refl } /-- The `pre_envel_group_rel` relation as a `Prop`. Used as the relation for `pre_envel_group.setoid`. -/ inductive pre_envel_group_rel (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Prop where | rel : ∀ {a b : pre_envel_group R}, pre_envel_group_rel' R a b → pre_envel_group_rel R a b /-- A quick way to convert a `pre_envel_group_rel'` to a `pre_envel_group_rel`. -/ theorem pre_envel_group_rel'.rel {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel' R a b → pre_envel_group_rel R a b := pre_envel_group_rel.rel theorem pre_envel_group_rel.refl {R : Type u} [rack R] {a : pre_envel_group R} : pre_envel_group_rel R a a := pre_envel_group_rel.rel pre_envel_group_rel'.refl theorem pre_envel_group_rel.symm {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b a := sorry theorem pre_envel_group_rel.trans {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} {c : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b c → pre_envel_group_rel R a c := sorry protected instance pre_envel_group.setoid (R : Type u_1) [rack R] : setoid (pre_envel_group R) := setoid.mk (pre_envel_group_rel R) sorry /-- The universal enveloping group for the rack R. -/ def envel_group (R : Type u_1) [rack R] := quotient (pre_envel_group.setoid R) -- Define the `group` instances in two steps so `inv` can be inferred correctly. -- TODO: is there a non-invasive way of defining the instance directly? protected instance envel_group.div_inv_monoid (R : Type u_1) [rack R] : div_inv_monoid (envel_group R) := div_inv_monoid.mk (fun (a b : envel_group R) => quotient.lift_on₂ a b (fun (a b : pre_envel_group R) => quotient.mk (pre_envel_group.mul a b)) sorry) sorry (quotient.mk pre_envel_group.unit) sorry sorry (fun (a : envel_group R) => quotient.lift_on a (fun (a : pre_envel_group R) => quotient.mk (pre_envel_group.inv a)) sorry) fun (a b : envel_group R) => quotient.lift_on₂ a (quotient.lift_on b (fun (a : pre_envel_group R) => quotient.mk (pre_envel_group.inv a)) sorry) (fun (a b : pre_envel_group R) => quotient.mk (pre_envel_group.mul a b)) sorry protected instance envel_group.group (R : Type u_1) [rack R] : group (envel_group R) := group.mk div_inv_monoid.mul sorry div_inv_monoid.one sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry protected instance envel_group.inhabited (R : Type u_1) [rack R] : Inhabited (envel_group R) := { default := 1 } /-- The canonical homomorphism from a rack to its enveloping group. Satisfies universal properties given by `to_envel_group.map` and `to_envel_group.univ`. -/ def to_envel_group (R : Type u_1) [rack R] : shelf_hom R (quandle.conj (envel_group R)) := shelf_hom.mk (fun (x : R) => quotient.mk (pre_envel_group.incl x)) sorry /-- The preliminary definition of the induced map from the enveloping group. See `to_envel_group.map`. -/ def to_envel_group.map_aux {R : Type u_1} [rack R] {G : Type u_2} [group G] (f : shelf_hom R (quandle.conj G)) : pre_envel_group R → G := sorry namespace to_envel_group.map_aux /-- Show that `to_envel_group.map_aux` sends equivalent expressions to equal terms. -/ theorem well_def {R : Type u_1} [rack R] {G : Type u_2} [group G] (f : shelf_hom R (quandle.conj G)) {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel' R a b → map_aux f a = map_aux f b := sorry end to_envel_group.map_aux /-- Given a map from a rack to a group, lift it to being a map from the enveloping group. More precisely, the `envel_group` functor is left adjoint to `quandle.conj`. -/ def to_envel_group.map {R : Type u_1} [rack R] {G : Type u_2} [group G] : shelf_hom R (quandle.conj G) ≃ (envel_group R →* G) := equiv.mk (fun (f : shelf_hom R (quandle.conj G)) => monoid_hom.mk (fun (x : envel_group R) => quotient.lift_on x (to_envel_group.map_aux f) sorry) sorry sorry) (fun (F : envel_group R →* G) => shelf_hom.comp (quandle.conj.map F) (to_envel_group R)) sorry sorry /-- Given a homomorphism from a rack to a group, it factors through the enveloping group. -/ theorem to_envel_group.univ (R : Type u_1) [rack R] (G : Type u_2) [group G] (f : shelf_hom R (quandle.conj G)) : shelf_hom.comp (quandle.conj.map (coe_fn to_envel_group.map f)) (to_envel_group R) = f := equiv.symm_apply_apply to_envel_group.map f /-- The homomorphism `to_envel_group.map f` is the unique map that fits into the commutative triangle in `to_envel_group.univ`. -/ theorem to_envel_group.univ_uniq (R : Type u_1) [rack R] (G : Type u_2) [group G] (f : shelf_hom R (quandle.conj G)) (g : envel_group R →* G) (h : f = shelf_hom.comp (quandle.conj.map g) (to_envel_group R)) : g = coe_fn to_envel_group.map f := Eq.symm h ▸ Eq.symm (equiv.apply_symm_apply to_envel_group.map g) /-- The induced group homomorphism from the enveloping group into bijections of the rack, using `rack.to_conj`. Satisfies the property `envel_action_prop`. This gives the rack `R` the structure of an augmented rack over `envel_group R`. -/ def envel_action {R : Type u_1} [rack R] : envel_group R →* R ≃ R := coe_fn to_envel_group.map (to_conj R) @[simp] theorem envel_action_prop {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (coe_fn envel_action (coe_fn (to_envel_group R) x)) y = shelf.act x y := rfl end Mathlib
54b1c6e06043c61ca9a3685ad0857760b8c63564
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/metric_space/antilipschitz.lean
e7b09f09554a224b5d466b59c6951f826f8c7dfe
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
9,501
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.lipschitz import topology.uniform_space.complete_separated /-! # Antilipschitz functions We say that a map `f : α → β` between two (extended) metric spaces is `antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`. For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ℝ≥0∞`. We do not require `0 < K` in the definition, mostly because we do not have a `posreal` type. -/ variables {α : Type*} {β : Type*} {γ : Type*} open_locale nnreal ennreal uniformity open set filter bornology /-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have `K * edist x y ≤ edist (f x) (f y)`. -/ def antilipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) := ∀ x y, edist x y ≤ K * edist (f x) (f y) lemma antilipschitz_with.edist_lt_top [pseudo_emetric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} (h : antilipschitz_with K f) (x y : α) : edist x y < ⊤ := (h x y).trans_lt $ ennreal.mul_lt_top ennreal.coe_ne_top (edist_ne_top _ _) lemma antilipschitz_with.edist_ne_top [pseudo_emetric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} (h : antilipschitz_with K f) (x y : α) : edist x y ≠ ⊤ := (h.edist_lt_top x y).ne section metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma antilipschitz_with_iff_le_mul_nndist : antilipschitz_with K f ↔ ∀ x y, nndist x y ≤ K * nndist (f x) (f y) := by { simp only [antilipschitz_with, edist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_nndist ↔ antilipschitz_with.le_mul_nndist antilipschitz_with.of_le_mul_nndist lemma antilipschitz_with_iff_le_mul_dist : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) := by { simp only [antilipschitz_with_iff_le_mul_nndist, dist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist antilipschitz_with.of_le_mul_dist namespace antilipschitz_with lemma mul_le_nndist (hf : antilipschitz_with K f) (x y : α) : K⁻¹ * nndist x y ≤ nndist (f x) (f y) := by simpa only [div_eq_inv_mul] using nnreal.div_le_of_le_mul' (hf.le_mul_nndist x y) lemma mul_le_dist (hf : antilipschitz_with K f) (x y : α) : (K⁻¹ * dist x y : ℝ) ≤ dist (f x) (f y) := by exact_mod_cast hf.mul_le_nndist x y end antilipschitz_with end metric namespace antilipschitz_with variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables {K : ℝ≥0} {f : α → β} open emetric /-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g., if `K` is given by a long formula, and we want to reuse this value. -/ @[nolint unused_arguments] -- uses neither `f` nor `hf` protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K protected lemma injective {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) : function.injective f := λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) : (K⁻¹ * edist x y : ℝ≥0∞) ≤ edist (f x) (f y) := begin rw [mul_comm, ← div_eq_mul_inv], exact ennreal.div_le_of_le_mul' (hf x y) end lemma ediam_preimage_le (hf : antilipschitz_with K f) (s : set β) : diam (f ⁻¹' s) ≤ K * diam s := diam_le $ λ x hx y hy, (hf x y).trans $ mul_le_mul_left' (edist_le_diam_of_mem hx hy) K lemma le_mul_ediam_image (hf : antilipschitz_with K f) (s : set α) : diam s ≤ K * diam (f '' s) := (diam_mono (subset_preimage_image _ _)).trans (hf.ediam_preimage_le (f '' s)) protected lemma id : antilipschitz_with 1 (id : α → α) := λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl] lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g) {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) : antilipschitz_with (Kf * Kg) (g ∘ f) := λ x y, calc edist x y ≤ Kf * edist (f x) (f y) : hf x y ... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _) ... = _ : by rw [ennreal.coe_mul, mul_assoc] lemma restrict (hf : antilipschitz_with K f) (s : set α) : antilipschitz_with K (s.restrict f) := λ x y, hf x y lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) : antilipschitz_with K (s.cod_restrict f hs) := λ x y, hf x y lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f)) {g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) : lipschitz_with K (t.restrict g) := λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β} (h : right_inv_on g f t) : lipschitz_with K (t.restrict g) := (hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : lipschitz_with K g := begin intros x y, have := hf (g x) (g y), rwa [hg x, hg y] at this end lemma comap_uniformity_le (hf : antilipschitz_with K f) : (𝓤 β).comap (prod.map f f) ≤ 𝓤 α := begin refine ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).2 (λ ε h₀, _), refine ⟨K⁻¹ * ε, ennreal.mul_pos (ennreal.inv_ne_zero.2 ennreal.coe_ne_top) h₀.ne', _⟩, refine λ x hx, (hf x.1 x.2).trans_lt _, rw [mul_comm, ← div_eq_mul_inv] at hx, rw mul_comm, exact ennreal.mul_lt_of_lt_div hx end protected lemma uniform_inducing (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_inducing f := ⟨le_antisymm hf.comap_uniformity_le hfc.le_comap⟩ protected lemma uniform_embedding {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f := ⟨hf.uniform_inducing hfc, hf.injective⟩ lemma is_complete_range [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_complete (range f) := (hf.uniform_inducing hfc).is_complete_range lemma is_closed_range {α β : Type*} [pseudo_emetric_space α] [emetric_space β] [complete_space α] {f : α → β} {K : ℝ≥0} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_closed (range f) := (hf.is_complete_range hfc).is_closed lemma closed_embedding {α : Type*} {β : Type*} [emetric_space α] [emetric_space β] {K : ℝ≥0} {f : α → β} [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : closed_embedding f := { closed_range := hf.is_closed_range hfc, .. (hf.uniform_embedding hfc).embedding } lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) := antilipschitz_with.id.restrict s lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f := λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le] /-- If `f : α → β` is `0`-antilipschitz, then `α` is a `subsingleton`. -/ protected lemma subsingleton {α β} [emetric_space α] [pseudo_emetric_space β] {f : α → β} (h : antilipschitz_with 0 f) : subsingleton α := ⟨λ x y, edist_le_zero.1 $ (h x y).trans_eq $ zero_mul _⟩ end antilipschitz_with namespace antilipschitz_with open metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma bounded_preimage (hf : antilipschitz_with K f) {s : set β} (hs : bounded s) : bounded (f ⁻¹' s) := exists.intro (K * diam s) $ λ x hx y hy, calc dist x y ≤ K * dist (f x) (f y) : hf.le_mul_dist x y ... ≤ K * diam s : mul_le_mul_of_nonneg_left (dist_le_diam_of_mem hs hx hy) K.2 lemma tendsto_cobounded (hf : antilipschitz_with K f) : tendsto f (cobounded α) (cobounded β) := compl_surjective.forall.2 $ λ s (hs : is_bounded s), metric.is_bounded_iff.2 $ hf.bounded_preimage $ metric.is_bounded_iff.1 hs /-- The image of a proper space under an expanding onto map is proper. -/ protected lemma proper_space {α : Type*} [metric_space α] {K : ℝ≥0} {f : α → β} [proper_space α] (hK : antilipschitz_with K f) (f_cont : continuous f) (hf : function.surjective f) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := is_closed_ball.preimage f_cont, have B : bounded K := hK.bounded_preimage bounded_closed_ball, have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, convert this.image f_cont, exact (hf.image_preimage _).symm end end antilipschitz_with lemma lipschitz_with.to_right_inverse [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : antilipschitz_with K g := λ x y, by simpa only [hg _] using hf (g x) (g y)
e9561b3c5e90c517acd1729185d4f27d73dddb55
a339bc2ac96174381fb610f4b2e1ba42df2be819
/hott/homotopy/susp.hlean
01a4c816fe5a4b9657851a5cdb4f97739de97b13
[ "Apache-2.0" ]
permissive
kalfsvag/lean2
25b2dccc07a98e5aa20f9a11229831f9d3edf2e7
4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7
refs/heads/master
1,610,513,122,164
1,483,135,198,000
1,483,135,198,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,435
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Ulrik Buchholtz Declaration of suspension -/ import hit.pushout types.pointed cubical.square .connectedness open pushout unit eq equiv definition susp (A : Type) : Type := pushout (λ(a : A), star) (λ(a : A), star) namespace susp variable {A : Type} definition north {A : Type} : susp A := inl star definition south {A : Type} : susp A := inr star definition merid (a : A) : @north A = @south A := glue a protected definition rec {P : susp A → Type} (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) (x : susp A) : P x := begin induction x with u u, { cases u, exact PN}, { cases u, exact PS}, { apply Pm}, end protected definition rec_on [reducible] {P : susp A → Type} (y : susp A) (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) : P y := susp.rec PN PS Pm y theorem rec_merid {P : susp A → Type} (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) (a : A) : apd (susp.rec PN PS Pm) (merid a) = Pm a := !rec_glue protected definition elim {P : Type} (PN : P) (PS : P) (Pm : A → PN = PS) (x : susp A) : P := susp.rec PN PS (λa, pathover_of_eq _ (Pm a)) x protected definition elim_on [reducible] {P : Type} (x : susp A) (PN : P) (PS : P) (Pm : A → PN = PS) : P := susp.elim PN PS Pm x theorem elim_merid {P : Type} {PN PS : P} (Pm : A → PN = PS) (a : A) : ap (susp.elim PN PS Pm) (merid a) = Pm a := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (merid a)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑susp.elim,rec_merid], end protected definition elim_type (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (x : susp A) : Type := pushout.elim_type (λx, PN) (λx, PS) Pm x protected definition elim_type_on [reducible] (x : susp A) (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) : Type := susp.elim_type PN PS Pm x theorem elim_type_merid (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (a : A) : transport (susp.elim_type PN PS Pm) (merid a) = Pm a := !elim_type_glue theorem elim_type_merid_inv {A : Type} (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (a : A) : transport (susp.elim_type PN PS Pm) (merid a)⁻¹ = to_inv (Pm a) := !elim_type_glue_inv protected definition merid_square {a a' : A} (p : a = a') : square (merid a) (merid a') idp idp := by cases p; apply vrefl end susp attribute susp.north susp.south [constructor] attribute susp.rec susp.elim [unfold 6] [recursor 6] attribute susp.elim_type [unfold 5] attribute susp.rec_on susp.elim_on [unfold 3] attribute susp.elim_type_on [unfold 2] namespace susp open is_trunc is_conn trunc -- Theorem 8.2.1 definition is_conn_susp [instance] (n : trunc_index) (A : Type) [H : is_conn n A] : is_conn (n .+1) (susp A) := is_contr.mk (tr north) begin apply trunc.rec, fapply susp.rec, { reflexivity }, { exact (trunc.rec (λa, ap tr (merid a)) (center (trunc n A))) }, { intro a, generalize (center (trunc n A)), apply trunc.rec, intro a', apply pathover_of_tr_eq, rewrite [eq_transport_Fr,idp_con], revert H, induction n with [n, IH], { intro H, apply is_prop.elim }, { intros H, change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a'), generalize a', apply is_conn_fun.elim n (is_conn_fun_from_unit n A a) (λx : A, trunctype.mk' n (ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid x))), intros, change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a), reflexivity } } end /- Flattening lemma -/ open prod prod.ops section universe variable u parameters (A : Type) (PN PS : Type.{u}) (Pm : A → PN ≃ PS) include Pm local abbreviation P [unfold 5] := susp.elim_type PN PS Pm local abbreviation F : A × PN → PN := λz, z.2 local abbreviation G : A × PN → PS := λz, Pm z.1 z.2 protected definition flattening : sigma P ≃ pushout F G := begin apply equiv.trans !pushout.flattening, fapply pushout.equiv, { exact sigma.equiv_prod A PN }, { apply sigma.sigma_unit_left }, { apply sigma.sigma_unit_left }, { reflexivity }, { reflexivity } end end end susp /- Functoriality and equivalence -/ namespace susp variables {A B : Type} (f : A → B) include f protected definition functor [unfold 4] : susp A → susp B := begin intro x, induction x with a, { exact north }, { exact south }, { exact merid (f a) } end variable [Hf : is_equiv f] include Hf open is_equiv protected definition is_equiv_functor [instance] [constructor] : is_equiv (susp.functor f) := adjointify (susp.functor f) (susp.functor f⁻¹) abstract begin intro sb, induction sb with b, do 2 reflexivity, apply eq_pathover, rewrite [ap_id,ap_compose' (susp.functor f) (susp.functor f⁻¹)], krewrite [susp.elim_merid,susp.elim_merid], apply transpose, apply susp.merid_square (right_inv f b) end end abstract begin intro sa, induction sa with a, do 2 reflexivity, apply eq_pathover, rewrite [ap_id,ap_compose' (susp.functor f⁻¹) (susp.functor f)], krewrite [susp.elim_merid,susp.elim_merid], apply transpose, apply susp.merid_square (left_inv f a) end end end susp namespace susp variables {A B : Type} (f : A ≃ B) protected definition equiv : susp A ≃ susp B := equiv.mk (susp.functor f) _ end susp namespace susp open pointed definition pointed_susp [instance] [constructor] (X : Type) : pointed (susp X) := pointed.mk north end susp open susp definition psusp [constructor] (X : Type) : Type* := pointed.mk' (susp X) namespace susp open pointed is_trunc variables {X Y Z : Type*} definition is_conn_psusp [instance] (n : trunc_index) (A : Type*) [H : is_conn n A] : is_conn (n .+1) (psusp A) := is_conn_susp n A definition psusp_functor [constructor] (f : X →* Y) : psusp X →* psusp Y := begin fconstructor, { exact susp.functor f }, { reflexivity } end definition is_equiv_psusp_functor [constructor] (f : X →* Y) [Hf : is_equiv f] : is_equiv (psusp_functor f) := susp.is_equiv_functor f definition psusp_equiv [constructor] (f : X ≃* Y) : psusp X ≃* psusp Y := pequiv_of_equiv (susp.equiv f) idp definition psusp_functor_compose (g : Y →* Z) (f : X →* Y) : psusp_functor (g ∘* f) ~* psusp_functor g ∘* psusp_functor f := begin fconstructor, { intro a, induction a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, rewrite [▸*,ap_compose' _ (psusp_functor f)], krewrite +susp.elim_merid } }, { reflexivity } end -- adjunction from Coq-HoTT definition loop_psusp_unit [constructor] (X : Type*) : X →* Ω(psusp X) := begin fconstructor, { intro x, exact merid x ⬝ (merid pt)⁻¹ }, { apply con.right_inv }, end definition loop_psusp_unit_natural (f : X →* Y) : loop_psusp_unit Y ∘* f ~* ap1 (psusp_functor f) ∘* loop_psusp_unit X := begin induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf, fconstructor, { intro x', esimp [psusp_functor], symmetry, exact !idp_con ⬝ (!ap_con ⬝ whisker_left _ !ap_inv) ⬝ (!elim_merid ◾ (inverse2 !elim_merid)) }, { rewrite [▸*,idp_con (con.right_inv _)], apply inv_con_eq_of_eq_con, refine _ ⬝ !con.assoc', rewrite inverse2_right_inv, refine _ ⬝ !con.assoc', rewrite [ap_con_right_inv], xrewrite [idp_con_idp, -ap_compose (concat idp)] }, end definition loop_psusp_counit [constructor] (X : Type*) : psusp (Ω X) →* X := begin fconstructor, { intro x, induction x, exact pt, exact pt, exact a }, { reflexivity }, end definition loop_psusp_counit_natural (f : X →* Y) : f ∘* loop_psusp_counit X ~* loop_psusp_counit Y ∘* (psusp_functor (ap1 f)) := begin induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf, fconstructor, { intro x', induction x' with p, { reflexivity }, { reflexivity }, { esimp, apply eq_pathover, apply hdeg_square, xrewrite [ap_compose' f, ap_compose' (susp.elim (f x) (f x) (λ (a : f x = f x), a)),▸*], xrewrite [+elim_merid,▸*,idp_con] }}, { reflexivity } end definition loop_psusp_counit_unit (X : Type*) : ap1 (loop_psusp_counit X) ∘* loop_psusp_unit (Ω X) ~* pid (Ω X) := begin induction X with X x, fconstructor, { intro p, esimp, refine !idp_con ⬝ (!ap_con ⬝ whisker_left _ !ap_inv) ⬝ (!elim_merid ◾ inverse2 !elim_merid) }, { rewrite [▸*,inverse2_right_inv (elim_merid id idp)], refine !con.assoc ⬝ _, xrewrite [ap_con_right_inv (susp.elim x x (λa, a)) (merid idp),idp_con_idp,-ap_compose] } end definition loop_psusp_unit_counit (X : Type*) : loop_psusp_counit (psusp X) ∘* psusp_functor (loop_psusp_unit X) ~* pid (psusp X) := begin induction X with X x, fconstructor, { intro x', induction x', { reflexivity }, { exact merid pt }, { apply eq_pathover, xrewrite [▸*, ap_id, ap_compose' (susp.elim north north (λa, a)), +elim_merid,▸*], apply square_of_eq, exact !idp_con ⬝ !inv_con_cancel_right⁻¹ }}, { reflexivity } end definition psusp.elim [constructor] {X Y : Type*} (f : X →* Ω Y) : psusp X →* Y := loop_psusp_counit Y ∘* psusp_functor f definition loop_psusp_intro [constructor] {X Y : Type*} (f : psusp X →* Y) : X →* Ω Y := ap1 f ∘* loop_psusp_unit X definition psusp_adjoint_loop_right_inv {X Y : Type*} (g : X →* Ω Y) : loop_psusp_intro (psusp.elim g) ~* g := begin refine !pwhisker_right !ap1_pcompose ⬝* _, refine !passoc ⬝* _, refine !pwhisker_left !loop_psusp_unit_natural⁻¹* ⬝* _, refine !passoc⁻¹* ⬝* _, refine !pwhisker_right !loop_psusp_counit_unit ⬝* _, apply pid_pcompose end definition psusp_adjoint_loop_left_inv {X Y : Type*} (f : psusp X →* Y) : psusp.elim (loop_psusp_intro f) ~* f := begin refine !pwhisker_left !psusp_functor_compose ⬝* _, refine !passoc⁻¹* ⬝* _, refine !pwhisker_right !loop_psusp_counit_natural⁻¹* ⬝* _, refine !passoc ⬝* _, refine !pwhisker_left !loop_psusp_unit_counit ⬝* _, apply pcompose_pid end -- TODO: rename to psusp_adjoint_loop (also in above lemmas) definition psusp_adjoint_loop_unpointed [constructor] (X Y : Type*) : psusp X →* Y ≃ X →* Ω Y := begin fapply equiv.MK, { exact loop_psusp_intro }, { exact psusp.elim }, { intro g, apply eq_of_phomotopy, exact psusp_adjoint_loop_right_inv g }, { intro f, apply eq_of_phomotopy, exact psusp_adjoint_loop_left_inv f } end definition psusp_adjoint_loop_pconst (X Y : Type*) : psusp_adjoint_loop_unpointed X Y (pconst (psusp X) Y) ~* pconst X (Ω Y) := begin refine pwhisker_right _ !ap1_pconst ⬝* _, apply pconst_pcompose end definition psusp_adjoint_loop [constructor] (X Y : Type*) : ppmap (psusp X) Y ≃* ppmap X (Ω Y) := begin apply pequiv_of_equiv (psusp_adjoint_loop_unpointed X Y), apply eq_of_phomotopy, apply psusp_adjoint_loop_pconst end definition ap1_psusp_elim {A : Type*} {X : Type*} (p : A →* Ω X) : Ω→(psusp.elim p) ∘* loop_psusp_unit A ~* p := psusp_adjoint_loop_right_inv p definition psusp_adjoint_loop_nat_right (f : psusp X →* Y) (g : Y →* Z) : psusp_adjoint_loop X Z (g ∘* f) ~* ap1 g ∘* psusp_adjoint_loop X Y f := begin esimp [psusp_adjoint_loop], refine _ ⬝* !passoc, apply pwhisker_right, apply ap1_pcompose end definition psusp_adjoint_loop_nat_left (f : Y →* Ω Z) (g : X →* Y) : (psusp_adjoint_loop X Z)⁻¹ᵉ (f ∘* g) ~* (psusp_adjoint_loop Y Z)⁻¹ᵉ f ∘* psusp_functor g := begin esimp [psusp_adjoint_loop], refine _ ⬝* !passoc⁻¹*, apply pwhisker_left, apply psusp_functor_compose end /- iterated suspension -/ definition iterate_susp (n : ℕ) (A : Type) : Type := iterate susp n A definition iterate_psusp (n : ℕ) (A : Type*) : Type* := iterate (λX, psusp X) n A open is_conn trunc_index nat definition iterate_susp_succ (n : ℕ) (A : Type) : iterate_susp (succ n) A = susp (iterate_susp n A) := idp definition is_conn_iterate_susp [instance] (n : ℕ₋₂) (m : ℕ) (A : Type) [H : is_conn n A] : is_conn (n + m) (iterate_susp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end definition is_conn_iterate_psusp [instance] (n : ℕ₋₂) (m : ℕ) (A : Type*) [H : is_conn n A] : is_conn (n + m) (iterate_psusp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end -- Separate cases for n = 0, which comes up often definition is_conn_iterate_susp_zero [instance] (m : ℕ) (A : Type) [H : is_conn 0 A] : is_conn m (iterate_susp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end definition is_conn_iterate_psusp_zero [instance] (m : ℕ) (A : Type*) [H : is_conn 0 A] : is_conn m (iterate_psusp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end definition iterate_psusp_functor (n : ℕ) {A B : Type*} (f : A →* B) : iterate_psusp n A →* iterate_psusp n B := begin induction n with n g, { exact f }, { exact psusp_functor g } end definition iterate_psusp_succ_in (n : ℕ) (A : Type*) : iterate_psusp (succ n) A ≃* iterate_psusp n (psusp A) := begin induction n with n IH, { reflexivity}, { exact psusp_equiv IH} end definition iterate_psusp_adjoint_loopn [constructor] (X Y : Type*) (n : ℕ) : ppmap (iterate_psusp n X) Y ≃* ppmap X (Ω[n] Y) := begin revert X Y, induction n with n IH: intro X Y, { reflexivity }, { refine !psusp_adjoint_loop ⬝e* !IH ⬝e* _, apply pequiv_ppcompose_left, symmetry, apply loopn_succ_in } end end susp
0650de95f6850b9bee7e3eca314ed664c46ced61
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/meta/has_reflect.lean
73850242dfce0396948fc2a7bfe51bcacae19679
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,788
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.expr init.util universes u v /-- `has_reflect α` lets you produce an `expr` from an instance of α. That is, it is a function from α to expr such that the expr has type α. -/ @[reducible] meta def has_reflect (α : Sort u) := Π a : α, reflected a meta structure reflected_value (α : Type u) := (val : α) [reflect : reflected val] namespace reflected_value meta def expr {α : Type u} (v : reflected_value α) : expr := v.reflect meta def subst {α : Type u} {β : Type v} (f : α → β) [rf : reflected f] (a : reflected_value α) : reflected_value β := @mk _ (f a.val) (rf.subst a.reflect) end reflected_value section local attribute [semireducible] reflected meta instance nat.reflect : has_reflect ℕ | n := if n = 0 then `(0 : ℕ) else if n = 1 then `(1 : ℕ) else if n % 2 = 0 then `(bit0 %%(nat.reflect (n / 2)) : ℕ) else `(bit1 %%(nat.reflect (n / 2)) : ℕ) meta instance unsigned.reflect : has_reflect unsigned | ⟨n, pr⟩ := `(unsigned.of_nat' n) end /- Instances that [derive] depends on. All other basic instances are defined at the end of derive.lean. -/ meta instance name.reflect : has_reflect name | name.anonymous := `(name.anonymous) | (name.mk_string s n) := `(λ n, name.mk_string s n).subst (name.reflect n) | (name.mk_numeral i n) := `(λ n, name.mk_numeral i n).subst (name.reflect n) meta instance list.reflect {α : Type} [has_reflect α] [reflected α] : has_reflect (list α) | [] := `([]) | (h::t) := `(λ t, h :: t).subst (list.reflect t) meta instance punit.reflect : has_reflect punit | () := `(_)
04e3ee9da4774695f679b0a89636948c8a5dbbab
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/ring_theory/localization.lean
f6128e7d0c7caf73386c7f9adb40e061592d354b
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
68,209
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 -/ import data.equiv.ring import group_theory.monoid_localization import ring_theory.ideal.operations import ring_theory.algebraic import ring_theory.integral_closure import ring_theory.non_zero_divisors /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We show that a localization at the complement of a prime ideal is a local ring. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## 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] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know` the map needed to induce the instance. -/ @[nolint unused_arguments has_inhabited_instance] def codomain (f : localization_map M S) := S instance : comm_ring f.codomain := by assumption instance {K : Type*} [field K] (f : localization_map M K) : field f.codomain := by assumption /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map -- TODO: define a subalgebra of `is_integer`s lemma is_integer_zero : f.is_integer 0 := ⟨0, f.to_map.map_zero⟩ lemma is_integer_one : f.is_integer 1 := ⟨1, f.to_map.map_one⟩ variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) := begin haveI := classical.prop_decidable, use ∏ a in s, (f.to_localization_map.sec a).2, intros a ha, use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (f.map_units y).mul_left_eq_zero.1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_surjective (z : S) : ∃ x (y : M), f.mk' x y = z := let ⟨r, hr⟩ := f.surj z in ⟨r.1, r.2, (f.eq_mk'_iff_mul_eq.2 hr).symm⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : f.mk' x y ∈ I ↔ f.to_map x ∈ I := begin split; intro h, { rw [← mk'_spec f x y, mul_comm], exact I.smul_mem (f.to_map y) h }, { rw ← mk'_spec f x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units f y), have := I.smul_mem b h, rwa [smul_eq_mul, mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self' _ lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : f.mk' x y * f.mk' y x = 1 := by rw [←f.mk'_mul, mul_comm]; exact f.mk'_self _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : f.mk' x y * f.mk' y ⟨x, h⟩ = 1 := f.mk'_mul_mk'_eq_one ⟨x, h⟩ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ section away_map variables (x : R) /-- Given `x : R`, the type of homomorphisms `f : R →* S` such that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away_map (S' : Type*) [comm_ring S'] := localization_map (submonoid.powers x) S' variables (F : away_map x S) /-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def away_map.inv_self : S := F.mk' 1 ⟨x, submonoid.mem_powers _⟩ /-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s `g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def away_map.lift (hg : is_unit (g x)) : S →+* P := localization_map.lift F $ λ y, show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : R` and localization maps `F : R →+* S, G : R →+* P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) (G : away_map (x * y) P) : S →* P := F.lift x $ show is_unit (G.to_map x), from is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away_map end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ section away variables (x : R) /-- Given `x : R`, the natural hom sending `y : R`, `R` a `comm_ring`, to the equivalence class of `(y, 1)` in the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away.of : localization_map.away_map x (away x) := of (submonoid.powers x) @[simp] lemma away.mk_eq_mk' : mk = (away.of x).mk' := mk_eq_mk' /-- Given `x : R` and a localization map `f : R →+* S` away from `x`, we get an isomorphism between the localization of `R` at the submonoid generated by `x` as a quotient type and `S`. -/ noncomputable def away.ring_equiv_of_quotient (f : localization_map.away_map x S) : away x ≃+* S := ring_equiv_of_quotient f end away end localization variables {M} section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } end ideal namespace localization_map variables (S) /-- A localization map from `R` to `S` where the submonoid is the complement of a prime ideal of `R`. -/ @[reducible] def at_prime := localization_map I.prime_compl S end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal, as a quotient type. -/ @[reducible] def at_prime := localization I.prime_compl end localization namespace localization_map variables {I} /-- When `f` is a localization map from `R` at the complement of a prime ideal `I`, we use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `local_ring` instance on `S` can 'know' the map needed to induce the instance. -/ instance at_prime.local_ring (f : at_prime S I) : local_ring f.codomain := local_of_nonunits_ideal (λ hze, begin rw [←f.to_map.map_one, ←f.to_map.map_zero] at hze, obtain ⟨t, ht⟩ := f.eq_iff_exists.1 hze, exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm, htz.symm ▸ I.zero_mem)) end) (begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r s}, f.mk' r s ∈ nonunits S → r ∈ I, from λ r s, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨f.mk' s ⟨r, nr⟩, f.mk'_mul_mk'_eq_one' _ _ nr⟩), rcases f.mk'_surjective x with ⟨rx, sx, hrx⟩, rcases f.mk'_surjective y with ⟨ry, sy, hry⟩, rcases f.mk'_surjective z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←f.mk'_add, ←f.mk'_mul, ←f.mk'_self I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, cases f.eq.1 hxyz with t ht, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, rw [←sub_eq_zero, ←sub_mul] at ht, have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2, have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr), { exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)}, { exact I.mul_mem_right (I.add_mem (I.mul_mem_right (this hx)) (I.mul_mem_right (this hy)))} end) end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := localization_map.at_prime.local_ring (of I.prime_compl) end localization end at_prime namespace localization_map variables (f : localization_map M S) section ideals /-- Explicit characterization of the ideal given by `ideal.map f.to_map I`. In practice, this ideal differs only in that the carrier set is defined explicitly. This definition is only meant to be used in proving `mem_map_to_map_iff`, and any proof that needs to refer to the explicit carrier set should use that theorem. -/ private def to_map_ideal (I : ideal R) : ideal S := { carrier := { z : S | ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1}, zero_mem' := ⟨⟨0, 1⟩, by simp⟩, add_mem' := begin rintros a b ⟨a', ha⟩ ⟨b', hb⟩, use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.smul_mem _ b'.1.2) (I.smul_mem _ a'.1.2)⟩, use a'.2 * b'.2, simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], rw [add_mul, ← mul_assoc a, ha, mul_comm (f.to_map a'.2) (f.to_map b'.2), ← mul_assoc b, hb], ring end, smul_mem' := begin rintros c x ⟨x', hx⟩, obtain ⟨c', hc⟩ := localization_map.surj f c, use ⟨c'.1 * x'.1, I.smul_mem c'.1 x'.1.2⟩, use c'.2 * x'.2, simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], ring end } theorem mem_map_to_map_iff {I : ideal R} {z} : z ∈ ideal.map f.to_map I ↔ ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1 := begin split, { show _ → z ∈ to_map_ideal f I, refine λ h, ideal.mem_Inf.1 h (λ z hz, _), obtain ⟨y, hy⟩ := hz, use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ }, { rintros ⟨⟨a, s⟩, h⟩, rw [← ideal.unit_mul_mem_iff_mem _ (map_units f s), mul_comm], exact h.symm ▸ ideal.mem_map_of_mem a.2 } end theorem map_comap (J : ideal S) : ideal.map f.to_map (ideal.comap f.to_map J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ, begin obtain ⟨r, s, hx⟩ := f.mk'_surjective x, rw ←hx at ⊢ hJ, exact ideal.mul_mem_right _ (ideal.mem_map_of_mem (show f.to_map r ∈ J, from f.mk'_spec r s ▸ @ideal.mul_mem_right _ _ J (f.mk' r s) (f.to_map s) hJ)), end theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime) (hM : disjoint (M : set R) I) : ideal.comap f.to_map (ideal.map f.to_map I) = I := begin refine le_antisymm (λ a ha, _) ideal.le_comap_map, rw [ideal.mem_comap, mem_map_to_map_iff] at ha, obtain ⟨⟨b, s⟩, h⟩ := ha, have : f.to_map (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h, rw [← f.to_map.map_zero, eq_iff_exists] at this, obtain ⟨c, hc⟩ := this, have : a * s ∈ I, { rw zero_mul at hc, let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem, cases hI.right this with h1 h2, { simpa using I.add_mem h1 b.2 }, { exfalso, refine hM ⟨c.2, h2⟩ } }, cases hI.right this with h1 h2, { exact h1 }, { exfalso, refine hM ⟨s.2, h2⟩ } end /-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is embedded in the ordering of ideals of `R`. -/ def order_embedding : ideal S ↪o ideal R := { to_fun := λ J, ideal.comap f.to_map J, inj' := function.left_inverse.injective f.map_comap, map_rel_iff' := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, f.map_comap J₁ ▸ f.map_comap J₂ ▸ ideal.map_mono hJ⟩ } /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its comap, see `le_rel_iso_of_prime` for the more general relation isomorphism -/ lemma is_prime_iff_is_prime_disjoint (J : ideal S) : J.is_prime ↔ (ideal.comap f.to_map J).is_prime ∧ disjoint (M : set R) ↑(ideal.comap f.to_map J) := begin split, { refine λ h, ⟨⟨_, _⟩, λ m hm, h.1 (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units f ⟨m, hm.left⟩))⟩, { refine λ hJ, h.left _, rw [eq_top_iff, (order_embedding f).map_rel_iff], exact le_of_eq hJ.symm }, { intros x y hxy, rw [ideal.mem_comap, ring_hom.map_mul] at hxy, exact h.right hxy } }, { refine λ h, ⟨λ hJ, h.left.left (eq_top_iff.2 _), _⟩, { rwa [eq_top_iff, (order_embedding f).map_rel_iff] at hJ }, { intros x y hxy, obtain ⟨a, s, ha⟩ := mk'_surjective f x, obtain ⟨b, t, hb⟩ := mk'_surjective f y, have : f.mk' (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb], rw [mk'_mem_iff, ← ideal.mem_comap] at this, replace this := h.left.right this, rw [ideal.mem_comap, ideal.mem_comap] at this, rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } } end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its map, see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/ lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime) (hd : disjoint (M : set R) ↑I) : (ideal.map f.to_map I).is_prime := begin rw [is_prime_iff_is_prime_disjoint f, comap_map_of_is_prime_disjoint f I hp hd], exact ⟨hp, hd⟩ end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M` -/ def order_iso_of_prime (f : localization_map M S) : {p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} := { to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_prime_iff_is_prime_disjoint f p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_prime_of_is_prime_disjoint f p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap f J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 I.2.1 I.2.2), map_rel_iff' := λ I I', ⟨λ h x hx, h hx, λ h, (show I.val ≤ I'.val, from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h))⟩ } /-- `quotient_map` applied to maximal ideals of a localization is `surjective`. The quotient by a maximal ideal is a field, so inverses to elements already exist, and the localization necessarily maps the equivalence class of the inverse in the localization -/ lemma surjective_quotient_map_of_maximal_of_localization {f : localization_map M S} {I : ideal S} [I.is_prime] {J : ideal R} {H : J ≤ I.comap f.to_map} (hI : (I.comap f.to_map).is_maximal) : function.surjective (I.quotient_map f.to_map H) := begin intro s, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective s, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := f.mk'_surjective s, by_cases hM : (ideal.quotient.mk (I.comap f.to_map)) m = 0, { have : I = ⊤, { rw ideal.eq_top_iff_one, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_comap] at hM, convert I.smul_mem (f.mk' 1 ⟨m, hm⟩) hM, rw [smul_eq_mul, mul_comm, ← f.mk'_eq_mul_mk'_one, f.mk'_self] }, exact ⟨0, eq_comm.1 (by simp [ideal.quotient.eq_zero_iff_mem, this])⟩ }, { rw ideal.quotient.maximal_ideal_iff_is_field_quotient at hI, obtain ⟨n, hn⟩ := hI.3 hM, obtain ⟨rn, rfl⟩ := ideal.quotient.mk_surjective n, refine ⟨(ideal.quotient.mk J) (r * rn), _⟩, -- The rest of the proof is essentially just algebraic manipulations to prove the equality rw ← ring_hom.map_mul at hn, replace hn := congr_arg (ideal.quotient_map I f.to_map le_rfl) hn, simp only [ring_hom.map_one, ideal.quotient_map_mk, ring_hom.map_mul] at hn, rw [ideal.quotient_map_mk, ← sub_eq_zero_iff_eq, ← ring_hom.map_sub, ideal.quotient.eq_zero_iff_mem, ← ideal.quotient.eq_zero_iff_mem, ring_hom.map_sub, sub_eq_zero_iff_eq, localization_map.mk'_eq_mul_mk'_one], simp only [mul_eq_mul_left_iff, ring_hom.map_mul], exact or.inl (mul_left_cancel' (λ hn, hM (ideal.quotient.eq_zero_iff_mem.2 (ideal.mem_comap.2 (ideal.quotient.eq_zero_iff_mem.1 hn)))) (trans hn (by rw [← ring_hom.map_mul, ← f.mk'_eq_mul_mk'_one, f.mk'_self, ring_hom.map_one]))) } end end ideals /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance algebra : algebra R f.codomain := f.to_map.to_algebra end localization_map namespace localization instance : algebra R (localization M) := localization_map.algebra (of M) end localization namespace localization_map variables (f : localization_map M S) @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl @[simp] lemma algebra_map_eq : algebra_map R f.codomain = f.to_map := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } /-- Map from ideals of `R` to submodules of `S` induced by `f`. -/ -- This was previously a `has_coe` instance, but if `f.codomain = R` then this will loop. -- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down -- the rest of the library. def coe_submodule (I : ideal R) : submodule R f.codomain := submodule.map f.lin_coe I variables {f} lemma mem_coe_submodule (I : ideal R) {x : S} : x ∈ f.coe_submodule I ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl variables {g : R →+* P} variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) lemma map_smul (x : f.codomain) (z : R) : f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) := show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x, by rw [ring_hom.map_mul, map_eq] lemma is_noetherian_ring (h : is_noetherian_ring R) : is_noetherian_ring f.codomain := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at h ⊢, exact order_embedding.well_founded (f.order_embedding.dual) h end end localization_map namespace localization variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an `R`-preserving isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def alg_equiv_of_quotient : localization M ≃ₐ[R] f.codomain := { commutes' := ring_equiv_of_quotient_of, ..ring_equiv_of_quotient f } lemma alg_equiv_of_quotient_apply (x : localization M) : alg_equiv_of_quotient f x = ring_equiv_of_quotient f x := rfl lemma alg_equiv_of_quotient_symm_apply (x : f.codomain) : (alg_equiv_of_quotient f).symm x = (ring_equiv_of_quotient f).symm x := rfl end localization namespace localization_map section integer_normalization variables {f : localization_map M S} open finsupp polynomial open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ) (h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization (f : localization_map M S) : polynomial f.codomain → polynomial R := λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p) @[simp] lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) : (f.integer_normalization p).coeff i = coeff_integer_normalization p i := rfl lemma integer_normalization_spec (p : polynomial f.codomain) : ∃ (b : M), ∀ i, f.to_map ((f.integer_normalization p).coeff i) = f.to_map b * p.coeff i := begin use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (_root_.mul_zero (f.to_map _)).symm, { exact f.to_ring_hom.map_zero }, { exact finsupp.not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial f.codomain) : ∃ (b : M), (f.integer_normalization p).map f.to_map = f.to_map b • p := let ⟨b, hb⟩ := integer_normalization_spec p in ⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (f.integer_normalization p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map p in trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra f.codomain R'] [is_scalar_tower R f.codomain R'] (p : polynomial f.codomain) {x : R'} (hx : aeval x p = 0) : aeval x (f.integer_normalization p) = 0 := by rw [aeval_def, is_scalar_tower.algebra_map_eq R f.codomain R', algebra_map_eq, integer_normalization_eval₂_eq_zero _ _ hx] end integer_normalization variables {R} {A K : Type*} [integral_domain A] lemma to_map_eq_zero_iff (f : localization_map M S) {x : R} (hM : M ≤ non_zero_divisors R) : f.to_map x = 0 ↔ x = 0 := begin rw ← f.to_map.map_zero, split; intro h, { cases f.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end lemma injective (f : localization_map M S) (hM : M ≤ non_zero_divisors R) : injective f.to_map := begin rw ring_hom.injective_iff f.to_map, intros a ha, rw [← f.to_map.map_zero, f.eq_iff_exists] at ha, cases ha with c hc, rw zero_mul at hc, exact hM c.2 a hc, end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (f : localization_map M S) (hM : M ≤ non_zero_divisors R) (x : non_zero_divisors R) : f.to_map x ≠ 0 := map_ne_zero_of_mem_non_zero_divisors (f.injective hM) /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. -/ def integral_domain_of_le_non_zero_divisors {M : submonoid A} (f : localization_map M S) (hM : M ≤ non_zero_divisors A) : integral_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases f.surj z with x hx, cases f.surj w with y hy, have : z * w * f.to_map y.2 * f.to_map x.2 = f.to_map x.1 * f.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, rw [h, zero_mul, zero_mul, ← f.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff f hM).mp this.symm) with H H, { exact or.inl (f.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (f.eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨f.to_map 0, f.to_map 1, λ h, zero_ne_one (f.injective hM h)⟩, ..(infer_instance : comm_ring S) } /-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/ def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : integral_domain (localization M) := (localization.of M).integral_domain_of_le_non_zero_divisors hM /-- The localization of an integral domain at the complement of a prime ideal is an integral domain. -/ instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) : integral_domain (localization.at_prime P) := integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem)) end localization_map section at_prime namespace localization local attribute [instance] classical.prop_decidable /-- The image of `P` in the localization at `P.prime_compl` is a maximal ideal, and in particular it is the unique maximal ideal given by the local ring structure `at_prime.local_ring` -/ lemma at_prime.map_eq_maximal_ideal {P : ideal R} [hP : ideal.is_prime P] : ideal.map (localization.of P.prime_compl).to_map P = (local_ring.maximal_ideal (localization P.prime_compl)) := begin let f := localization.of P.prime_compl, ext x, split; simp only [local_ring.mem_maximal_ideal, mem_nonunits_iff]; intro hx, { exact λ h, (localization_map.is_prime_of_is_prime_disjoint f P hP (set.disjoint_compl_left P.carrier)).1 (ideal.eq_top_of_is_unit_mem _ hx h) }, { obtain ⟨⟨a, b⟩, hab⟩ := localization_map.surj f x, contrapose! hx, rw is_unit_iff_exists_inv, rw localization_map.mem_map_to_map_iff at hx, obtain ⟨a', ha'⟩ := is_unit_iff_exists_inv.1 (localization_map.map_units f ⟨a, λ ha, hx ⟨⟨⟨a, ha⟩, b⟩, hab⟩⟩), exact ⟨f.to_map b * a', by rwa [← mul_assoc, hab]⟩ } end /-- The unique maximal ideal of the localization at `P.prime_compl` lies over the ideal `P`. -/ lemma at_prime.comap_maximal_ideal {P : ideal R} [ideal.is_prime P] : ideal.comap (localization.of P.prime_compl).to_map (local_ring.maximal_ideal (localization P.prime_compl)) = P := begin let Pₚ := local_ring.maximal_ideal (localization P.prime_compl), refine le_antisymm (λ x hx, _) (le_trans ideal.le_comap_map (ideal.comap_mono (le_of_eq at_prime.map_eq_maximal_ideal))), by_cases h0 : x = 0, { exact h0.symm ▸ P.zero_mem }, { have : Pₚ.is_prime := ideal.is_maximal.is_prime (local_ring.maximal_ideal.is_maximal _), rw localization_map.is_prime_iff_is_prime_disjoint (localization.of P.prime_compl) at this, contrapose! h0 with hx', simpa using this.2 ⟨hx', hx⟩ } end end localization end at_prime variables (R) {A : Type*} [integral_domain A] variables (K : Type*) /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : φ.to_map x = 0 ↔ x = 0 := φ.to_map_eq_zero_iff (le_of_eq rfl) protected theorem injective [comm_ring K] (φ : fraction_map R K) : function.injective φ.to_map := φ.injective (le_of_eq rfl) protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] [comm_ring K] (φ : fraction_map R K) (x : non_zero_divisors R) : φ.to_map x ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (le_of_eq rfl) x /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := φ.integral_domain_of_le_non_zero_divisors (le_of_eq rfl) local attribute [instance] classical.dec_eq /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (f.to_map_ne_zero_of_mem_non_zero_divisors _)).symm lemma is_unit_map_of_injective (hg : function.injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw mem_non_zero_divisors_iff_ne_zero at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa mem_non_zero_divisors_iff_ne_zero at hc, end, ..int.cast_ring_hom ℚ } lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} : f.integer_normalization p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p, split; intros h i, { apply f.to_map_eq_zero_iff.mp, rw [hb i, h i], exact _root_.mul_zero _ }, { have hi := h i, rw [polynomial.coeff_zero, ← f.to_map_eq_zero_iff, hb i] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact f.to_map_eq_zero_iff.mp h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] : algebra.is_algebraic A L ↔ algebra.is_algebraic f.codomain L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact f.to_map_eq_zero_iff.mp this }, { rwa [is_scalar_tower.aeval_apply _ f.codomain, algebra_map_eq] at px } }, { exact ⟨f.integer_normalization p, mt f.integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero p px⟩ }, end section num_denom variables [unique_factorization_monoid A] (φ : fraction_map A K) lemma exists_reduced_fraction (x : φ.codomain) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ φ.mk' a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := φ.exists_integer_multiple x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_monoid.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, apply mul_left_cancel' (φ.to_map_ne_zero_of_mem_non_zero_divisors ⟨c' * b', b_nonzero⟩), simp only [subtype.coe_mk, φ.to_map.map_mul] at *, erw [←hab, mul_assoc, φ.mk'_spec' a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : φ.codomain) : A := classical.some (φ.exists_reduced_fraction x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : φ.codomain) : non_zero_divisors A := classical.some (classical.some_spec (φ.exists_reduced_fraction x)) lemma num_denom_reduced (x : φ.codomain) : ∀ {d}, d ∣ φ.num x → d ∣ φ.denom x → is_unit d := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).1 @[simp] lemma mk'_num_denom (x : φ.codomain) : φ.mk' (φ.num x) (φ.denom x) = x := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).2 lemma num_mul_denom_eq_num_iff_eq {x y : φ.codomain} : x * φ.to_map (φ.denom y) = φ.to_map (φ.num y) ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : φ.codomain} : y * φ.to_map (φ.denom x) = φ.to_map (φ.num x) ↔ x = y := ⟨ λ h, by simpa only [eq_comm, mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : φ.codomain} : φ.num y * φ.denom x = φ.num x * φ.denom y ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.mk'_eq_of_eq h, λ h, by rw h ⟩ lemma eq_zero_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : x = 0 := φ.num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : φ.codomain} (h : is_unit (φ.denom x : A)) : φ.is_integer x := begin cases h with d hd, have d_ne_zero : φ.to_map (φ.denom x) ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (φ.denom x), use ↑d⁻¹ * φ.num x, refine trans _ (φ.mk'_num_denom x), rw [φ.to_map.map_mul, φ.to_map.map_units_inv, hd], apply mul_left_cancel' d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, φ.mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : is_unit (φ.denom x : A) := φ.num_denom_reduced x (h.symm ▸ dvd_zero _) (dvd_refl _) end num_denom end fraction_map section algebra section is_integral variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] [algebra R S] /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra (M : submonoid R) (f : localization_map M Rₘ) (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) : algebra Rₘ Sₘ := (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).to_algebra variables (f : localization_map M Rₘ) variables (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) lemma algebra_map_mk' (r : R) (m : M) : (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) (f.mk' r m) = g.mk' (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ := localization_map.map_mk' f _ r m /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) (hM : algebra.algebra_map_submonoid S M ≤ non_zero_divisors S) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) := begin rintros x y hxy, obtain ⟨a, b, rfl⟩ := localization_map.mk'_surjective f x, obtain ⟨c, d, rfl⟩ := localization_map.mk'_surjective f y, rw [algebra_map_mk' f g a b, algebra_map_mk' f g c d, localization_map.mk'_eq_iff_eq] at hxy, refine (localization_map.mk'_eq_iff_eq f).2 (congr_arg f.to_map (hRS _)), convert g.injective hM hxy; simp, end open polynomial /-- Given a particular witness to an element being algebraic over an algebra `R → S`, We can localize to a submonoid containing the leading coefficient to make it integral. Explicitly, the map between the localizations will be an integral ring morphism -/ theorem is_integral_localization_at_leading_coeff {x : S} (p : polynomial R) (hp : aeval x p = 0) (hM' : p.leading_coeff ∈ M) : (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).is_integral_elem (g.to_map x) := begin by_cases triv : (1 : Rₘ) = 0, { exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ }, haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp (localization_map.map_units f ⟨p.leading_coeff, hM'⟩), refine ⟨(p.map f.to_map) * C b, ⟨_, _⟩⟩, { refine monic_mul_C_of_leading_coeff_mul_eq_one _, rwa leading_coeff_map_of_leading_coeff_ne_zero f.to_map, refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) }, { refine eval₂_mul_eq_zero_of_left _ _ _ _, erw [eval₂_map, localization_map.map_comp, ← hom_eval₂ _ (algebra_map R S) g.to_map x], exact trans (congr_arg g.to_map hp) g.to_map.map_zero } end theorem is_integral_elem_localization_at_leading_coeff' {R S : Type*} [comm_ring R] [comm_ring S] (x : S) (p : polynomial R) (f : R →+* S) (hf : p.eval₂ f x = 0) (M : submonoid R) (hM : p.leading_coeff ∈ M) {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] (ϕ : localization_map M Rₘ) (ϕ' : localization_map (M.map ↑f : submonoid S) Sₘ) : (ϕ.map (M.mem_map_of_mem (f : R →* S)) ϕ').is_integral_elem (ϕ'.to_map x) := @is_integral_localization_at_leading_coeff R _ M S _ Rₘ Sₘ _ _ f.to_algebra ϕ ϕ' x p hf hM /-- If `R → S` is an integral extension, `M` is a submonoid of `R`, `Rₘ` is the localization of `R` at `M`, and `Sₘ` is the localization of `S` at the image of `M` under the extension map, then the induced map `Rₘ → Sₘ` is also an integral extension -/ theorem is_integral_localization (H : algebra.is_integral R S) : (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).is_integral := begin intro x, by_cases triv : (1 : R) = 0, { have : (1 : Rₘ) = 0 := by convert congr_arg f.to_map triv; simp, exact ⟨0, ⟨trans leading_coeff_zero this.symm, eval₂_zero _ _⟩⟩ }, { haveI : nontrivial R := nontrivial_of_ne 1 0 triv, obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := g.surj x, obtain ⟨v, hv⟩ := hu, obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (f.map_units ⟨v, hv.1⟩), refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _ (localization_algebra M f g) x (g.to_map u) v' _ _, { replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) hv', rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ f.to_map] at hv', erw localization_map.map_comp at hv', exact hv.2 ▸ hv' }, { obtain ⟨p, hp⟩ := H s, exact hx.symm ▸ is_integral_localization_at_leading_coeff f g p hp.2 (hp.1.symm ▸ M.one_mem) } } end lemma is_integral_localization' {R S : Type*} [comm_ring R] [comm_ring S] {f : R →+* S} (hf : f.is_integral) (M : submonoid R) : ((localization.of M).map (M.mem_map_of_mem (f : R →* S)) (localization.of (M.map ↑f))).is_integral := @is_integral_localization R _ M S _ _ _ _ _ f.to_algebra _ _ hf end is_integral namespace integral_closure variables {L : Type*} [field K] [field L] (f : fraction_map A K) open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : fraction_map (integral_closure A L) L := (algebra_map (integral_closure A L) L).to_localization_map (λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩) (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩) (λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩) variables {K} (L) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_finite_extension [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] [finite_dimensional f.codomain L] : fraction_map (integral_closure A L) L := fraction_map_of_algebraic (f.comap_is_algebraic_iff.mpr is_algebraic_of_finite) (λ x hx, f.to_map_eq_zero_iff.mp ((algebra_map f.codomain L).map_eq_zero.mp $ (is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end integral_closure end algebra variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) namespace fraction_ring /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an `A`-isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def alg_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃ₐ[A] f.codomain := localization.alg_equiv_of_quotient f instance : algebra A (fraction_ring A) := (of A).to_map.to_algebra end fraction_ring
bff12e6901ff64ccbc4ce69bd838591ccd8300b7
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/module/prod.lean
c2fd3294686f89eb24f7edbd3dbc826906b72d0a
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,165
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.module.basic import group_theory.group_action.prod /-! # Prod instances for module and multiplicative actions This file defines instances for binary product of modules -/ variables {R : Type*} {S : Type*} {M : Type*} {N : Type*} namespace prod instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : semimodule R (M × N) := { add_smul := λ a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, zero_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, .. prod.distrib_mul_action } instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [no_zero_smul_divisors R M] [no_zero_smul_divisors R N] : no_zero_smul_divisors R (M × N) := ⟨λ c ⟨x, y⟩ h, or_iff_not_imp_left.mpr (λ hc, mk.inj_iff.mpr ⟨(smul_eq_zero.mp (congr_arg fst h)).resolve_left hc, (smul_eq_zero.mp (congr_arg snd h)).resolve_left hc⟩)⟩ end prod
94ee71e218dbd016a68c6d583e7459a461929434
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/option/basic.lean
c85fb37f1dbc8b68e97797f2fd199c51abc3fad9
[]
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
17,623
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.basic import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib namespace option theorem coe_def {α : Type u_1} : coe = some := rfl theorem some_ne_none {α : Type u_1} (x : α) : some x ≠ none := fun (h : some x = none) => option.no_confusion h @[simp] theorem get_mem {α : Type u_1} {o : Option α} (h : ↥(is_some o)) : get h ∈ o := option.cases_on o (fun (h : ↥(is_some none)) => eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h)) (fun (o : α) (h : ↥(is_some (some o))) => idRhs (some o = some o) rfl) h theorem get_of_mem {α : Type u_1} {a : α} {o : Option α} (h : ↥(is_some o)) : a ∈ o → get h = a := sorry @[simp] theorem not_mem_none {α : Type u_1} (a : α) : ¬a ∈ none := fun (h : a ∈ none) => option.no_confusion h @[simp] theorem some_get {α : Type u_1} {x : Option α} (h : ↥(is_some x)) : some (get h) = x := option.cases_on x (fun (h : ↥(is_some none)) => eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h)) (fun (x : α) (h : ↥(is_some (some x))) => idRhs (some (get h) = some (get h)) rfl) h @[simp] theorem get_some {α : Type u_1} (x : α) (h : ↥(is_some (some x))) : get h = x := rfl @[simp] theorem get_or_else_some {α : Type u_1} (x : α) (y : α) : get_or_else (some x) y = x := rfl @[simp] theorem get_or_else_coe {α : Type u_1} (x : α) (y : α) : get_or_else (↑x) y = x := rfl theorem get_or_else_of_ne_none {α : Type u_1} {x : Option α} (hx : x ≠ none) (y : α) : some (get_or_else x y) = x := sorry theorem mem_unique {α : Type u_1} {o : Option α} {a : α} {b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := some.inj (Eq.trans (Eq.symm ha) hb) theorem some_injective (α : Type u_1) : function.injective some := fun (_x _x_1 : α) => iff.mp some_inj /-- `option.map f` is injective if `f` is injective. -/ theorem map_injective {α : Type u_1} {β : Type u_2} {f : α → β} (Hf : function.injective f) : function.injective (option.map f) := sorry theorem ext {α : Type u_1} {o₁ : Option α} {o₂ : Option α} : (∀ (a : α), a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ := sorry theorem eq_none_iff_forall_not_mem {α : Type u_1} {o : Option α} : o = none ↔ ∀ (a : α), ¬a ∈ o := sorry @[simp] theorem none_bind {α : Type u_1} {β : Type u_1} (f : α → Option β) : none >>= f = none := rfl @[simp] theorem some_bind {α : Type u_1} {β : Type u_1} (a : α) (f : α → Option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' {α : Type u_1} {β : Type u_2} (f : α → Option β) : option.bind none f = none := rfl @[simp] theorem some_bind' {α : Type u_1} {β : Type u_2} (a : α) (f : α → Option β) : option.bind (some a) f = f a := rfl @[simp] theorem bind_some {α : Type u_1} (x : Option α) : x >>= some = x := bind_pure @[simp] theorem bind_eq_some {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → Option β} {b : β} : x >>= f = some b ↔ ∃ (a : α), x = some a ∧ f a = some b := sorry @[simp] theorem bind_eq_some' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → Option β} {b : β} : option.bind x f = some b ↔ ∃ (a : α), x = some a ∧ f a = some b := sorry @[simp] theorem bind_eq_none' {α : Type u_1} {β : Type u_2} {o : Option α} {f : α → Option β} : option.bind o f = none ↔ ∀ (b : β) (a : α), a ∈ o → ¬b ∈ f a := sorry @[simp] theorem bind_eq_none {α : Type u_1} {β : Type u_1} {o : Option α} {f : α → Option β} : o >>= f = none ↔ ∀ (b : β) (a : α), a ∈ o → ¬b ∈ f a := bind_eq_none' theorem bind_comm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β → Option γ} (a : Option α) (b : Option β) : (option.bind a fun (x : α) => option.bind b (f x)) = option.bind b fun (y : β) => option.bind a fun (x : α) => f x y := sorry theorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} (x : Option α) (f : α → Option β) (g : β → Option γ) : option.bind (option.bind x f) g = option.bind x fun (y : α) => option.bind (f y) g := option.cases_on x (Eq.refl (option.bind (option.bind none f) g)) fun (x : α) => Eq.refl (option.bind (option.bind (some x) f) g) theorem join_eq_some {α : Type u_1} {x : Option (Option α)} {a : α} : join x = some a ↔ x = some (some a) := sorry theorem join_ne_none {α : Type u_1} {x : Option (Option α)} : join x ≠ none ↔ ∃ (z : α), x = some (some z) := sorry theorem join_ne_none' {α : Type u_1} {x : Option (Option α)} : ¬join x = none ↔ ∃ (z : α), x = some (some z) := sorry theorem bind_id_eq_join {α : Type u_1} {x : Option (Option α)} : x >>= id = join x := sorry theorem join_eq_join {α : Type u_1} : mjoin = join := sorry theorem bind_eq_bind {α : Type u_1} {β : Type u_1} {f : α → Option β} {x : Option α} : x >>= f = option.bind x f := rfl @[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} {f : α → β} : Functor.map f = option.map f := rfl theorem map_none {α : Type u_1} {β : Type u_1} {f : α → β} : f <$> none = none := rfl theorem map_some {α : Type u_1} {β : Type u_1} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {α : Type u_1} {β : Type u_2} {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {α : Type u_1} {β : Type u_2} {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl theorem map_eq_some {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ (a : α), x = some a ∧ f a = b := sorry @[simp] theorem map_eq_some' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → β} {b : β} : option.map f x = some b ↔ ∃ (a : α), x = some a ∧ f a = b := sorry theorem map_eq_none {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → β} : f <$> x = none ↔ x = none := sorry @[simp] theorem map_eq_none' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → β} : option.map f x = none ↔ x = none := sorry theorem map_congr {α : Type u_1} {β : Type u_2} {f : α → β} {g : α → β} {x : Option α} (h : ∀ (a : α), a ∈ x → f a = g a) : option.map f x = option.map g x := sorry @[simp] theorem map_id' {α : Type u_1} : option.map id = id := map_id @[simp] theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (h : β → γ) (g : α → β) (x : Option α) : option.map h (option.map g x) = option.map (h ∘ g) x := sorry theorem comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (h : β → γ) (g : α → β) (x : Option α) : option.map (h ∘ g) x = option.map h (option.map g x) := Eq.symm (map_map h g x) @[simp] theorem map_comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : β → γ) : option.map g ∘ option.map f = option.map (g ∘ f) := sorry theorem mem_map_of_mem {α : Type u_1} {β : Type u_2} {a : α} {x : Option α} (g : α → β) (h : a ∈ x) : g a ∈ option.map g x := iff.mpr mem_def (Eq.symm (iff.mp mem_def h) ▸ map_some') theorem bind_map_comm {α : Type u_1} {β : Type u_1} {x : Option (Option α)} {f : α → β} : x >>= option.map f = option.map (option.map f) x >>= id := sorry theorem join_map_eq_map_join {α : Type u_1} {β : Type u_2} {f : α → β} {x : Option (Option α)} : join (option.map (option.map f) x) = option.map f (join x) := sorry theorem join_join {α : Type u_1} {x : Option (Option (Option α))} : join (join x) = join (option.map join x) := sorry theorem mem_of_mem_join {α : Type u_1} {a : α} {x : Option (Option α)} (h : a ∈ join x) : some a ∈ x := iff.mpr mem_def (Eq.symm (iff.mp mem_def h) ▸ iff.mp join_eq_some h) @[simp] theorem pbind_eq_bind {α : Type u_1} {β : Type u_2} (f : α → Option β) (x : Option α) : (pbind x fun (a : α) (_x : a ∈ x) => f a) = option.bind x f := sorry theorem map_bind {α : Type u_1} {β : Type u_1} {γ : Type u_1} (f : β → γ) (x : Option α) (g : α → Option β) : option.map f (x >>= g) = do let a ← x option.map f (g a) := sorry theorem map_bind' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (x : Option α) (g : α → Option β) : option.map f (option.bind x g) = option.bind x fun (a : α) => option.map f (g a) := sorry theorem map_pbind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (x : Option α) (g : (a : α) → a ∈ x → Option β) : option.map f (pbind x g) = pbind x fun (a : α) (H : a ∈ x) => option.map f (g a H) := sorry theorem pbind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (x : Option α) (g : (b : β) → b ∈ option.map f x → Option γ) : pbind (option.map f x) g = pbind x fun (a : α) (h : a ∈ x) => g (f a) (mem_map_of_mem f h) := option.cases_on x (fun (g : (b : β) → b ∈ option.map f none → Option γ) => Eq.refl (pbind (option.map f none) g)) (fun (x : α) (g : (b : β) → b ∈ option.map f (some x) → Option γ) => Eq.refl (pbind (option.map f (some x)) g)) g @[simp] theorem pmap_none {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) {H : ∀ (a : α), a ∈ none → p a} : pmap f none H = none := rfl @[simp] theorem pmap_some {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) {x : α} (h : p x) : pmap f (some x) = fun (_x : ∀ (a : α), a ∈ some x → p a) => some (f x h) := rfl theorem mem_pmem {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (x : Option α) {a : α} (h : ∀ (a : α), a ∈ x → p a) (ha : a ∈ x) : f a (h a ha) ∈ pmap f x h := eq.mpr (id (Eq._oldrec (Eq.refl (f a (h a ha) ∈ pmap f x h)) (propext mem_def))) (Eq._oldrec (fun (h : ∀ (a_1 : α), a_1 ∈ some a → p a_1) (ha : a ∈ some a) => Eq.refl (pmap f (some a) h)) (Eq.symm (eq.mp (Eq._oldrec (Eq.refl (a ∈ x)) (propext mem_def)) ha)) h ha) theorem pmap_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (f : (a : α) → p a → β) (g : γ → α) (x : Option γ) (H : ∀ (a : α), a ∈ option.map g x → p a) : pmap f (option.map g x) H = pmap (fun (a : γ) (h : p (g a)) => f (g a) h) x fun (a : γ) (h : a ∈ x) => H (g a) (mem_map_of_mem g h) := sorry theorem map_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (g : β → γ) (f : (a : α) → p a → β) (x : Option α) (H : ∀ (a : α), a ∈ x → p a) : option.map g (pmap f x H) = pmap (fun (a : α) (h : p a) => g (f a h)) x H := sorry @[simp] theorem pmap_eq_map {α : Type u_1} {β : Type u_2} (p : α → Prop) (f : α → β) (x : Option α) (H : ∀ (a : α), a ∈ x → p a) : pmap (fun (a : α) (_x : p a) => f a) x H = option.map f x := sorry theorem pmap_bind {α : Type u_1} {β : Type u_1} {γ : Type u_1} {x : Option α} {g : α → Option β} {p : β → Prop} {f : (b : β) → p b → γ} (H : ∀ (a : β), a ∈ x >>= g → p a) (H' : ∀ (a : α) (b : β), b ∈ g a → b ∈ x >>= g) : pmap f (x >>= g) H = do let a ← x pmap f (g a) fun (b : β) (h : b ∈ g a) => H b (H' a b h) := sorry theorem bind_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (x : Option α) (g : β → Option γ) (H : ∀ (a : α), a ∈ x → p a) : pmap f x H >>= g = pbind x fun (a : α) (h : a ∈ x) => g (f a (H a h)) := sorry theorem pbind_eq_none {α : Type u_1} {β : Type u_2} {x : Option α} {f : (a : α) → a ∈ x → Option β} (h' : ∀ (a : α) (H : a ∈ x), f a H = none → x = none) : pbind x f = none ↔ x = none := sorry theorem pbind_eq_some {α : Type u_1} {β : Type u_2} {x : Option α} {f : (a : α) → a ∈ x → Option β} {y : β} : pbind x f = some y ↔ ∃ (z : α), ∃ (H : z ∈ x), f z H = some y := sorry @[simp] theorem pmap_eq_none_iff {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {x : Option α} {h : ∀ (a : α), a ∈ x → p a} : pmap f x h = none ↔ x = none := sorry @[simp] theorem pmap_eq_some_iff {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {x : Option α} {hf : ∀ (a : α), a ∈ x → p a} {y : β} : pmap f x hf = some y ↔ ∃ (a : α), ∃ (H : x = some a), f a (hf a H) = y := sorry @[simp] theorem join_pmap_eq_pmap_join {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {x : Option (Option α)} (H : ∀ (a : Option α), a ∈ x → ∀ (a_1 : α), a_1 ∈ a → p a_1) : join (pmap (pmap f) x H) = pmap f (join x) fun (a : α) (h : a ∈ join x) => H (some a) (mem_of_mem_join h) a rfl := sorry @[simp] theorem seq_some {α : Type u_1} {β : Type u_1} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' {α : Type u_1} (a : α) (x : Option α) : option.orelse (some a) x = some a := rfl @[simp] theorem some_orelse {α : Type u_1} (a : α) (x : Option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' {α : Type u_1} (x : Option α) : option.orelse none x = x := option.cases_on x (Eq.refl (option.orelse none none)) fun (x : α) => Eq.refl (option.orelse none (some x)) @[simp] theorem none_orelse {α : Type u_1} (x : Option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' {α : Type u_1} (x : Option α) : option.orelse x none = x := option.cases_on x (Eq.refl (option.orelse none none)) fun (x : α) => Eq.refl (option.orelse (some x) none) @[simp] theorem orelse_none {α : Type u_1} (x : Option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none {α : Type u_1} : is_some none = false := rfl @[simp] theorem is_some_some {α : Type u_1} {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {α : Type u_1} {x : Option α} : ↥(is_some x) ↔ ∃ (a : α), x = some a := sorry @[simp] theorem is_none_none {α : Type u_1} : is_none none = tt := rfl @[simp] theorem is_none_some {α : Type u_1} {a : α} : is_none (some a) = false := rfl @[simp] theorem not_is_some {α : Type u_1} {a : Option α} : is_some a = false ↔ is_none a = tt := sorry theorem eq_some_iff_get_eq {α : Type u_1} {o : Option α} {a : α} : o = some a ↔ ∃ (h : ↥(is_some o)), get h = a := sorry theorem not_is_some_iff_eq_none {α : Type u_1} {o : Option α} : ¬↥(is_some o) ↔ o = none := sorry theorem ne_none_iff_is_some {α : Type u_1} {o : Option α} : o ≠ none ↔ ↥(is_some o) := sorry theorem ne_none_iff_exists {α : Type u_1} {o : Option α} : o ≠ none ↔ ∃ (x : α), some x = o := sorry theorem ne_none_iff_exists' {α : Type u_1} {o : Option α} : o ≠ none ↔ ∃ (x : α), o = some x := iff.trans ne_none_iff_exists (exists_congr fun (_x : α) => eq_comm) theorem bex_ne_none {α : Type u_1} {p : Option α → Prop} : (∃ (x : Option α), ∃ (H : x ≠ none), p x) ↔ ∃ (x : α), p (some x) := sorry theorem ball_ne_none {α : Type u_1} {p : Option α → Prop} : (∀ (x : Option α), x ≠ none → p x) ↔ ∀ (x : α), p (some x) := sorry theorem iget_mem {α : Type u_1} [Inhabited α] {o : Option α} : ↥(is_some o) → iget o ∈ o := sorry theorem iget_of_mem {α : Type u_1} [Inhabited α] {a : α} {o : Option α} : a ∈ o → iget o = a := sorry @[simp] theorem guard_eq_some {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {b : α} : guard p a = some b ↔ a = b ∧ p a := sorry @[simp] theorem guard_eq_some' {p : Prop} [Decidable p] (u : Unit) : guard p = some u ↔ p := sorry theorem lift_or_get_choice {α : Type u_1} {f : α → α → α} (h : ∀ (a b : α), f a b = a ∨ f a b = b) (o₁ : Option α) (o₂ : Option α) : lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ := sorry @[simp] theorem lift_or_get_none_left {α : Type u_1} {f : α → α → α} {b : Option α} : lift_or_get f none b = b := option.cases_on b (Eq.refl (lift_or_get f none none)) fun (b : α) => Eq.refl (lift_or_get f none (some b)) @[simp] theorem lift_or_get_none_right {α : Type u_1} {f : α → α → α} {a : Option α} : lift_or_get f a none = a := option.cases_on a (Eq.refl (lift_or_get f none none)) fun (a : α) => Eq.refl (lift_or_get f (some a) none) @[simp] theorem lift_or_get_some_some {α : Type u_1} {f : α → α → α} {a : α} {b : α} : lift_or_get f (some a) (some b) = ↑(f a b) := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' {α : Type u_1} {β : Type u_2} : Option α → β → (α → β) → β := sorry @[simp] theorem cases_on'_none {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) : cases_on' none x f = x := rfl @[simp] theorem cases_on'_some {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) (a : α) : cases_on' (some a) x f = f a := rfl @[simp] theorem cases_on'_coe {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) (a : α) : cases_on' (↑a) x f = f a := rfl @[simp] theorem cases_on'_none_coe {α : Type u_1} {β : Type u_2} (f : Option α → β) (o : Option α) : cases_on' o (f none) (f ∘ coe) = f o := option.cases_on o (Eq.refl (cases_on' none (f none) (f ∘ coe))) fun (o : α) => Eq.refl (cases_on' (some o) (f none) (f ∘ coe))
424be30d1ea38c8e27e7ecef4673c30f653a2f14
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/backwards_reasoning.lean
518c1dea985578f6ed4bff92eed80e5819a51270
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
3,249
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .pempty import .recover open tactic meta def back_attribute : user_attribute := { name := `back, descr := "A lemma that should be applied to a goal whenever possible; use `backwards_reasoning` to automatically `apply` all lemmas tagged `[back]`." } run_cmd attribute.register `back_attribute /-- Try to apply one of the given lemmas; it succeeds as soon as one of them succeeds. -/ meta def any_apply : list name → tactic name | [] := failed | (c::cs) := (mk_const c >>= apply >> pure c) <|> any_apply cs meta def back'_attribute : user_attribute := { name := `back', descr := "A lemma that should be applied to a goal whenever possible, as long as all arguments to the lemma by be fulfilled from existing hypotheses; use `backwards_reasoning` to automatically apply all lemmas tagged `[back']`." } run_cmd attribute.register `back'_attribute meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) /-- Try to apply one of the given lemmas, fulfilling all new goals using existing hypotheses. It succeeds if one of them succeeds. -/ meta def any_apply_no_new_goals : list name → tactic name | [] := failed | (c::cs) := (do g::gs ← get_goals, set_goals [g], t ← mk_const c, r ← apply t, all_goals solve_by_elim, a ← r.mmap (λ p, do e ← instantiate_mvars p.2, return e.metavariables.length), guard (a.all (λ n, n = 0)), gs' ← get_goals, set_goals (gs' ++ gs), pure c) <|> any_apply_no_new_goals cs /-- Try to apply any lemma marked with the attributes `@[back]` or `@[back']`. -/ meta def backwards_reasoning : tactic string := do cs ← attribute.get_instances `back', r ← try_core (any_apply_no_new_goals cs), match r with | (some n) := return ("apply " ++ n.to_string ++ " ; solve_by_elim") | none := do cs ← attribute.get_instances `back, n ← any_apply cs <|> fail "no @[back] or @[back'] lemmas could be applied", return ("apply " ++ n.to_string) end attribute [extensionality] subtype.eq -- TODO get from subsingleton.elim? -- @[extensionality] lemma punit_ext (a b : punit.{u₁}) : a = b := begin induction a, induction b, refl end -- @[extensionality] lemma sigma_ext {α : Type u₁} (Z : α → Type u₂) (X Y : Σ a : α, Z a) (w₁ : X.1 = Y.1) (w₂ : @eq.rec_on _ X.1 _ _ w₁ X.2 = Y.2) : X = Y := -- begin -- induction X, induction Y, dsimp at w₁, dsimp at w₂, induction w₁, induction w₂, refl, -- end -- TODO should `apply_instance` be in tidy? If so, these shouldn't be needed. @[back] definition decidable_true : decidable true := is_true dec_trivial @[back] definition decidable_false : decidable false := is_false dec_trivial attribute [back] quotient.mk quotient.sound attribute [back] eqv_gen.rel attribute [back'] Exists.intro
9ab9be0591ace7b5aeb1fa22276c5f9ea8a59c4c
4727251e0cd73359b15b664c3170e5d754078599
/src/data/rat/meta_defs.lean
abff0313e2258c0080c6b3d0a81488f39291ac5c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,425
lean
/- Copyright (c) 2019 Robert Y. Lewis . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.rat.basic import tactic.core /-! # Meta operations on ℚ This file defines functions for dealing with rational numbers as expressions. They are not defined earlier in the hierarchy, in the `tactic` or `meta` folders, since we do not want to import `data.rat.basic` there. ## Main definitions * `rat.mk_numeral` embeds a rational `q` as a numeral expression into a type supporting the needed operations. It does not need a tactic state. * `rat.reflect` specializes `rat.mk_numeral` to `ℚ`. * `expr.of_rat` behaves like `rat.mk_numeral`, but uses the tactic state to infer the needed structure on the target type. * `expr.to_rat` evaluates a normal numeral expression as a rat. * `expr.eval_rat` evaluates a numeral expression with arithmetic operations as a rat. -/ /-- `rat.mk_numeral q` embeds `q` as a numeral expression inside a type with 0, 1, +, -, and / `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. This function is similar to `expr.of_rat` but takes more hypotheses and is not tactic valued. -/ meta def rat.mk_numeral (type has_zero has_one has_add has_neg has_div : expr) : ℚ → expr | ⟨num, denom, _, _⟩ := let nume := num.mk_numeral type has_zero has_one has_add has_neg in if denom = 1 then nume else let dene := denom.mk_numeral type has_zero has_one has_add in `(@has_div.div.{0} %%type %%has_div %%nume %%dene) /-- `rat.reflect q` represents the rational number `q` as a numeral expression of type `ℚ`. -/ protected meta def rat.reflect : ℚ → expr := rat.mk_numeral `(ℚ) `((by apply_instance : has_zero ℚ)) `((by apply_instance : has_one ℚ))`((by apply_instance : has_add ℚ)) `((by apply_instance : has_neg ℚ)) `(by apply_instance : has_div ℚ) section local attribute [semireducible] reflected meta instance : has_reflect ℚ := rat.reflect end /-- `rat.to_pexpr q` creates a `pexpr` that will evaluate to `q`. The `pexpr` does not hold any typing information: `to_expr ``((%%(rat.to_pexpr (3/4)) : K))` will create a native `K` numeral `(3/4 : K)`. -/ meta def rat.to_pexpr (q : ℚ) : pexpr := let n := q.num, d := q.denom in if d = 1 then n.to_pexpr else ``(%%n.to_pexpr / %%d.to_pexpr) /-- Evaluates an expression as a rational number, if that expression represents a numeral or the quotient of two numerals. -/ protected meta def expr.to_nonneg_rat : expr → option ℚ | `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, if c : m.coprime n then if h : 1 < n then return ⟨m, n, lt_trans zero_lt_one h, c⟩ else none else none | e := do n ← e.to_nat, return (rat.of_int n) /-- Evaluates an expression as a rational number, if that expression represents a numeral, the quotient of two numerals, the negation of a numeral, or the negation of the quotient of two numerals. -/ protected meta def expr.to_rat : expr → option ℚ | `(has_neg.neg %%e) := do q ← e.to_nonneg_rat, some (-q) | e := e.to_nonneg_rat /-- Evaluates an expression into a rational number, if that expression is built up from numerals, +, -, *, /, ⁻¹ -/ protected meta def expr.eval_rat : expr → option ℚ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%q) := (*) 2 <$> q.eval_rat | `(bit1 %%q) := (+) 1 <$> (*) 2 <$> q.eval_rat | `(%%a + %%b) := (+) <$> a.eval_rat <*> b.eval_rat | `(%%a - %%b) := has_sub.sub <$> a.eval_rat <*> b.eval_rat | `(%%a * %%b) := (*) <$> a.eval_rat <*> b.eval_rat | `(%%a / %%b) := (/) <$> a.eval_rat <*> b.eval_rat | `(-(%%a)) := has_neg.neg <$> a.eval_rat | `((%%a)⁻¹) := has_inv.inv <$> a.eval_rat | _ := none /-- `expr.of_rat α q` embeds `q` as a numeral expression inside the type `α`. Lean will try to infer the correct type classes on `α`, and the tactic will fail if it cannot. This function is similar to `rat.mk_numeral` but it takes fewer hypotheses and is tactic valued. -/ protected meta def expr.of_rat (α : expr) : ℚ → tactic expr | ⟨(n:ℕ), d, h, c⟩ := do e₁ ← expr.of_nat α n, if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, h, c⟩ := do e₁ ← expr.of_nat α (n+1), e ← (if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂]), tactic.mk_app ``has_neg.neg [e] namespace tactic namespace instance_cache /-- `c.of_rat q` embeds `q` as a numeral expression inside the type `α`. Lean will try to infer the correct type classes on `c.α`, and the tactic will fail if it cannot. This function is similar to `rat.mk_numeral` but it takes fewer hypotheses and is tactic valued. -/ protected meta def of_rat (c : instance_cache) : ℚ → tactic (instance_cache × expr) | ⟨(n:ℕ), d, _, _⟩ := if d = 1 then c.of_nat n else do (c, e₁) ← c.of_nat n, (c, e₂) ← c.of_nat d, c.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, _, _⟩ := do (c, e) ← (if d = 1 then c.of_nat (n+1) else do (c, e₁) ← c.of_nat (n+1), (c, e₂) ← c.of_nat d, c.mk_app ``has_div.div [e₁, e₂]), c.mk_app ``has_neg.neg [e] end instance_cache end tactic
e022716f31e9a28ae9c73ca1b6a8ed83fe0c6eab
63abd62053d479eae5abf4951554e1064a4c45b4
/src/linear_algebra/finsupp.lean
d7c683c26bf5c724797a152573b00370366e75a0
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
24,917
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import data.finsupp.basic import linear_algebra.basic /-! # Properties of the semimodule `α →₀ M` Given an `R`-semimodule `M`, the `R`-semimodule structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, semimodule, linear algebra -/ noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {R : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := { map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a } /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext $ λ a, linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { map_smul' := assume a b, rfl, ..finsupp.eval_add_hom a } section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot_of_injective (single_injective a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right s) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right t) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), map_add' := λ l₁ l₂, filter_add, map_smul' := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l a, by_cases a ∈ s; simp [h], exact ((mem_supported' R l.1).1 l.2 a h).symm end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := begin have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s), rw [restrict_dom_comp_subtype, linear_map.range_id] at this, exact eq_top_mono (submodule.map_mono le_top) this.symm end theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff] theorem supported_inter (s t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty] theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := begin refine ⟨λ h x hx, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩, rw [mem_bot, single_eq_zero] at this, exact hy this end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. We define this as an additive equivalence. For a commutative `R`, this equivalence can be upgraded further to a linear equivalence. -/ def lsum : (α → M →ₗ[R] N) ≃+ ((α →₀ M) →ₗ[R] N) := { to_fun := λ F, { to_fun := λ d, d.sum (λ i, F i), map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add, map_smul' := λ c f, by simp [sum_smul_index', smul_sum] }, inv_fun := λ F x, F.comp (lsingle x), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) : lsum.symm f x = f.comp (lsingle x) := rfl section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.lmap_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_monoid M'] [semimodule R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R (↑s : set α)) : finsupp.total α M R v l = s.sum (λ i, l i • v i) := finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul] @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_unique [unique α] (l : α →₀ R) (v) : finsupp.total α M R v l = l (default α) • v (default α) := by rw [← total_single, ← unique_single l] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _) theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := begin ext l, simp [total_apply], rw sum_map_domain_index; simp [add_smul], end lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl lemma total_on_finset {s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s): finsupp.total α M R g (finsupp.on_finset s f hf) = finset.sum s (λ (x : α), f x • g x) := begin simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset], rw finset.sum_filter_of_ne, intros x hx h, contrapose! h, simp [h], end end total /-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/ protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv (lmap_domain M R e).map_smul @[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m := by simp [finsupp.dom_lcongr, finsupp.dom_congr, map_domain_single] /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) := (finsupp.dom_lcongr e₁).trans { to_fun := map_range e₂ e₂.map_zero, inv_fun := map_range e₂.symm e₂.symm.map_zero, left_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.map_add, map_range_add e₂.symm.map_add, map_range_single, map_range_single, e₂.symm_apply_apply, ih], right_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.symm.map_add, map_range_add e₂.map_add, map_range_single, map_range_single, e₂.apply_symm_apply, ih], map_add' := map_range_add e₂.map_add, map_smul' := λ c f, finsupp.induction f (by rw [smul_zero, map_range_zero, smul_zero]) $ λ a b f ha hb ih, by rw [smul_add, smul_single, map_range_add e₂.map_add, map_range_single, e₂.map_smul, ih, map_range_add e₂.map_add, smul_add, map_range_single, smul_single] } @[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) := by simp [lcongr] end finsupp variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe], apply N.sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), end lemma mem_span_finset {s : finset M} {x : M} : x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x := ⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_iff_total _).1 (show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in ⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩, λ ⟨f, hf⟩, hf ▸ sum_mem _ (λ i hi, smul_mem _ _ $ subset_span hi)⟩
a985079302ae229d15c1f9517416625119c42b66
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/basic.lean
8349487904e637d1e5407f87c9771c7cf259d73c
[ "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
79,127
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, Kevin Buzzard -/ import algebra.pi_instances data.finsupp data.equiv.mul_add order.order_iso /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module.lean`. ## Main definitions * Many constructors for linear maps, including `prod` and `coprod` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends `linear_map` and `equiv`. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `sup_quotient_equiv_quotient_inf`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`prod`, `coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function reserve infix ` ≃ₗ `:25 universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [ring R] [add_comm_group M] [module R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = finset.sum finset.univ (λi:ι, x i • (λj, if i = j then 1 else 0)) := begin ext k, rw pi.finset_sum_apply, have : finset.sum finset.univ (λ (x_1 : ι), x x_1 * ite (k = x_1) 1 0) = x k, by { have := finset.sum_mul_boole finset.univ x k, rwa if_pos (finset.mem_univ _) at this }, rw ← this, apply finset.sum_congr rfl (λl hl, _), simp only [smul_eq_mul, mul_ite, pi.smul_apply], conv_lhs { rw eq_comm } end end namespace linear_map section variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map.is_add_group_hom : is_add_group_hom f := { map_add := f.add } instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : t.sum f b = t.sum (λd, f d b) := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl section variables (R M) include M instance endomorphism_ring : ring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp } end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = finset.sum finset.univ (λi:ι, x i • (f (λj, if i = j then 1 else 0))) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := { to_fun := λ x, (f x, g x), add := λ x y, by simp only [prod.mk_add_mk, map_add], smul := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem prod_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : prod f g x = (f x, g x) := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl] /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr] end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := { to_fun := λ x, f x.1 + g x.2, add := λ x y, by simp only [map_add, prod.snd_add, prod.fst_add]; cc, smul := λ x y, by simp only [smul_add, prod.smul_snd, prod.smul_fst, map_smul] } @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : coprod f g (x, y) = f x + g y := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext ⟨x, y⟩; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl end section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl instance : module R (M →ₗ[R] M₂) := module.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, add := λ m m', by { ext, apply smul_add, }, smul := λ c m, by { ext, apply smul_comm, } }, add := λ f f', by { ext, apply add_smul, }, smul := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map namespace submodule variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := partial_order.lift (coe : submodule R M → set M) (λ a b, ext') (by apply_instance) variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules p and p' satisfy p ⊆ p', then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨by split; try {exact {0}}; simp {contextual := tt}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨by split; try {exact set.univ}; simp⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, ↑s, zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot } instance : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, zero := ⟨0, p.zero_mem, f.map_zero⟩, add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩; exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩, smul := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ } lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.ext' $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, zero := by simp, add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂], smul := λ a x h, by simp [p.smul_mem _ h] } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.ext' rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hdir end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ end lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (span K {x}) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin rw [← union_singleton, span_union, mem_sup], simp [mem_span_singleton, add_comm, add_left_comm], split, { rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ }, { rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ } end lemma mem_span_insert' {y} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem _ i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : span R {m} ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, zero := ⟨zero_mem _, zero_mem _⟩, add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩; exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩, smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := ext' set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] end quotient end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end set_option class.instance_max_depth 40 lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule @[simp] lemma finsupp_sum {R M M₂ γ} [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := (set.ext_iff _ _).1 (range_coe f). @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := begin refine eq_top_iff'.2 (λ x, mem_sup.2 _), rcases x with ⟨x₁, x₂⟩ , have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range, by simp, have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range, by simp, use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂], simp end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0), from ⟨λ h m, h m mem_top, λ h m _, h m⟩, by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rw [map_comap_eq, inf_of_le_right h] lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem map_le_map_iff {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := ⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩ theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h)) theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl end linear_map namespace linear_map variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end linear_map namespace is_linear_map lemma is_linear_map_add {R M : Type*} [ring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [ring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot.2 $ λ x y, subtype.eq' @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] lemma disjoint_iff_comap_eq_bot (p q : submodule R M) : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl /-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/ def map_subtype.order_iso : ((≤) : submodule R p → submodule R p → Prop) ≃o ((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq], ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of M. -/ def map_subtype.le_order_embedding : ((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.le_order_embedding p p' = map p.subtype p' := rfl /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of M. -/ def map_subtype.lt_order_embedding : ((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (map_subtype.le_order_embedding p).lt_embedding_of_le_embedding @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by ext ⟨x, y⟩; simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.order_iso : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o ((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq], ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.le_order_embedding : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.lt_order_embedding : ((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding end submodule section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint doc_blame has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] extends M →ₗ[R] M₂, M ≃ M₂ end infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] theorem coe_apply (e : M ≃ₗ[R] M₂) (b : M) : (e : M →ₗ[R] M₂) b = e b := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[ext] lemma ext {f g : M ≃ₗ[R] M₂} (h : (f : M → M₂) = g) : f = g := to_equiv_injective (equiv.eq_of_to_fun_eq h) section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm (e : M ≃ₗ[R] M₂) : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- Linear equivalences are transitive. -/ @[trans] def trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } /-- A linear equivalence is an additive equivalence. -/ def to_add_equiv (e : M ≃ₗ[R] M₂) : M ≃+ M₂ := { map_add' := e.add, .. e } @[simp] theorem trans_apply (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (e : M ≃ₗ[R] M₂) (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (e : M ≃ₗ[R] M₂) (b : M) : e.symm (e b) = b := e.5 b @[simp] theorem map_add (e : M ≃ₗ[R] M₂) (a b : M) : e (a + b) = e a + e b := e.add a b @[simp] theorem map_zero (e : M ≃ₗ[R] M₂) : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_neg (e : M ≃ₗ[R] M₂) (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (e : M ≃ₗ[R] M₂) (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b @[simp] theorem map_smul (e : M ≃ₗ[R] M₂) (c : R) (x : M) : e (c • x) = c • e x := e.smul c x @[simp] theorem map_eq_zero_iff (e : M ≃ₗ[R] M₂) {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff (e : M ≃ₗ[R] M₂) {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm (e : M ≃ₗ[R] M₂) : e.symm.symm = e := by { cases e, refl } @[simp] theorem symm_symm_apply (e : M ≃ₗ[R] M₂) (x : M) : e.symm.symm x = e x := by { cases e, refl } protected lemma bijective (e : M ≃ₗ[R] M₂) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : M ≃ₗ[R] M₂) : function.injective e := e.to_equiv.injective protected lemma surjective (e : M ≃ₗ[R] M₂) : function.surjective e := e.to_equiv.surjective section prod variables [add_comm_group M₄] [module R M₄] /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { add := λ x y, prod.ext (e.map_add _ _) (e'.map_add _ _), smul := λ c x, prod.ext (e.map_smul c _) (e'.map_smul c _), .. equiv.prod_congr e.to_equiv e'.to_equiv } lemma prod_symm (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) : (e.prod e').symm = e.symm.prod e'.symm := rfl @[simp] lemma prod_apply (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) (p) : e.prod e' p = (e p.1, e' p.2) := rfl @[simp, move_cast] lemma coe_prod (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) : (e.prod e' : (M × M₃) →ₗ[R] M₂ × M₄) = (e : M →ₗ[R] M₂).prod_map (e' : M₃ →ₗ[R] M₄) := rfl /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e.symm p.1, e'.symm (p.2 - f (e.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e' : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) (f : M →ₗ[R] M₄) (x) : e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (e : M ≃ₗ[R] M₂) (e' : M₃ ≃ₗ[R] M₄) (f : M →ₗ[R] M₄) (x) : (e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl end prod /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (f : M →ₗ[R] M₂) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := { ..f, ..@equiv.of_bijective _ _ f ⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ } @[simp] theorem of_bijective_apply (f : M →ₗ[R] M₂) {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem ker (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot.2 f.to_equiv.injective @[simp] protected theorem range (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 f.to_equiv.surjective /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (p : submodule R M) (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply (p : submodule R M) {h} (x : p) : of_top p h x = x := rfl @[simp] theorem of_top_symm_apply (p : submodule R M) {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl lemma eq_bot_of_equiv (p : submodule R M) (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), have := e.symm_apply_apply ⟨b, hb⟩, rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[R] (⊥ : submodule R M₂)) ⟨b, hb⟩), ← e.symm.coe_apply, linear_map.map_zero] at this, exact congr_arg (coe : p → M) this.symm end end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open linear_map set_option class.instance_max_depth 39 /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, e₂.to_linear_map.comp $ f.comp e₁.symm.to_linear_map, inv_fun := λ f, e₂.symm.to_linear_map.comp $ f.comp e₁.to_linear_map, left_inv := λ f, by { ext x, unfold_coes, change e₂.inv_fun (e₂.to_fun $ f.to_fun $ e₁.inv_fun $ e₁.to_fun x) = _, rw [e₁.left_inv, e₂.left_inv] }, right_inv := λ f, by { ext x, unfold_coes, change e₂.to_fun (e₂.inv_fun $ f.to_fun $ e₁.to_fun $ e₁.inv_fun x) = _, rw [e₁.right_inv, e₂.right_inv] }, add := λ f g, by { ext x, change e₂.to_fun ((f + g) (e₁.inv_fun x)) = _, rw [linear_map.add_apply, e₂.add], refl }, smul := λ c f, by { ext x, change e₂.to_fun ((c • f) (e₁.inv_fun x)) = _, rw [linear_map.smul_apply, e₂.smul], refl } } /-- If M₂ and M₃ are linearly isomorphic then the two spaces of linear maps from M into M₂ and M into M₃ are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If M and M₂ are linearly isomorphic then the two spaces of linear maps from M and M₂ to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variable (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha end field end linear_equiv namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply submodule.smul _ _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply submodule.add _ h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, add := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, smul := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { add := h.add, smul := h.smul, .. e} end equiv namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right, let F : f.ker.quotient →ₗ[R] f.range := f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩) (λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in { inv_fun := λx, submodule.quotient.mk (classical.some (hr x)), left_inv := by rintro ⟨x⟩; exact (submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $ classical.some_spec $ hr $ F $ submodule.quotient.mk x), right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x), .. F } open submodule /-- Canonical linear map from the quotient p/(p ∩ p') to (p+p')/p', mapping x + (p ∩ p') to x + p', where p and p' are submodules of an ambient module. -/ def sup_quotient_to_quotient_inf (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf le_sup_left (le_refl _)) end set_option class.instance_max_depth 41 /-- Second Isomorphism Law : the canonical map from p/(p ∩ p') to (p+p')/p' as a linear isomorphism. -/ noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := { .. sup_quotient_to_quotient_inf p p', .. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from @equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin constructor, { rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ }, rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end } section prod lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables {φ : ι → Type i} variables [∀i, add_comm_group (φ i)] [∀i, module R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'], ext b ⟨j, hj⟩, refl }, { ext ⟨b, hb⟩, apply subtype.coe_ext.2, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { rw [dif_pos h], refl }, { rw [dif_neg h], exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot.2 $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne R φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show I.sum (λi, std_basis R φ i (b i)) = b, { ext i, rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $ linear_map.mem_range.2 ⟨_, rfl⟩) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [← finset.mem_coe, finset.coe_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : group (general_linear_group R M) := by delta general_linear_group; apply_instance instance : inhabited (general_linear_group R M) := ⟨1⟩ /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, begin delta to_linear_equiv of_linear_equiv, cases f with f f_inv, cases f, cases f_inv, congr end, right_inv := λ f, begin delta to_linear_equiv of_linear_equiv, cases f, congr end, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : ((general_linear_equiv R M).to_equiv f).to_linear_map = f.val := by {ext, refl} end general_linear_group end linear_map
46611cf0652e7c66d98b3f77fcde4da8674f70cb
0030aab32adb6325aa93cc2051c443945934d083
/src/main.lean
aae572f944b8ffae4ba86bfb968e024fdf7640a9
[]
no_license
JasonKYi/sylvester
914e1abe9c82a3ab4edec15ef58faa8f31921d8f
dfa7a2f323cf9db5fca0a3b8f852b3b9a058bc56
refs/heads/main
1,682,286,953,450
1,620,149,451,000
1,620,149,451,000
362,582,788
0
0
null
null
null
null
UTF-8
Lean
false
false
11,855
lean
import linear_algebra.quadratic_form import analysis.special_functions.pow /- Sylvester's law of inertia: - We would like to prove the complex version first: A quadratic form `Q` over the field `R` is isometric to a quadratic form in the form ` ∑ xᵢ^2 ` The idea is we would like to expand the API for `quadratic_form.equivalent`. Given a orthogonal basis wrt. some quadratic form, we should have a equivalent form. This will be constructed. -/ open_locale big_operators classical variables {R : Type*} [ring R] variables {R₁ : Type*} [comm_ring R₁] [invertible (2 : R₁)] variables {M : Type*} [add_comm_group M] [module R M] [module R₁ M] variables {M₁ : Type*} [add_comm_group M₁] [module R M₁] variables {ι : Type*} [fintype ι] {v : ι → M} -- Should be a def since it takes a parameter def field.invertible {K : Type*} [field K] {z : K} (hz : z ≠ 0) : invertible z := { inv_of := z⁻¹, inv_of_mul_self := inv_mul_cancel hz, mul_inv_of_self := mul_inv_cancel hz } lemma is_basis.smul_of_invertible {v : ι → M} (hv : is_basis R v) {w : ι → R} (hw : ∀ i : ι, invertible (w i)) : is_basis R (λ i, w i • v i) := begin obtain ⟨hw₁', hw₁''⟩ := hv, split, { rw linear_independent_iff'' at hw₁' ⊢, intros s g hgs hsum i, have hw₁ : g i * w i = 0 := hw₁' s (λ i, g i • w i) _ _ i, { suffices : g i * w i * (hw i).inv_of = 0, rwa [mul_assoc, mul_inv_of_self, mul_one] at this, rw [hw₁, zero_mul] }, { intros i hi, simp only [algebra.id.smul_eq_mul, hgs i hi, zero_smul] }, { rw [← hsum, finset.sum_congr rfl _], intros, simp only [smul_assoc] } }, { rw eq_top_iff, intros j hj, rw ← hw₁'' at hj, rw submodule.mem_span at hj ⊢, refine λ p hp, hj p (λ u hu, _), obtain ⟨i, rfl⟩ := hu, have := p.smul_mem (⅟ (w i)) (hp ⟨i, rfl⟩), simp only [← smul_assoc, smul_eq_mul, inv_of_mul_self, one_smul] at this, exact this } end namespace quadratic_form open finset bilin_form /-- A quadratic form composed with a `linear_equiv` is isometric to itself. -/ def isometry_of_comp_linear_equiv (Q : quadratic_form R M) (f : M₁ ≃ₗ[R] M) : Q.isometry (Q.comp (f : M₁ →ₗ[R] M)) := { map_app' := begin intro, simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.to_fun_eq_coe, linear_equiv.apply_symm_apply, f.apply_symm_apply], end, .. f.symm } /-- Given a quadratic form `Q` and a basis, `of_is_basis` is the basis representation of `Q`. -/ noncomputable def of_is_basis (Q : quadratic_form R M) (hv₁ : is_basis R v) : quadratic_form R (ι → R) := Q.comp hv₁.equiv_fun.symm @[simp] lemma isometry_of_is_basis_apply (Q : quadratic_form R M) (hv₁ : is_basis R v) (w : ι → R) : Q.of_is_basis hv₁ w = Q (∑ i : ι, w i • v i) := by { rw ← hv₁.equiv_fun_symm_apply, refl } /-- A quadratic form is isometric to its bases representations. -/ noncomputable def isometry_of_is_basis (Q : quadratic_form R M) (hv₁ : is_basis R v) : isometry Q (Q.of_is_basis hv₁) := isometry_of_comp_linear_equiv Q hv₁.equiv_fun.symm lemma isometry_of_is_Ortho_apply [invertible (2 : R₁)] (Q : quadratic_form R₁ M) (hv₁ : is_basis R₁ v) (hv₂ : (associated Q).is_Ortho v) (w : ι → R₁) : Q.of_is_basis hv₁ w = ∑ i : ι, associated Q (v i) (v i) * w i * w i := begin rw [isometry_of_is_basis_apply, ← @associated_eq_self_apply R₁, sum_left], refine sum_congr rfl (λ j hj, _), rw [sum_right, sum_eq_single j], { rw [smul_left, smul_right], ring }, { intros i _ hij, rw [smul_left, smul_right, show (associated_hom R₁) Q (v j) (v i) = 0, by exact hv₂ i j hij, mul_zero, mul_zero] }, { contradiction } end /-- The weighted sum of squares with respect some weight as a quadratic form. -/ def weighted_sum_squares (w : ι → R₁) : quadratic_form R₁ (ι → R₁) := ∑ i : ι, w i • proj i i @[simp] lemma weighted_sum_squares_apply (w v : ι → R₁) : weighted_sum_squares w v = ∑ i : ι, w i * (v i * v i) := quadratic_form.sum_apply _ _ _ variables {V : Type*} {K : Type*} [field K] [invertible (2 : K)] variables [add_comm_group V] [module K V] [finite_dimensional K V] lemma equivalent_weighted_sum_squares_of_nondegenerate' (Q : quadratic_form K V) (hQ : (associated Q).nondegenerate) : ∃ w : fin (finite_dimensional.finrank K V) → K, (∀ i, w i ≠ 0) ∧ equivalent Q (weighted_sum_squares w) := begin obtain ⟨v, hv₁, hv₂, hv₃⟩ := exists_orthogonal_basis' hQ associated_is_sym, refine ⟨λ i, associated Q (v i) (v i), hv₃, _⟩, refine nonempty.intro _, convert Q.isometry_of_is_basis hv₂, ext w, rw [isometry_of_is_Ortho_apply Q hv₂ hv₁, weighted_sum_squares_apply], refine finset.sum_congr rfl _, intros, rw ← mul_assoc, end lemma equivalent_weighted_sum_squares_of_nondegenerate (Q : quadratic_form K V) (hQ : (associated Q).nondegenerate) : ∃ w : fin (finite_dimensional.finrank K V) → K, equivalent Q (weighted_sum_squares w) := let ⟨w, _, hw₂⟩ := Q.equivalent_weighted_sum_squares_of_nondegenerate' hQ in ⟨w, hw₂⟩ section complex /-- The isometry between a weighted sum of squares on the complex numbers and the sum of squares, i.e. `weighted_sum_squares` with weight `λ i : ι, 1`. -/ noncomputable def isometry_sum_squares [decidable_eq ι] (w : ι → ℂ) (hw : ∀ i : ι, w i ≠ 0) : isometry (weighted_sum_squares w) (weighted_sum_squares (λ _, 1 : ι → ℂ)) := begin have hw' : ∀ i : ι, (w i) ^ - (1 / 2 : ℂ) ≠ 0, { intros i hi, exact hw i ((complex.cpow_eq_zero_iff _ _).1 hi).1 }, convert (weighted_sum_squares w).isometry_of_is_basis (is_basis.smul_of_invertible (pi.is_basis_fun ℂ ι) (λ i, field.invertible (hw' i))), ext1 v, rw [isometry_of_is_basis_apply, weighted_sum_squares_apply, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), have hsum : (∑ (i : ι), v i • w i ^ - (1 / 2 : ℂ) • (linear_map.std_basis ℂ (λ (i : ι), ℂ) i) 1) j = v j • w j ^ - (1 / 2 : ℂ), { rw [finset.sum_apply, sum_eq_single j, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one], intros i _ hij, rw [linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul, mul_zero, mul_zero], intro hj', exact false.elim (hj' hj) }, rw [hsum, smul_eq_mul], suffices : 1 * v j * v j = w j ^ - (1 / 2 : ℂ) * w j ^ - (1 / 2 : ℂ) * w j * v j * v j, { rw [← mul_assoc, this], ring }, rw [← complex.cpow_add _ _ (hw j), show - (1 / 2 : ℂ) + - (1 / 2) = -1, by ring, complex.cpow_neg_one, inv_mul_cancel (hw j)], end . /-- A nondegenerate quadratic form on the complex numbers is equivalent to the sum of squares, i.e. `weighted_sum_squares` with weight `λ i : ι, 1`. -/ theorem equivalent_sum_squares {M : Type*} [add_comm_group M] [module ℂ M] [finite_dimensional ℂ M] (Q : quadratic_form ℂ M) (hQ : (associated Q).nondegenerate) : equivalent Q (weighted_sum_squares (λ _, 1 : fin (finite_dimensional.finrank ℂ M) → ℂ)) := let ⟨w, hw₁, hw₂⟩ := Q.equivalent_weighted_sum_squares_of_nondegenerate' hQ in nonempty.intro $ (classical.choice hw₂).trans (isometry_sum_squares w hw₁) end complex section real /-- The sign function that maps negative real numbers to -1 and nonnegative numbers to 1. -/ noncomputable def sign (r : ℝ) : ℝ := if r < 0 then -1 else 1 lemma sign_apply_eq (r : ℝ) : sign r = -1 ∨ sign r = 1 := begin by_cases r < 0, { exact or.intro_left _ (if_pos h) }, { exact or.intro_right _ (if_neg h) } end lemma sign_mul_nonneg (r : ℝ) : 0 ≤ sign r * r := begin by_cases r < 0, { rw [sign, if_pos h], exact mul_nonneg_of_nonpos_of_nonpos (by norm_num) (le_of_lt h) }, { rw [sign, if_neg h, one_mul], exact not_lt.1 h } end lemma sign_mul_ne_zero_pos (r : ℝ) (hr : r ≠ 0) : 0 < sign r * r := begin refine lt_of_le_of_ne (sign_mul_nonneg r) (λ h, _), rw zero_eq_mul at h, cases sign_apply_eq r with hneg hpos; cases h; { linarith <|> exact hr h } end lemma sign_inv_eq_self (r : ℝ) : (sign r)⁻¹ = sign r := begin cases sign_apply_eq r with h h, { rw h, norm_num }, { rw h, exact inv_one } end /-- The isometry between a weighted sum of squares with weights `u` on the complex numbers and the weighted sum of squares with weights `sign ∘ u`. -/ noncomputable def isometry_sign_weighted_sum_squares' [decidable_eq ι] (u : ι → ℝ) (hu : ∀ i : ι, u i ≠ 0) : isometry (weighted_sum_squares u) (weighted_sum_squares (sign ∘ u)) := begin have hu' : ∀ i : ι, 0 ≠ (sign (u i) * u i) ^ - (1 / 2 : ℝ), { intro i, exact ne_of_lt (real.rpow_pos_of_pos (sign_mul_ne_zero_pos _ (hu i)) _) }, convert ((weighted_sum_squares u).isometry_of_is_basis (is_basis.smul_of_invertible (pi.is_basis_fun ℝ ι) (λ i, field.invertible (hu' i).symm))), ext1 v, rw [isometry_of_is_basis_apply, weighted_sum_squares_apply, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), have hsum : (∑ (i : ι), v i • (sign (u i) * u i) ^ - (1 / 2 : ℝ) • (linear_map.std_basis ℝ (λ (i : ι), ℝ) i) 1) j = v j • (sign (u j) * u j) ^ - (1 / 2 : ℝ), { rw [finset.sum_apply, sum_eq_single j, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one], intros i _ hij, rw [linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul, mul_zero, mul_zero], intro hj', exact false.elim (hj' hj) }, rw [hsum, smul_eq_mul], suffices : (sign ∘ u) j * v j * v j = (sign (u j) * u j) ^ - (1 / 2 : ℝ) * (sign (u j) * u j) ^ - (1 / 2 : ℝ) * u j * v j * v j, { rw [← mul_assoc, this], ring }, rw [← real.rpow_add (sign_mul_ne_zero_pos _ (hu j)), show - (1 / 2 : ℝ) + - (1 / 2) = -1, by ring, real.rpow_neg_one, mul_inv', sign_inv_eq_self, mul_assoc (sign (u j)) (u j)⁻¹, inv_mul_cancel (hu j), mul_one], end /-- Sylvester's law of inertia: A nondegenerate real quadratic form is equivalent to a weighted sum of squares with the weights being ±1. -/ theorem equivalent_one_neg_one_weighted_sum_squared {M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M] (Q : quadratic_form ℝ M) (hQ : (associated Q).nondegenerate) : ∃ w : fin (finite_dimensional.finrank ℝ M) → ℝ, (∀ i, w i = -1 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares w) := let ⟨w, hw₁, hw₂⟩ := Q.equivalent_weighted_sum_squares_of_nondegenerate' hQ in ⟨sign ∘ w, λ i, sign_apply_eq (w i), hw₂.trans (nonempty.intro $ isometry_sign_weighted_sum_squares' w hw₁)⟩ end real -- The idea now is to restrict a degenerate quadratic form onto a smaller subspace -- such that it becomes nondegenerate. -- def restrict_nezero (Q : quadratic_form R₁ M) : submodule R₁ M := -- { carrier := { v : M | v ≠ 0 → Q v ≠ 0 }, -- zero_mem' := by contradiction, -- add_mem' := -- begin -- intros x y hx hy hxy, -- rw [← @associated_eq_self_apply R₁ _ _ _ _ _ _ _ _ _ (x + y), -- add_left, add_right, add_right], -- swap, apply_instance, swap, apply_instance, -- by_cases h₁ : x = 0; by_cases h₂ : y = 0, -- { exact false.elim (hxy (h₁.symm ▸ h₂.symm ▸ zero_add _)) }, -- { subst h₁, simp only [zero_left, zero_right, zero_add], -- rw associated_eq_self_apply, exact hy h₂ }, -- { -- } -- end, -- smul_mem' := _ } end quadratic_form
accfd0519b9d4d640b2ea7b59d2c534b390cb8bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/CommMon_.lean
949b2ac4e0357cc06776613fc0383773cf5e3b15
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,492
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.monoidal.braided import category_theory.monoidal.Mon_ /-! # The category of commutative monoids in a braided monoidal category. -/ universes v₁ v₂ u₁ u₂ u open category_theory open category_theory.monoidal_category variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] [braided_category.{v₁} C] /-- A commutative monoid object internal to a monoidal category. -/ structure CommMon_ extends Mon_ C := (mul_comm' : (β_ _ _).hom ≫ mul = mul . obviously) restate_axiom CommMon_.mul_comm' attribute [simp, reassoc] CommMon_.mul_comm namespace CommMon_ /-- The trivial commutative monoid object. We later show this is initial in `CommMon_ C`. -/ @[simps] def trivial : CommMon_ C := { mul_comm' := begin dsimp, rw [braiding_left_unitor, unitors_equal], end ..Mon_.trivial C } instance : inhabited (CommMon_ C) := ⟨trivial C⟩ variables {C} {M : CommMon_ C} instance : category (CommMon_ C) := induced_category.category CommMon_.to_Mon_ @[simp] lemma id_hom (A : CommMon_ C) : Mon_.hom.hom (𝟙 A) = 𝟙 A.X := rfl @[simp] lemma comp_hom {R S T : CommMon_ C} (f : R ⟶ S) (g : S ⟶ T) : Mon_.hom.hom (f ≫ g) = f.hom ≫ g.hom := rfl section variables (C) /-- The forgetful functor from commutative monoid objects to monoid objects. -/ @[derive [full, faithful]] def forget₂_Mon_ : CommMon_ C ⥤ Mon_ C := induced_functor CommMon_.to_Mon_ @[simp] lemma forget₂_Mon_obj_one (A : CommMon_ C) : ((forget₂_Mon_ C).obj A).one = A.one := rfl @[simp] lemma forget₂_Mon_obj_mul (A : CommMon_ C) : ((forget₂_Mon_ C).obj A).mul = A.mul := rfl @[simp] lemma forget₂_Mon_map_hom {A B : CommMon_ C} (f : A ⟶ B) : ((forget₂_Mon_ C).map f).hom = f.hom := rfl end instance unique_hom_from_trivial (A : CommMon_ C) : unique (trivial C ⟶ A) := Mon_.unique_hom_from_trivial A.to_Mon_ open category_theory.limits instance : has_initial (CommMon_ C) := has_initial_of_unique (trivial C) end CommMon_ namespace category_theory.lax_braided_functor variables {C} {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] [braided_category.{v₂} D] /-- A lax braided functor takes commutative monoid objects to commutative monoid objects. That is, a lax braided functor `F : C ⥤ D` induces a functor `CommMon_ C ⥤ CommMon_ D`. -/ @[simps] def map_CommMon (F : lax_braided_functor C D) : CommMon_ C ⥤ CommMon_ D := { obj := λ A, { mul_comm' := begin dsimp, have := F.braided, slice_lhs 1 2 { rw ←this, }, slice_lhs 2 3 { rw [←category_theory.functor.map_comp, A.mul_comm], }, end, ..F.to_lax_monoidal_functor.map_Mon.obj A.to_Mon_ }, map := λ A B f, F.to_lax_monoidal_functor.map_Mon.map f, } variables (C) (D) /-- `map_CommMon` is functorial in the lax braided functor. -/ def map_CommMon_functor : (lax_braided_functor C D) ⥤ (CommMon_ C ⥤ CommMon_ D) := { obj := map_CommMon, map := λ F G α, { app := λ A, { hom := α.app A.X, } } } end category_theory.lax_braided_functor namespace CommMon_ open category_theory.lax_braided_functor namespace equiv_lax_braided_functor_punit /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def lax_braided_to_CommMon : lax_braided_functor (discrete punit.{u+1}) C ⥤ CommMon_ C := { obj := λ F, (F.map_CommMon : CommMon_ _ ⥤ CommMon_ C).obj (trivial (discrete punit)), map := λ F G α, ((map_CommMon_functor (discrete punit) C).map α).app _ } /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def CommMon_to_lax_braided : CommMon_ C ⥤ lax_braided_functor (discrete punit.{u+1}) C := { obj := λ A, { obj := λ _, A.X, map := λ _ _ _, 𝟙 _, ε := A.one, μ := λ _ _, A.mul, map_id' := λ _, rfl, map_comp' := λ _ _ _ _ _, (category.id_comp (𝟙 A.X)).symm, }, map := λ A B f, { app := λ _, f.hom, naturality' := λ _ _ _, by { dsimp, rw [category.id_comp, category.comp_id], }, unit' := f.one_hom, tensor' := λ _ _, f.mul_hom, }, } local attribute [tidy] tactic.discrete_cases local attribute [simp] eq_to_iso_map /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def unit_iso : 𝟭 (lax_braided_functor (discrete punit.{u+1}) C) ≅ lax_braided_to_CommMon C ⋙ CommMon_to_lax_braided C := nat_iso.of_components (λ F, lax_braided_functor.mk_iso (monoidal_nat_iso.of_components (λ _, F.to_lax_monoidal_functor.to_functor.map_iso (eq_to_iso (by ext))) (by tidy) (by tidy) (by tidy))) (by tidy) /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def counit_iso : CommMon_to_lax_braided C ⋙ lax_braided_to_CommMon C ≅ 𝟭 (CommMon_ C) := nat_iso.of_components (λ F, { hom := { hom := 𝟙 _, }, inv := { hom := 𝟙 _, } }) (by tidy) end equiv_lax_braided_functor_punit open equiv_lax_braided_functor_punit local attribute [simp] eq_to_iso_map /-- Commutative monoid objects in `C` are "just" braided lax monoidal functors from the trivial braided monoidal category to `C`. -/ @[simps] def equiv_lax_braided_functor_punit : lax_braided_functor (discrete punit.{u+1}) C ≌ CommMon_ C := { functor := lax_braided_to_CommMon C, inverse := CommMon_to_lax_braided C, unit_iso := unit_iso C, counit_iso := counit_iso C, } end CommMon_
6b8b1fa6a7f731199cd14b91fec52e3253cf22ac
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/meta/rb_map.lean
25857e9114657607ca0ef0f6d0d25e76d4b0210e
[ "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
7,192
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import data.option.defs import data.list.defs /-! # rb_map This file defines additional operations on native rb_maps and rb_sets. These structures are defined in core in `init.meta.rb_map`. They are meta objects, and are generally the most efficient dictionary structures to use for pure metaprogramming right now. -/ namespace native /-! ### Declarations about `rb_set` -/ namespace rb_set meta instance {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_set key) := ⟨mk_rb_set⟩ /-- `filter s P` returns the subset of elements of `s` satisfying `P`. -/ meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter s P` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union {key} (s t : rb_set key) : rb_set key := s.fold t (λ a t, t.insert a) /-- `of_list_core empty l` turns a list of keys into an `rb_set`. It takes a user_provided `rb_set` to use for the base case. This can be used to pre-seed the set with additional elements, and/or to use a custom comparison operator. -/ meta def of_list_core {key} (base : rb_set key) : list key → rb_map key unit | [] := base | (x::xs) := rb_set.insert (of_list_core xs) x /-- `of_list l` transforms a list `l : list key` into an `rb_set`, inferring an order on the type `key`. -/ meta def of_list {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list key → rb_set key := of_list_core mk_rb_set /-- `sdiff s1 s2` returns the set of elements that are in `s1` but not in `s2`. It does so by folding over `s2`. If `s1` is significantly smaller than `s2`, it may be worth it to reverse the fold. -/ meta def sdiff {α} (s1 s2 : rb_set α) : rb_set α := s2.fold s1 $ λ v s, s.erase v /-- `insert_list s l` inserts each element of `l` into `s`. -/ meta def insert_list {key} (s : rb_set key) (l : list key) : rb_set key := l.foldl rb_set.insert s end rb_set /-! ### Declarations about `rb_map` -/ namespace rb_map meta instance {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_map key data) := ⟨mk_rb_map⟩ /-- `find_def default m k` returns the value corresponding to `k` in `m`, if it exists. Otherwise it returns `default`. -/ meta def find_def {key value} (default : value) (m : rb_map key value) (k : key) := (m.find k).get_or_else default /-- `ifind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns the default value of `value`. -/ meta def ifind {key value} [inhabited value] (m : rb_map key value) (k : key) : value := (m.find k).iget /-- `zfind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns 0. -/ meta def zfind {key value} [has_zero value] (m : rb_map key value) (k : key) : value := (m.find k).get_or_else 0 /-- Returns the pointwise sum of `m1` and `m2`, treating nonexistent values as 0. -/ meta def add {key value} [has_add value] [has_zero value] [decidable_eq value] (m1 m2 : rb_map key value) : rb_map key value := m1.fold m2 (λ n v m, let nv := v + m2.zfind n in if nv = 0 then m.erase n else m.insert n nv) variables {m : Type → Type*} [monad m] open function /-- `mfilter P s` filters `s` by the monadic predicate `P` on keys and values. -/ meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) := rb_map.of_list <$> s.to_list.mfilter (uncurry P) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') := rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b) /-- `scale b m` multiplies every value in `m` by `b`. -/ meta def scale {key value} [has_lt key] [decidable_rel ((<) : key → key → Prop)] [has_mul value] (b : value) (m : rb_map key value) : rb_map key value := m.map ((*) b) section open format prod variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data] private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format := do fk ← tactic.pp k, fd ← tactic.pp d, return $ (if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd meta instance : has_to_tactic_format (rb_map key data) := ⟨λ m, do (fmt, _) ← fold m (return (to_fmt "", tt)) (λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)), return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩ end end rb_map /-! ### Declarations about `rb_lmap` -/ namespace rb_lmap meta instance (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : inhabited (rb_lmap key data) := ⟨rb_lmap.mk _ _⟩ /-- Construct a rb_lmap from a list of key-data pairs -/ protected meta def of_list {key : Type} {data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data | [] := rb_lmap.mk key data | ((k, v)::ls) := (of_list ls).insert k v /-- Returns the list of values of an `rb_lmap`. -/ protected meta def values {key data} (m : rb_lmap key data) : list data := m.fold [] (λ _, (++)) end rb_lmap end native /-! ### Declarations about `name_set` -/ namespace name_set meta instance : inhabited name_set := ⟨mk_name_set⟩ /-- `filter P s` returns the subset of elements of `s` satisfying `P`. -/ meta def filter (P : name → bool) (s : name_set) : name_set := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter P s` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set := s.fold (pure mk_name_set) (λ a m, do x ← m, b ← f a, (pure $ x.insert b)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union (s t : name_set) : name_set := s.fold t (λ a t, t.insert a) /-- `insert_list s l` inserts every element of `l` into `s`. -/ meta def insert_list (s : name_set) (l : list name) : name_set := l.foldr (λ n s', s'.insert n) s end name_set /-! ### Declarations about `name_map` -/ namespace name_map meta instance {data : Type} : inhabited (name_map data) := ⟨mk_name_map⟩ end name_map
b5751d663919ee4f50e87f2cedcc20287f227419
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/tensor_algebra/basic.lean
4df29b1a0274859f8a9bfba568c000e279a20c48
[ "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,349
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import algebra.free_algebra import algebra.ring_quot import algebra.triv_sq_zero_ext import algebra.algebra.operations /-! # Tensor Algebras Given a commutative semiring `R`, and an `R`-module `M`, we construct the tensor algebra of `M`. This is the free `R`-algebra generated (`R`-linearly) by the module `M`. ## Notation 1. `tensor_algebra R M` is the tensor algebra itself. It is endowed with an R-algebra structure. 2. `tensor_algebra.ι R` is the canonical R-linear map `M → tensor_algebra R M`. 3. Given a linear map `f : M → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an `R`-algebra morphism `tensor_algebra R M → A`. ## Theorems 1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`. 2. `lift_unique` states that whenever an R-algebra morphism `g : tensor_algebra R M → A` is given whose composition with `ι R` is `f`, then one has `g = lift R f`. 3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem. 4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift of the composition of an algebra morphism with `ι` is the algebra morphism itself. ## Implementation details As noted above, the tensor algebra of `M` is constructed as the free `R`-algebra generated by `M`, modulo the additional relations making the inclusion of `M` into an `R`-linear map. -/ variables (R : Type*) [comm_semiring R] variables (M : Type*) [add_comm_monoid M] [module R M] namespace tensor_algebra /-- An inductively defined relation on `pre R M` used to force the initial algebra structure on the associated quotient. -/ inductive rel : free_algebra R M → free_algebra R M → Prop -- force `ι` to be linear | add {a b : M} : rel (free_algebra.ι R (a+b)) (free_algebra.ι R a + free_algebra.ι R b) | smul {r : R} {a : M} : rel (free_algebra.ι R (r • a)) (algebra_map R (free_algebra R M) r * free_algebra.ι R a) end tensor_algebra /-- The tensor algebra of the module `M` over the commutative semiring `R`. -/ @[derive [inhabited, semiring, algebra R]] def tensor_algebra := ring_quot (tensor_algebra.rel R M) namespace tensor_algebra instance {S : Type*} [comm_ring S] [module S M] : ring (tensor_algebra S M) := ring_quot.ring (rel S M) variables {M} /-- The canonical linear map `M →ₗ[R] tensor_algebra R M`. -/ def ι : M →ₗ[R] (tensor_algebra R M) := { to_fun := λ m, (ring_quot.mk_alg_hom R _ (free_algebra.ι R m)), map_add' := λ x y, by { rw [←alg_hom.map_add], exact ring_quot.mk_alg_hom_rel R rel.add, }, map_smul' := λ r x, by { rw [←alg_hom.map_smul], exact ring_quot.mk_alg_hom_rel R rel.smul, } } lemma ring_quot_mk_alg_hom_free_algebra_ι_eq_ι (m : M) : ring_quot.mk_alg_hom R (rel R M) (free_algebra.ι R m) = ι R m := rfl /-- Given a linear map `f : M → A` where `A` is an `R`-algebra, `lift R f` is the unique lift of `f` to a morphism of `R`-algebras `tensor_algebra R M → A`. -/ @[simps symm_apply] def lift {A : Type*} [semiring A] [algebra R A] : (M →ₗ[R] A) ≃ (tensor_algebra R M →ₐ[R] A) := { to_fun := ring_quot.lift_alg_hom R ∘ λ f, ⟨free_algebra.lift R ⇑f, λ x y (h : rel R M x y), by induction h; simp [algebra.smul_def]⟩, inv_fun := λ F, F.to_linear_map.comp (ι R), left_inv := λ f, by { ext, simp [ι], }, right_inv := λ F, by { ext, simp [ι], } } variables {R} @[simp] theorem ι_comp_lift {A : Type*} [semiring A] [algebra R A] (f : M →ₗ[R] A) : (lift R f).to_linear_map.comp (ι R) = f := (lift R).symm_apply_apply f @[simp] theorem lift_ι_apply {A : Type*} [semiring A] [algebra R A] (f : M →ₗ[R] A) (x) : lift R f (ι R x) = f x := by { dsimp [lift, ι], refl, } @[simp] theorem lift_unique {A : Type*} [semiring A] [algebra R A] (f : M →ₗ[R] A) (g : tensor_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R f := (lift R).symm_apply_eq -- Marking `tensor_algebra` irreducible makes `ring` instances inaccessible on quotients. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. attribute [irreducible] ι lift @[simp] theorem lift_comp_ι {A : Type*} [semiring A] [algebra R A] (g : tensor_algebra R M →ₐ[R] A) : lift R (g.to_linear_map.comp (ι R)) = g := by { rw ←lift_symm_apply, exact (lift R).apply_symm_apply g } /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {A : Type*} [semiring A] [algebra R A] {f g : tensor_algebra R M →ₐ[R] A} (w : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g := begin rw [←lift_symm_apply, ←lift_symm_apply] at w, exact (lift R).symm.injective w, end /-- If `C` holds for the `algebra_map` of `r : R` into `tensor_algebra R M`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `tensor_algebra R M`. -/ -- This proof closely follows `free_algebra.induction` @[elab_as_eliminator] lemma induction {C : tensor_algebra R M → Prop} (h_grade0 : ∀ r, C (algebra_map R (tensor_algebra R M) r)) (h_grade1 : ∀ x, C (ι R x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : tensor_algebra R M) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from M let s : subalgebra R (tensor_algebra R M) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : M →ₗ[R] s := (ι R).cod_restrict s.to_submodule h_grade1, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (tensor_algebra R M) = s.val.comp (lift R of), { ext, simp [of], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift R of a), exact alg_hom.congr_fun of_id a, end /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : tensor_algebra R M →ₐ[R] R := lift R (0 : M →ₗ[R] R) variables (M) lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ tensor_algebra R M) := λ x, by simp [algebra_map_inv] @[simp] lemma algebra_map_inj (x y : R) : algebra_map R (tensor_algebra R M) x = algebra_map R (tensor_algebra R M) y ↔ x = y := (algebra_map_left_inverse M).injective.eq_iff @[simp] lemma algebra_map_eq_zero_iff (x : R) : algebra_map R (tensor_algebra R M) x = 0 ↔ x = 0 := map_eq_zero_iff (algebra_map _ _) (algebra_map_left_inverse _).injective @[simp] lemma algebra_map_eq_one_iff (x : R) : algebra_map R (tensor_algebra R M) x = 1 ↔ x = 1 := map_eq_one_iff (algebra_map _ _) (algebra_map_left_inverse _).injective variables {M} /-- The canonical map from `tensor_algebra R M` into `triv_sq_zero_ext R M` that sends `tensor_algebra.ι` to `triv_sq_zero_ext.inr`. -/ def to_triv_sq_zero_ext : tensor_algebra R M →ₐ[R] triv_sq_zero_ext R M := lift R (triv_sq_zero_ext.inr_hom R M) @[simp] lemma to_triv_sq_zero_ext_ι (x : M) : to_triv_sq_zero_ext (ι R x) = triv_sq_zero_ext.inr x := lift_ι_apply _ _ /-- The left-inverse of `ι`. As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable algebra structure. -/ def ι_inv : tensor_algebra R M →ₗ[R] M := (triv_sq_zero_ext.snd_hom R M).comp to_triv_sq_zero_ext.to_linear_map lemma ι_left_inverse : function.left_inverse ι_inv (ι R : M → tensor_algebra R M) := λ x, by simp [ι_inv] variables (R) @[simp] lemma ι_inj (x y : M) : ι R x = ι R y ↔ x = y := ι_left_inverse.injective.eq_iff @[simp] lemma ι_eq_zero_iff (x : M) : ι R x = 0 ↔ x = 0 := by rw [←ι_inj R x 0, linear_map.map_zero] variables {R} @[simp] lemma ι_eq_algebra_map_iff (x : M) (r : R) : ι R x = algebra_map R _ r ↔ x = 0 ∧ r = 0 := begin refine ⟨λ h, _, _⟩, { have hf0 : to_triv_sq_zero_ext (ι R x) = (0, x), from lift_ι_apply _ _, rw [h, alg_hom.commutes] at hf0, have : r = 0 ∧ 0 = x := prod.ext_iff.1 hf0, exact this.symm.imp_left eq.symm, }, { rintro ⟨rfl, rfl⟩, rw [linear_map.map_zero, ring_hom.map_zero] } end @[simp] lemma ι_ne_one [nontrivial R] (x : M) : ι R x ≠ 1 := begin rw [←(algebra_map R (tensor_algebra R M)).map_one, ne.def, ι_eq_algebra_map_iff], exact one_ne_zero ∘ and.right, end /-- The generators of the tensor algebra are disjoint from its scalars. -/ lemma ι_range_disjoint_one : disjoint (ι R).range (1 : submodule R (tensor_algebra R M)) := begin rw submodule.disjoint_def, rintros _ ⟨x, hx⟩ ⟨r, (rfl : algebra_map _ _ _ = _)⟩, rw ι_eq_algebra_map_iff x at hx, rw [hx.2, ring_hom.map_zero] end end tensor_algebra namespace free_algebra variables {R M} /-- The canonical image of the `free_algebra` in the `tensor_algebra`, which maps `free_algebra.ι R x` to `tensor_algebra.ι R x`. -/ def to_tensor : free_algebra R M →ₐ[R] tensor_algebra R M := free_algebra.lift R (tensor_algebra.ι R) @[simp] lemma to_tensor_ι (m : M) : (free_algebra.ι R m).to_tensor = tensor_algebra.ι R m := by simp [to_tensor] end free_algebra
2ee9c97602f92c8f441ca0128ba5a98dde90e396
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/tests/linarith.lean
518d08e578c7defaf27b0ff0e830043e40934b95
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
2,934
lean
import tactic.linarith example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by linarith example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : false := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε := by linarith example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith {discharger := `[ring SOP]} example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false := by linarith {restrict_type := ℚ} example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0) (h5 : 0 ≤ c) (h6 : c < 1) : v ≤ V := by linarith example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z)) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) : ¬ 12*y - 4* z < 0 := by linarith example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false := by linarith example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false := by linarith example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 := by linarith {exfalso := ff} example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith using [rat.num_pos_iff_pos.mpr hx] example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (h1 : (1 : ℕ) < 1) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 := by linarith example (a b c : ℕ) : a + b ≥ a := by linarith example (a b c : ℕ) : ¬ a + b < a := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0) (h'' : (6 + 3 * y) * y ≥ 0) : false := by linarith example (x y : ℕ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) : false := by linarith
5c12ca9c1de67095a801c1e76a0df85027d09229
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/format.lean
526420cda5452ff8770d3c930699d0d7ca6ca51a
[]
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
599
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.meta.options import Mathlib.Lean3Lib.init.function import Mathlib.Lean3Lib.init.data.to_string universes l namespace Mathlib inductive format.color where | red : format.color | green : format.color | orange : format.color | blue : format.color | pink : format.color | cyan : format.color | grey : format.color def format.color.to_string : format.color → string := sorry
176582027288ffc3a4dbc41176d60639b931005f
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/category/constructions/rezk.hlean
554b536bf6009114a856f4f52ef2d992d87c433b
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
17,528
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer The Rezk completion -/ import hit.two_quotient types.trunc types.arrow algebra.category.functor.exponential_laws open eq category equiv trunc_two_quotient is_trunc iso e_closure function pi trunctype namespace rezk section universes l k parameters {A : Type.{l}} [C : precategory.{l k} A] include C inductive rezk_Q : Π ⦃a b : A⦄, e_closure iso a b → e_closure iso a b → Type := | comp_con : Π ⦃a b c : A⦄ (g : b ≅ c) (f : a ≅ b) , rezk_Q [f ⬝i g] ([f] ⬝r [g]) definition rezk_carrier := trunc_two_quotient 1 iso rezk_Q local attribute rezk_carrier [reducible] definition is_trunc_rezk_carrier [instance] : is_trunc 1 rezk_carrier := _ variables {a b c : A} definition elt (a : A) : rezk_carrier := incl0 a definition pth (f : a ≅ b) : elt a = elt b := incl1 f definition resp_comp (g : b ≅ c) (f : a ≅ b) : pth (f ⬝i g) = pth f ⬝ pth g := incl2 (rezk_Q.comp_con g f) definition resp_id (a : A) : pth (iso.refl a) = idp := begin apply cancel_right (pth (iso.refl a)), refine _ ⬝ !idp_con⁻¹, refine !resp_comp⁻¹ ⬝ _, apply ap pth, apply iso_eq, apply id_left, end protected definition rec {P : rezk_carrier → Type} [Π x, is_trunc 1 (P x)] (Pe : Π a, P (elt a)) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a =[pth f] Pe b) (Pcomp : Π ⦃a b c⦄ (g : b ≅ c) (f : a ≅ b), change_path (resp_comp g f) (Pp (f ⬝i g)) = Pp f ⬝o Pp g) (x : rezk_carrier) : P x := begin induction x, { apply Pe }, { apply Pp }, { induction q with a b c g f, apply Pcomp } end protected definition rec_on {P : rezk_carrier → Type} [Π x, is_trunc 1 (P x)] (x : rezk_carrier) (Pe : Π a, P (elt a)) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a =[pth f] Pe b) (Pcomp : Π ⦃a b c⦄ (g : b ≅ c) (f : a ≅ b), change_path (resp_comp g f) (Pp (f ⬝i g)) = Pp f ⬝o Pp g) : P x := rec Pe Pp Pcomp x protected definition set_rec {P : rezk_carrier → Type} [Π x, is_set (P x)] (Pe : Π a, P (elt a)) (Pp : Π⦃a b⦄ (f : a ≅ b), Pe a =[pth f] Pe b) (x : rezk_carrier) : P x := rec Pe Pp !center x protected definition prop_rec {P : rezk_carrier → Type} [Π x, is_prop (P x)] (Pe : Π a, P (elt a)) (x : rezk_carrier) : P x := rec Pe !center !center x protected definition elim {P : Type} [is_trunc 1 P] (Pe : A → P) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a = Pe b) (Pcomp : Π ⦃a b c⦄ (g : b ≅ c) (f : a ≅ b), Pp (f ⬝i g) = Pp f ⬝ Pp g) (x : rezk_carrier) : P := begin induction x, { exact Pe a }, { exact Pp s }, { induction q with a b c g f, exact Pcomp g f } end protected definition elim_on [reducible] {P : Type} [is_trunc 1 P] (x : rezk_carrier) (Pe : A → P) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a = Pe b) (Pcomp : Π ⦃a b c⦄ (g : b ≅ c) (f : a ≅ b), Pp (f ⬝i g) = Pp f ⬝ Pp g) : P := elim Pe Pp Pcomp x protected definition set_elim [reducible] {P : Type} [is_set P] (Pe : A → P) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a = Pe b) (x : rezk_carrier) : P := elim Pe Pp !center x protected definition prop_elim [reducible] {P : Type} [is_prop P] (Pe : A → P) (x : rezk_carrier) : P := elim Pe !center !center x definition elim_pth {P : Type} [is_trunc 1 P] {Pe : A → P} {Pp : Π⦃a b⦄ (f : a ≅ b), Pe a = Pe b} (Pcomp : Π⦃a b c⦄ (g : b ≅ c) (f : a ≅ b), Pp (f ⬝i g) = Pp f ⬝ Pp g) {a b : A} (f : a ≅ b) : ap (elim Pe Pp Pcomp) (pth f) = Pp f := !elim_incl1 --TODO generalize this to arbitrary truncated two-quotients or not? protected definition elim_set.{m} [reducible] (Pe : A → Set.{m}) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a ≃ Pe b) (Pcomp : Π ⦃a b c⦄ (g : b ≅ c) (f : a ≅ b) (x : Pe a), Pp (f ⬝i g) x = Pp g (Pp f x)) (x : rezk_carrier) : Set.{m} := elim Pe (λa b f, tua (Pp f)) (λa b c g f, ap tua (equiv_eq (Pcomp g f)) ⬝ !tua_trans) x protected definition elim_set_pt.{m} [reducible] (Pe : A → Set.{m}) (Pp : Π ⦃a b⦄ (f : a ≅ b), Pe a ≃ Pe b) (Pcomp : Π ⦃a b c⦄ (g : b ≅ c) (f : a ≅ b) (x : Pe a), Pp (f ⬝i g) x = Pp g (Pp f x)) (a : A) : trunctype.carrier (rezk.elim_set Pe Pp Pcomp (elt a)) = Pe a := idp protected theorem elim_set_pth {Pe : A → Set} {Pp : Π⦃a b⦄ (f : a ≅ b), Pe a ≃ Pe b} (Pcomp : Π⦃a b c⦄ (g : b ≅ c) (f : a ≅ b) (x : Pe a), Pp (f ⬝i g) x = Pp g (Pp f x)) {a b : A} (f : a ≅ b) : transport (elim_set Pe Pp Pcomp) (pth f) = Pp f := begin rewrite [tr_eq_cast_ap_fn, ↑elim_set, ▸*], rewrite [-ap_compose' trunctype.carrier, elim_pth], apply tcast_tua_fn end end end rezk open rezk attribute rezk.elt [constructor] attribute rezk.rec rezk.elim [unfold 8] [recursor 8] attribute rezk.rec_on rezk.elim_on [unfold 5] attribute rezk.set_rec rezk.set_elim [unfold 7] attribute rezk.prop_rec rezk.prop_elim rezk.elim_set [unfold 6] namespace rezk section universes l k parameters (A : Type.{l}) (C : precategory.{l k} A) definition rezk_hom_left_pt [constructor] (a : A) (b : @rezk_carrier A C) : Set.{k} := begin refine rezk.elim_set _ _ _ b, { clear b, intro b, exact trunctype.mk' 0 (hom a b) }, { clear b, intro b b' f, apply equiv_postcompose (iso.to_hom f) }, { clear b, intro b b' b'' f g x, apply !assoc⁻¹ } end private definition pathover_rezk_hom_left_pt {a b c : A} (f : hom a b) (g : b ≅ c) : pathover (rezk_hom_left_pt a) f (pth g) ((to_hom g) ∘ f) := begin apply pathover_of_tr_eq, apply @homotopy_of_eq _ _ _ (λ f, (to_hom g) ∘ f), apply rezk.elim_set_pth, end definition rezk_hom_left_pth_1_trunc [instance] (a a' : A) (f : a ≅ a') : Π b, is_trunc 1 (carrier (rezk_hom_left_pt a b) ≃ carrier (rezk_hom_left_pt a' b)) := λ b, is_trunc_equiv _ _ _ definition rezk_hom_left_pth (a a' : A) (f : a ≅ a') (b : rezk_carrier) : carrier (rezk_hom_left_pt a b) ≃ carrier (rezk_hom_left_pt a' b) := begin --induction b using rezk.rec with b' b' b g, --why does this not work if it works below? refine @rezk.rec _ _ _ (rezk_hom_left_pth_1_trunc a a' f) _ _ _ b, intro b, apply equiv_precompose (to_hom f⁻¹ⁱ), --how do i unfold properly at this point? { intro b b' g, apply equiv_pathover2, intro g' g'' H, refine !pathover_rezk_hom_left_pt ⬝op _, refine !assoc ⬝ ap (λ x, x ∘ _) _, refine eq_of_parallel_po_right _ H, apply pathover_rezk_hom_left_pt }, intro b b' b'' g g', apply @is_prop.elim, apply is_trunc_pathover, apply is_trunc_equiv end definition rezk_hom [unfold 3 4] (a b : @rezk_carrier A C) : Set.{k} := begin refine rezk.elim_set _ _ _ a, { clear a, intro a, exact rezk_hom_left_pt a b }, { clear a, intro a a' f, apply rezk_hom_left_pth a a' f }, { clear a, intro a a' a'' Ef Eg Rfg, induction b using rezk.rec, apply assoc, apply is_prop.elimo, apply is_set.elimo } end private definition pathover_rezk_hom_left {a b c : A} (f : hom a c) (g : a ≅ b) : pathover (λ x, rezk_hom x (elt c)) f (pth g) (f ∘ (to_hom g)⁻¹) := begin apply pathover_of_tr_eq, apply @homotopy_of_eq _ _ _ (λ f, f ∘ (to_hom g)⁻¹), apply rezk.elim_set_pth, end private definition pathover_rezk_hom_right {a b c : A} (f : hom a b) (g : b ≅ c) : --todo delete? pathover (rezk_hom (elt a)) f (pth g) ((to_hom g) ∘ f) := begin apply pathover_rezk_hom_left_pt, end private definition transport_rezk_hom_eq_comp {a c : A} (f : hom a a) (g : a ≅ c) : transport (λ x, rezk_hom x x) (pth g) f = (to_hom g) ∘ f ∘ (to_hom g)⁻¹ := begin apply concat, apply tr_diag_eq_tr_tr rezk_hom, apply concat, apply ap (λ x, _ ▸ x), apply tr_eq_of_pathover, apply pathover_rezk_hom_left, apply tr_eq_of_pathover, apply pathover_rezk_hom_left_pt end definition rezk_id (a : @rezk_carrier A C) : rezk_hom a a := begin induction a using rezk.rec, apply id, { apply pathover_of_tr_eq, refine !transport_rezk_hom_eq_comp ⬝ _, refine (ap (λ x, to_hom f ∘ x) !id_left) ⬝ _, apply right_inverse }, apply is_set.elimo end definition rezk_comp_pt_pt [reducible] {c : rezk_carrier} {a b : A} (g : carrier (rezk_hom (elt b) c)) (f : carrier (rezk_hom (elt a) (elt b))) : carrier (rezk_hom (elt a) c) := begin induction c using rezk.set_rec with c c c' ic, exact g ∘ f, { apply arrow_pathover_left, intro d, apply concato !pathover_rezk_hom_left_pt, apply pathover_idp_of_eq, apply concat, apply assoc, apply ap (λ x, x ∘ f), apply inverse, apply tr_eq_of_pathover, apply pathover_rezk_hom_left_pt }, end definition rezk_comp_pt_pth [reducible] {c : rezk_carrier} {a b b' : A} {ib : iso b b'} : pathover (λ b, carrier (rezk_hom b c) → carrier (rezk_hom (elt a) b) → carrier (rezk_hom (elt a) c)) (λ g f, rezk_comp_pt_pt g f) (pth ib) (λ g f, rezk_comp_pt_pt g f) := begin apply arrow_pathover_left, intro x, apply arrow_pathover_left, intro y, induction c using rezk.set_rec with c c c' ic, { apply pathover_of_eq, apply inverse, apply concat, apply ap (λ x, rezk_comp_pt_pt x _), apply tr_eq_of_pathover, apply pathover_rezk_hom_left, apply concat, apply ap (rezk_comp_pt_pt _), apply tr_eq_of_pathover, apply pathover_rezk_hom_left_pt, refine !assoc ⬝ ap (λ x, x ∘ y) _, refine !assoc⁻¹ ⬝ _, refine ap (λ y, x ∘ y) !iso.left_inverse ⬝ _, apply id_right }, apply @is_prop.elimo end definition rezk_comp {a b c : @rezk_carrier A C} (g : rezk_hom b c) (f : rezk_hom a b) : rezk_hom a c := begin induction a using rezk.set_rec with a a a' ia, { induction b using rezk.set_rec with b b b' ib, apply rezk_comp_pt_pt g f, apply rezk_comp_pt_pth }, { induction b using rezk.set_rec with b b b' ib, apply arrow_pathover_left, intro f, induction c using rezk.set_rec with c c c' ic, { apply concato, apply pathover_rezk_hom_left, apply pathover_idp_of_eq, refine !assoc⁻¹ ⬝ ap (λ x, g ∘ x) _⁻¹, apply tr_eq_of_pathover, apply pathover_rezk_hom_left }, apply is_prop.elimo, apply is_prop.elimo } end definition is_set_rezk_hom [instance] (a b : @rezk_carrier A C) : is_set (rezk_hom a b) := _ protected definition id_left {a b : @rezk_carrier A C} (f : rezk_hom a b) : rezk_comp (rezk_id b) f = f := begin induction a using rezk.prop_rec with a a a' ia, induction b using rezk.prop_rec with b b b' ib, apply id_left, end protected definition id_right {a b : @rezk_carrier A C} (f : rezk_hom a b) : rezk_comp f (rezk_id a) = f := begin induction a using rezk.prop_rec with a a a' ia, induction b using rezk.prop_rec with b b b' ib, apply id_right, end protected definition assoc {a b c d : @rezk_carrier A C} (h : rezk_hom c d) (g : rezk_hom b c) (f : rezk_hom a b) : rezk_comp h (rezk_comp g f) = rezk_comp (rezk_comp h g) f := begin induction a using rezk.prop_rec with a a a' ia, induction b using rezk.prop_rec with b b b' ib, induction c using rezk.prop_rec with c c c' ic, induction d using rezk.prop_rec with d d d' id, apply assoc, end definition rezk_precategory [instance] : precategory (@rezk_carrier A C) := precategory.mk rezk_hom @rezk_comp rezk_id @assoc @id_left @id_right end definition to_rezk_Precategory.{l k} : Precategory.{l k} → Precategory.{(max l k) k} := begin intro C, apply Precategory.mk (@rezk_carrier (Precategory.carrier C) C), apply rezk_precategory _ _, end definition rezk_functor [constructor] (C : Precategory) : functor C (to_rezk_Precategory C) := begin fapply functor.mk, apply elt, { intro a b f, exact f }, do 2 (intros; reflexivity) end section parameters {A : Type} [C : precategory A] include C protected definition elt_iso_of_iso [reducible] {a b : A} (f : a ≅ b) : elt a ≅ elt b := begin fapply iso.mk, apply to_hom f, apply functor.preserve_is_iso (rezk_functor _) end protected definition iso_of_elt_iso [reducible] {a b : A} (f : elt a ≅ elt b) : a ≅ b := begin cases f with f Hf, cases Hf with inv linv rinv, fapply iso.mk, exact f, fapply is_iso.mk, exact inv, exact linv, exact rinv end protected definition iso_of_elt_iso_distrib {a b c : A} (f : elt a ≅ elt b) (g : elt b ≅ elt c) : iso_of_elt_iso (f ⬝i g) = (iso_of_elt_iso f) ⬝i (iso_of_elt_iso g) := begin cases g with g Hg, cases Hg with invg linvg rinvg, cases f with f Hf, cases Hf with invf linvf rinvf, reflexivity end protected definition iso_equiv_elt_iso (a b : A) : (a ≅ b) ≃ (elt a ≅ elt b) := begin fapply equiv.MK, apply elt_iso_of_iso, apply iso_of_elt_iso, { intro f, cases f with f Hf, cases Hf with inv linv rinv, fapply iso_eq, reflexivity }, { intro f, fapply iso_eq, reflexivity } end private definition hom_transport_eq_transport_hom {a b b' : @rezk_carrier A C} (f : a ≅ b) (p : b = b') : to_hom (transport (iso a) p f) = transport (λ x, hom _ _) p (to_hom f) := by cases p; reflexivity private definition hom_transport_eq_transport_hom' {a a' b : @rezk_carrier A C} (f : a ≅ b) (p : a = a') : to_hom (transport (λ x, iso x b) p f) = transport (λ x, hom _ _) p (to_hom f) := by cases p; reflexivity private definition pathover_iso_pth {a b b' : A} (f : elt a ≅ elt b) (ib : b ≅ b') : pathover (λ x, iso (elt a) x) f (pth ib) (f ⬝i elt_iso_of_iso ib) := begin apply pathover_of_tr_eq, apply iso_eq, apply concat, apply hom_transport_eq_transport_hom, apply tr_eq_of_pathover, apply pathover_rezk_hom_right A C end private definition pathover_iso_pth' {a a' b : A} (f : elt a ≅ elt b) (ia : a ≅ a') : pathover (λ x, iso x (elt b)) f (pth ia) (elt_iso_of_iso (iso.symm ia) ⬝i f) := begin apply pathover_of_tr_eq, apply iso_eq, apply concat, apply hom_transport_eq_transport_hom', apply tr_eq_of_pathover, apply pathover_rezk_hom_left A C end private definition eq_of_iso_pt {a : A} {b : @rezk_carrier A C} : elt a ≅ b → elt a = b := begin intro f, induction b using rezk.set_rec with b b b' ib, apply pth, apply iso_of_elt_iso f, apply arrow_pathover, intro f g p, apply eq_pathover, refine !ap_constant ⬝ph _ ⬝hp !ap_id⁻¹, apply square_of_eq, refine !resp_comp⁻¹ ⬝ (ap pth _)⁻¹ ⬝ !idp_con⁻¹, apply concat, apply inverse, apply ap rezk.iso_of_elt_iso, apply eq_of_parallel_po_right (pathover_iso_pth _ _) p, apply concat, apply iso_of_elt_iso_distrib, apply ap (λ x, _ ⬝i x), apply equiv.to_left_inv !iso_equiv_elt_iso end protected definition eq_of_iso {a b : @rezk_carrier A C} : a ≅ b → a = b := begin intro f, induction a using rezk.set_rec with a a a' ia, apply eq_of_iso_pt f, { induction b using rezk.set_rec with b b b' ib, { apply arrow_pathover, intro f g p, apply eq_pathover, refine !ap_id ⬝ph _ ⬝hp !ap_constant⁻¹, apply square_of_eq, refine (ap pth _) ⬝ !resp_comp, assert H : g = (elt_iso_of_iso (iso.symm ia) ⬝i f), apply eq_of_parallel_po_right p (pathover_iso_pth' _ _), rewrite H, apply inverse, apply concat, apply ap (λ x, ia ⬝i x), apply iso_of_elt_iso_distrib, apply concat, apply ap (λ x, _ ⬝i (x ⬝i _)), apply equiv.to_left_inv !iso_equiv_elt_iso, apply iso_eq, apply inverse_comp_cancel_right }, apply @is_prop.elimo } end protected definition eq_of_iso_of_eq (a b : @rezk_carrier A C) (p : a = b) : eq_of_iso (iso_of_eq p) = p := begin cases p, clear b, induction a using rezk.prop_rec, refine ap pth _ ⬝ !resp_id, apply iso_eq, reflexivity end protected definition iso_of_eq_of_iso (a b : @rezk_carrier A C) (f : a ≅ b) : iso_of_eq (eq_of_iso f) = f := begin induction a using rezk.prop_rec with a, induction b using rezk.prop_rec with b, cases f with f Hf, apply iso_eq, apply concat, apply ap to_hom, apply !transport_iso_of_eq⁻¹, apply concat, apply ap to_hom, apply tr_eq_of_pathover, apply pathover_iso_pth, cases Hf with invf linv rinv, apply id_right, end end definition rezk_category.{l k} {A : Type.{l}} [C : precategory.{l k} A] : category.{(max l k) k} (@rezk_carrier.{l k} A C) := begin fapply category.mk (rezk_precategory A C), intros, fapply is_equiv.adjointify, apply rezk.eq_of_iso, apply rezk.iso_of_eq_of_iso, apply rezk.eq_of_iso_of_eq end section variable (C : Precategory) definition fully_faithful_rezk_functor : fully_faithful (rezk_functor C) := by intros; apply is_equiv.is_equiv_id open trunc definition essentially_surj_rezk_functor : essentially_surjective (rezk_functor C) := begin intro a, esimp[to_rezk_Precategory] at *, induction a using rezk.prop_rec with a, apply tr, constructor, apply iso.refl (elt a), end definition is_weak_equiv_rezk_functor : is_weak_equivalence (rezk_functor C) := prod.mk (fully_faithful_rezk_functor C) (essentially_surj_rezk_functor C) end end rezk
20e1bdddb4e1110d72b0971cf9e428f0e0e4fadd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/smt_tactic.lean
7da4df32c9a4e7bfe0fefa3fbea5216e1fd4f818
[ "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
330
lean
namespace tactic.interactive meta def smt (tac : smt_tactic.interactive.itactic) : tactic unit := solve1 $ using_smt $ tac end tactic.interactive def f (a : nat) := a example (a b c : nat) (h₁ : a = b) (h₂ : b = c) : f b = c + 0 := begin smt { trace_state, change f b = c, add_lhs_lemma f.equations._eqn_1, ematch } end
c77dc118a3ee3b90b530f756027fbef54fd8cf25
fe25de614feb5587799621c41487aaee0d083b08
/tests/lean/struct1.lean
2cc3e72bcbad31d016e9a6187659b942bf398821
[ "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
940
lean
-- structure A (α : Type) := (x : α) structure B (α : Type) := (x : α) structure S : Nat := -- error expected Type (x : Nat) structure S extends Nat → Nat := -- error expected structure (x : Nat) structure S extends A Nat, A Bool := -- error field toA already declared (x : Nat) structure S extends A Nat, B Bool := -- error field `x` from `B` has already been declared (x : Nat) structure S1 := (_x : Nat) structure S2 := (x _y : Nat) structure S := (x : Nat) (x : Nat) -- error structure S extends A Nat := (x : Nat) -- error structure S extends A Nat := (x := true) -- error type mismatch structure S extends A Nat := (x : Bool := true) -- error omit type structure S := (x : Nat := true) -- error type mismatch private structure S := private mk :: (x : Nat) private structure S := protected mk :: (x : Nat) private structure S := protected (x : Nat) private structure S := mk2 :: (x : Nat) #check S #check S.mk2
a3180bfd2aa0e5ffeb3fb78578e6a8e280e73501
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/alternating.lean
0f12269e019634aee0bc48827774ad67285c4979
[ "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
42,998
lean
/- Copyright (c) 2020 Zhangir Azerbayev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Zhangir Azerbayev -/ import group_theory.group_action.quotient import group_theory.perm.sign import group_theory.perm.subgroup import linear_algebra.linear_independent import linear_algebra.multilinear.basis import linear_algebra.multilinear.tensor_product /-! # Alternating Maps We construct the bundled function `alternating_map`, which extends `multilinear_map` with all the arguments of the same type. ## Main definitions * `alternating_map R M N ι` is the space of `R`-linear alternating maps from `ι → M` to `N`. * `f.map_eq_zero_of_eq` expresses that `f` is zero when two inputs are equal. * `f.map_swap` expresses that `f` is negated when two inputs are swapped. * `f.map_perm` expresses how `f` varies by a sign change under a permutation of its inputs. * An `add_comm_monoid`, `add_comm_group`, and `module` structure over `alternating_map`s that matches the definitions over `multilinear_map`s. * `multilinear_map.dom_dom_congr`, for permutating the elements within a family. * `multilinear_map.alternatization`, which makes an alternating map out of a non-alternating one. * `alternating_map.dom_coprod`, which behaves as a product between two alternating maps. * `alternating_map.curry_left`, for binding the leftmost argument of an alternating map indexed by `fin n.succ`. ## Implementation notes `alternating_map` is defined in terms of `map_eq_zero_of_eq`, as this is easier to work with than using `map_swap` as a definition, and does not require `has_neg N`. `alternating_map`s are provided with a coercion to `multilinear_map`, along with a set of `norm_cast` lemmas that act on the algebraic structure: * `alternating_map.coe_add` * `alternating_map.coe_zero` * `alternating_map.coe_sub` * `alternating_map.coe_neg` * `alternating_map.coe_smul` -/ -- semiring / add_comm_monoid variables {R : Type*} [semiring R] variables {M : Type*} [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] -- semiring / add_comm_group variables {M' : Type*} [add_comm_group M'] [module R M'] variables {N' : Type*} [add_comm_group N'] [module R N'] variables {ι ι' ι'' : Type*} [decidable_eq ι] [decidable_eq ι'] [decidable_eq ι''] set_option old_structure_cmd true section variables (R M N ι) /-- An alternating map is a multilinear map that vanishes when two of its arguments are equal. -/ structure alternating_map extends multilinear_map R (λ i : ι, M) N := (map_eq_zero_of_eq' : ∀ (v : ι → M) (i j : ι) (h : v i = v j) (hij : i ≠ j), to_fun v = 0) end /-- The multilinear map associated to an alternating map -/ add_decl_doc alternating_map.to_multilinear_map namespace alternating_map variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! Basic coercion simp lemmas, largely copied from `ring_hom` and `multilinear_map` -/ section coercions instance : has_coe_to_fun (alternating_map R M N ι) (λ _, (ι → M) → N) := ⟨λ x, x.to_fun⟩ initialize_simps_projections alternating_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ⇑(⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) = f := rfl theorem congr_fun {f g : alternating_map R M N ι} (h : f = g) (x : ι → M) : f x = g x := congr_arg (λ h : alternating_map R M N ι, h x) h theorem congr_arg (f : alternating_map R M N ι) {x y : ι → M} (h : x = y) : f x = f y := congr_arg (λ x : ι → M, f x) h theorem coe_injective : injective (coe_fn : alternating_map R M N ι → ((ι → M) → N)) := λ f g h, by { cases f, cases g, cases h, refl } @[simp, norm_cast] theorem coe_inj {f g : alternating_map R M N ι} : (f : (ι → M) → N) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext {f f' : alternating_map R M N ι} (H : ∀ x, f x = f' x) : f = f' := coe_injective (funext H) theorem ext_iff {f g : alternating_map R M N ι} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : has_coe (alternating_map R M N ι) (multilinear_map R (λ i : ι, M) N) := ⟨λ x, x.to_multilinear_map⟩ @[simp, norm_cast] lemma coe_multilinear_map : ⇑(f : multilinear_map R (λ i : ι, M) N) = f := rfl lemma coe_multilinear_map_injective : function.injective (coe : alternating_map R M N ι → multilinear_map R (λ i : ι, M) N) := λ x y h, ext $ multilinear_map.congr_fun h @[simp] lemma to_multilinear_map_eq_coe : f.to_multilinear_map = f := rfl @[simp] lemma coe_multilinear_map_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = ⟨f, h₁, h₂⟩ := rfl end coercions /-! ### Simp-normal forms of the structure fields These are expressed in terms of `⇑f` instead of `f.to_fun`. -/ @[simp] lemma map_add (i : ι) (x y : M) : f (update v i (x + y)) = f (update v i x) + f (update v i y) := f.to_multilinear_map.map_add' v i x y @[simp] lemma map_sub (i : ι) (x y : M') : g' (update v' i (x - y)) = g' (update v' i x) - g' (update v' i y) := g'.to_multilinear_map.map_sub v' i x y @[simp] lemma map_neg (i : ι) (x : M') : g' (update v' i (-x)) = -g' (update v' i x) := g'.to_multilinear_map.map_neg v' i x @[simp] lemma map_smul (i : ι) (r : R) (x : M) : f (update v i (r • x)) = r • f (update v i x) := f.to_multilinear_map.map_smul' v i r x @[simp] lemma map_eq_zero_of_eq (v : ι → M) {i j : ι} (h : v i = v j) (hij : i ≠ j) : f v = 0 := f.map_eq_zero_of_eq' v i j h hij lemma map_coord_zero {m : ι → M} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_update_zero (m : ι → M) (i : ι) : f (update m i 0) = 0 := f.to_multilinear_map.map_update_zero m i @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero lemma map_eq_zero_of_not_injective (v : ι → M) (hv : ¬function.injective v) : f v = 0 := begin rw function.injective at hv, push_neg at hv, rcases hv with ⟨i₁, i₂, heq, hne⟩, exact f.map_eq_zero_of_eq v heq hne end /-! ### Algebraic structure inherited from `multilinear_map` `alternating_map` carries the same `add_comm_monoid`, `add_comm_group`, and `module` structure as `multilinear_map` -/ section has_smul variables {S : Type*} [monoid S] [distrib_mul_action S N] [smul_comm_class R S N] instance : has_smul S (alternating_map R M N ι) := ⟨λ c f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..((c • f : multilinear_map R (λ i : ι, M) N)) }⟩ @[simp] lemma smul_apply (c : S) (m : ι → M) : (c • f) m = c • f m := rfl @[norm_cast] lemma coe_smul (c : S): ((c • f : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = c • f := rfl lemma coe_fn_smul (c : S) (f : alternating_map R M N ι) : ⇑(c • f) = c • f := rfl instance [distrib_mul_action Sᵐᵒᵖ N] [is_central_scalar S N] : is_central_scalar S (alternating_map R M N ι) := ⟨λ c f, ext $ λ x, op_smul_eq_smul _ _⟩ end has_smul instance : has_add (alternating_map R M N ι) := ⟨λ a b, { map_eq_zero_of_eq' := λ v i j h hij, by simp [a.map_eq_zero_of_eq v h hij, b.map_eq_zero_of_eq v h hij], ..(a + b : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma add_apply : (f + f') v = f v + f' v := rfl @[norm_cast] lemma coe_add : (↑(f + f') : multilinear_map R (λ i : ι, M) N) = f + f' := rfl instance : has_zero (alternating_map R M N ι) := ⟨{map_eq_zero_of_eq' := λ v i j h hij, by simp, ..(0 : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma zero_apply : (0 : alternating_map R M N ι) v = 0 := rfl @[norm_cast] lemma coe_zero : ((0 : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = 0 := rfl instance : inhabited (alternating_map R M N ι) := ⟨0⟩ instance : add_comm_monoid (alternating_map R M N ι) := coe_injective.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, coe_fn_smul _ _) instance : has_neg (alternating_map R M N' ι) := ⟨λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(-(f : multilinear_map R (λ i : ι, M) N')) }⟩ @[simp] lemma neg_apply (m : ι → M) : (-g) m = -(g m) := rfl @[norm_cast] lemma coe_neg : ((-g : alternating_map R M N' ι) : multilinear_map R (λ i : ι, M) N') = -g := rfl instance : has_sub (alternating_map R M N' ι) := ⟨λ f g, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij, g.map_eq_zero_of_eq v h hij], ..(f - g : multilinear_map R (λ i : ι, M) N') }⟩ @[simp] lemma sub_apply (m : ι → M) : (g - g₂) m = g m - g₂ m := rfl @[norm_cast] lemma coe_sub : (↑(g - g₂) : multilinear_map R (λ i : ι, M) N') = g - g₂ := rfl instance : add_comm_group (alternating_map R M N' ι) := coe_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, coe_fn_smul _ _) (λ _ _, coe_fn_smul _ _) section distrib_mul_action variables {S : Type*} [monoid S] [distrib_mul_action S N] [smul_comm_class R S N] instance : distrib_mul_action S (alternating_map R M N ι) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {S : Type*} [semiring S] [module S N] [smul_comm_class R S N] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module S (alternating_map R M N ι) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } instance [no_zero_smul_divisors S N] : no_zero_smul_divisors S (alternating_map R M N ι) := coe_injective.no_zero_smul_divisors _ rfl coe_fn_smul end module section variables (R M) /-- The evaluation map from `ι → M` to `M` at a given `i` is alternating when `ι` is subsingleton. -/ @[simps] def of_subsingleton [subsingleton ι] (i : ι) : alternating_map R M M ι := { to_fun := function.eval i, map_eq_zero_of_eq' := λ v i j hv hij, (hij $ subsingleton.elim _ _).elim, ..multilinear_map.of_subsingleton R M i } /-- The constant map is alternating when `ι` is empty. -/ @[simps {fully_applied := ff}] def const_of_is_empty [is_empty ι] (m : N) : alternating_map R M N ι := { to_fun := function.const _ m, map_eq_zero_of_eq' := λ v, is_empty_elim, ..multilinear_map.const_of_is_empty R m } end /-- Restrict the codomain of an alternating map to a submodule. -/ @[simps] def cod_restrict (f : alternating_map R M N ι) (p : submodule R N) (h : ∀ v, f v ∈ p) : alternating_map R M p ι := { to_fun := λ v, ⟨f v, h v⟩, map_eq_zero_of_eq' := λ v i j hv hij, subtype.ext $ map_eq_zero_of_eq _ _ hv hij, ..f.to_multilinear_map.cod_restrict p h } end alternating_map /-! ### Composition with linear maps -/ namespace linear_map variables {N₂ : Type*} [add_comm_monoid N₂] [module R N₂] /-- Composing a alternating map with a linear map on the left gives again an alternating map. -/ def comp_alternating_map (g : N →ₗ[R] N₂) : alternating_map R M N ι →+ alternating_map R M N₂ ι := { to_fun := λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(g.comp_multilinear_map (f : multilinear_map R (λ _ : ι, M) N)) }, map_zero' := by { ext, simp }, map_add' := λ a b, by { ext, simp } } @[simp] lemma coe_comp_alternating_map (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) : ⇑(g.comp_alternating_map f) = g ∘ f := rfl @[simp] lemma comp_alternating_map_apply (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) (m : ι → M) : g.comp_alternating_map f m = g (f m) := rfl @[simp] lemma subtype_comp_alternating_map_cod_restrict (f : alternating_map R M N ι) (p : submodule R N) (h) : p.subtype.comp_alternating_map (f.cod_restrict p h) = f := alternating_map.ext $ λ v, rfl @[simp] lemma comp_alternating_map_cod_restrict (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) (p : submodule R N₂) (h) : (g.cod_restrict p h).comp_alternating_map f = (g.comp_alternating_map f).cod_restrict p (λ v, h (f v)):= alternating_map.ext $ λ v, rfl end linear_map namespace alternating_map variables {M₂ : Type*} [add_comm_monoid M₂] [module R M₂] variables {M₃ : Type*} [add_comm_monoid M₃] [module R M₃] /-- Composing a alternating map with the same linear map on each argument gives again an alternating map. -/ def comp_linear_map (f : alternating_map R M N ι) (g : M₂ →ₗ[R] M) : alternating_map R M₂ N ι := { map_eq_zero_of_eq' := λ v i j h hij, f.map_eq_zero_of_eq _ (linear_map.congr_arg h) hij, .. (f : multilinear_map R (λ _ : ι, M) N).comp_linear_map (λ _, g) } lemma coe_comp_linear_map (f : alternating_map R M N ι) (g : M₂ →ₗ[R] M) : ⇑(f.comp_linear_map g) = f ∘ ((∘) g) := rfl @[simp] lemma comp_linear_map_apply (f : alternating_map R M N ι) (g : M₂ →ₗ[R] M) (v : ι → M₂) : f.comp_linear_map g v = f (λ i, g (v i)) := rfl /-- Composing an alternating map twice with the same linear map in each argument is the same as composing with their composition. -/ lemma comp_linear_map_assoc (f : alternating_map R M N ι) (g₁ : M₂ →ₗ[R] M) (g₂ : M₃ →ₗ[R] M₂) : (f.comp_linear_map g₁).comp_linear_map g₂ = f.comp_linear_map (g₁ ∘ₗ g₂) := rfl @[simp] lemma zero_comp_linear_map (g : M₂ →ₗ[R] M) : (0 : alternating_map R M N ι).comp_linear_map g = 0 := by { ext, simp only [comp_linear_map_apply, zero_apply] } @[simp] lemma add_comp_linear_map (f₁ f₂ : alternating_map R M N ι) (g : M₂ →ₗ[R] M) : (f₁ + f₂).comp_linear_map g = f₁.comp_linear_map g + f₂.comp_linear_map g := by { ext, simp only [comp_linear_map_apply, add_apply] } @[simp] lemma comp_linear_map_zero [nonempty ι] (f : alternating_map R M N ι) : f.comp_linear_map (0 : M₂ →ₗ[R] M) = 0 := begin ext, simp_rw [comp_linear_map_apply, linear_map.zero_apply, ←pi.zero_def, map_zero, zero_apply], end /-- Composing an alternating map with the identity linear map in each argument. -/ @[simp] lemma comp_linear_map_id (f : alternating_map R M N ι) : f.comp_linear_map linear_map.id = f := ext $ λ _, rfl /-- Composing with a surjective linear map is injective. -/ lemma comp_linear_map_injective (f : M₂ →ₗ[R] M) (hf : function.surjective f) : function.injective (λ g : alternating_map R M N ι, g.comp_linear_map f) := λ g₁ g₂ h, ext $ λ x, by simpa [function.surj_inv_eq hf] using ext_iff.mp h (function.surj_inv hf ∘ x) lemma comp_linear_map_inj (f : M₂ →ₗ[R] M) (hf : function.surjective f) (g₁ g₂ : alternating_map R M N ι) : g₁.comp_linear_map f = g₂.comp_linear_map f ↔ g₁ = g₂ := (comp_linear_map_injective _ hf).eq_iff section dom_lcongr variables (ι R N) (S : Type*) [semiring S] [module S N] [smul_comm_class R S N] /-- Construct a linear equivalence between maps from a linear equivalence between domains. -/ @[simps apply] def dom_lcongr (e : M ≃ₗ[R] M₂) : alternating_map R M N ι ≃ₗ[S] alternating_map R M₂ N ι := { to_fun := λ f, f.comp_linear_map e.symm, inv_fun := λ g, g.comp_linear_map e, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl, left_inv := λ f, alternating_map.ext $ λ v, f.congr_arg $ funext $ λ i, e.symm_apply_apply _, right_inv := λ f, alternating_map.ext $ λ v, f.congr_arg $ funext $ λ i, e.apply_symm_apply _ } @[simp] lemma dom_lcongr_refl : dom_lcongr R N ι S (linear_equiv.refl R M) = linear_equiv.refl S _ := linear_equiv.ext $ λ _, alternating_map.ext $ λ v, rfl @[simp] lemma dom_lcongr_symm (e : M ≃ₗ[R] M₂) : (dom_lcongr R N ι S e).symm = dom_lcongr R N ι S e.symm := rfl lemma dom_lcongr_trans (e : M ≃ₗ[R] M₂) (f : M₂ ≃ₗ[R] M₃): (dom_lcongr R N ι S e).trans (dom_lcongr R N ι S f) = dom_lcongr R N ι S (e.trans f) := rfl end dom_lcongr /-- Composing an alternating map with the same linear equiv on each argument gives the zero map if and only if the alternating map is the zero map. -/ @[simp] lemma comp_linear_equiv_eq_zero_iff (f : alternating_map R M N ι) (g : M₂ ≃ₗ[R] M) : f.comp_linear_map (g : M₂ →ₗ[R] M) = 0 ↔ f = 0 := (dom_lcongr R N ι ℕ g.symm).map_eq_zero_iff variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! ### Other lemmas from `multilinear_map` -/ section open_locale big_operators lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M) (m : ι → M): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := f.to_multilinear_map.map_update_sum t i g m end /-! ### Theorems specific to alternating maps Various properties of reordered and repeated inputs which follow from `alternating_map.map_eq_zero_of_eq`. -/ lemma map_update_self {i j : ι} (hij : i ≠ j) : f (function.update v i (v j)) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij.symm]) hij lemma map_update_update {i j : ι} (hij : i ≠ j) (m : M) : f (function.update (function.update v i m) j m) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij, function.update_same]) hij lemma map_swap_add {i j : ι} (hij : i ≠ j) : f (v ∘ equiv.swap i j) + f v = 0 := begin rw equiv.comp_swap_eq_update, convert f.map_update_update v hij (v i + v j), simp [f.map_update_self _ hij, f.map_update_self _ hij.symm, function.update_comm hij (v i + v j) (v _) v, function.update_comm hij.symm (v i) (v i) v], end lemma map_add_swap {i j : ι} (hij : i ≠ j) : f v + f (v ∘ equiv.swap i j) = 0 := by { rw add_comm, exact f.map_swap_add v hij } lemma map_swap {i j : ι} (hij : i ≠ j) : g (v ∘ equiv.swap i j) = - g v := eq_neg_of_add_eq_zero_left $ g.map_swap_add v hij lemma map_perm [fintype ι] (v : ι → M) (σ : equiv.perm ι) : g (v ∘ σ) = σ.sign • g v := begin apply equiv.perm.swap_induction_on' σ, { simp }, { intros s x y hxy hI, simpa [g.map_swap (v ∘ s) hxy, equiv.perm.sign_swap hxy] using hI, } end lemma map_congr_perm [fintype ι] (σ : equiv.perm ι) : g v = σ.sign • g (v ∘ σ) := by { rw [g.map_perm, smul_smul], simp } section dom_dom_congr /-- Transfer the arguments to a map along an equivalence between argument indices. This is the alternating version of `multilinear_map.dom_dom_congr`. -/ @[simps] def dom_dom_congr (σ : ι ≃ ι') (f : alternating_map R M N ι) : alternating_map R M N ι' := { to_fun := λ v, f (v ∘ σ), map_eq_zero_of_eq' := λ v i j hv hij, f.map_eq_zero_of_eq (v ∘ σ) (by simpa using hv) (σ.symm.injective.ne hij), .. f.to_multilinear_map.dom_dom_congr σ } @[simp] lemma dom_dom_congr_refl (f : alternating_map R M N ι) : f.dom_dom_congr (equiv.refl ι) = f := ext $ λ v, rfl lemma dom_dom_congr_trans (σ₁ : ι ≃ ι') (σ₂ : ι' ≃ ι'') (f : alternating_map R M N ι) : f.dom_dom_congr (σ₁.trans σ₂) = (f.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl @[simp] lemma dom_dom_congr_zero (σ : ι ≃ ι') : (0 : alternating_map R M N ι).dom_dom_congr σ = 0 := rfl @[simp] lemma dom_dom_congr_add (σ : ι ≃ ι') (f g : alternating_map R M N ι) : (f + g).dom_dom_congr σ = f.dom_dom_congr σ + g.dom_dom_congr σ := rfl /-- `alternating_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (σ : ι ≃ ι') : alternating_map R M N ι ≃+ alternating_map R M N ι' := { to_fun := dom_dom_congr σ, inv_fun := dom_dom_congr σ.symm, left_inv := λ f, by { ext, simp [function.comp] }, right_inv := λ m, by { ext, simp [function.comp] }, map_add' := dom_dom_congr_add σ } /-- The results of applying `dom_dom_congr` to two maps are equal if and only if those maps are. -/ @[simp] lemma dom_dom_congr_eq_iff (σ : ι ≃ ι') (f g : alternating_map R M N ι) : f.dom_dom_congr σ = g.dom_dom_congr σ ↔ f = g := (dom_dom_congr_equiv σ : _ ≃+ alternating_map R M N ι').apply_eq_iff_eq @[simp] lemma dom_dom_congr_eq_zero_iff (σ : ι ≃ ι') (f : alternating_map R M N ι) : f.dom_dom_congr σ = 0 ↔ f = 0 := (dom_dom_congr_equiv σ : alternating_map R M N ι ≃+ alternating_map R M N ι').map_eq_zero_iff lemma dom_dom_congr_perm [fintype ι] (σ : equiv.perm ι) : g.dom_dom_congr σ = σ.sign • g := alternating_map.ext $ λ v, g.map_perm v σ @[norm_cast] lemma coe_dom_dom_congr (σ : ι ≃ ι') : ↑(f.dom_dom_congr σ) = (f : multilinear_map R (λ _ : ι, M) N).dom_dom_congr σ := multilinear_map.ext $ λ v, rfl end dom_dom_congr /-- If the arguments are linearly dependent then the result is `0`. -/ lemma map_linear_dependent {K : Type*} [ring K] {M : Type*} [add_comm_group M] [module K M] {N : Type*} [add_comm_group N] [module K N] [no_zero_smul_divisors K N] (f : alternating_map K M N ι) (v : ι → M) (h : ¬linear_independent K v) : f v = 0 := begin obtain ⟨s, g, h, i, hi, hz⟩ := not_linear_independent_iff.mp h, suffices : f (update v i (g i • v i)) = 0, { rw [f.map_smul, function.update_eq_self, smul_eq_zero] at this, exact or.resolve_left this hz, }, conv at h in (g _ • v _) { rw ←if_t_t (i = x) (g _ • v _), }, rw [finset.sum_ite, finset.filter_eq, finset.filter_ne, if_pos hi, finset.sum_singleton, add_eq_zero_iff_eq_neg] at h, rw [h, f.map_neg, f.map_update_sum, neg_eq_zero, finset.sum_eq_zero], intros j hj, obtain ⟨hij, _⟩ := finset.mem_erase.mp hj, rw [f.map_smul, f.map_update_self _ hij.symm, smul_zero], end section fin open fin /-- A version of `multilinear_map.cons_add` for `alternating_map`. -/ lemma map_vec_cons_add {n : ℕ} (f : alternating_map R M N (fin n.succ)) (m : fin n → M) (x y : M) : f (matrix.vec_cons (x+y) m) = f (matrix.vec_cons x m) + f (matrix.vec_cons y m) := f.to_multilinear_map.cons_add _ _ _ /-- A version of `multilinear_map.cons_smul` for `alternating_map`. -/ lemma map_vec_cons_smul {n : ℕ} (f : alternating_map R M N (fin n.succ)) (m : fin n → M) (c : R) (x : M) : f (matrix.vec_cons (c • x) m) = c • f (matrix.vec_cons x m) := f.to_multilinear_map.cons_smul _ _ _ end fin end alternating_map open_locale big_operators namespace multilinear_map open equiv variables [fintype ι] private lemma alternization_map_eq_zero_of_eq_aux (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) (i j : ι) (i_ne_j : i ≠ j) (hv : v i = v j) : (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ) v = 0 := begin rw sum_apply, exact finset.sum_involution (λ σ _, swap i j * σ) (λ σ _, by simp [perm.sign_swap i_ne_j, apply_swap_eq_self hv]) (λ σ _ _, (not_congr swap_mul_eq_iff).mpr i_ne_j) (λ σ _, finset.mem_univ _) (λ σ _, swap_mul_involutive i j σ) end /-- Produce an `alternating_map` out of a `multilinear_map`, by summing over all argument permutations. -/ def alternatization : multilinear_map R (λ i : ι, M) N' →+ alternating_map R M N' ι := { to_fun := λ m, { to_fun := ⇑(∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ), map_eq_zero_of_eq' := λ v i j hvij hij, alternization_map_eq_zero_of_eq_aux m v i j hij hvij, .. (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ)}, map_add' := λ a b, begin ext, simp only [ finset.sum_add_distrib, smul_add, add_apply, dom_dom_congr_apply, alternating_map.add_apply, alternating_map.coe_mk, smul_apply, sum_apply], end, map_zero' := begin ext, simp only [ finset.sum_const_zero, smul_zero, zero_apply, dom_dom_congr_apply, alternating_map.zero_apply, alternating_map.coe_mk, smul_apply, sum_apply], end } lemma alternatization_def (m : multilinear_map R (λ i : ι, M) N') : ⇑(alternatization m) = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := rfl lemma alternatization_coe (m : multilinear_map R (λ i : ι, M) N') : ↑m.alternatization = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := coe_injective rfl lemma alternatization_apply (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) : alternatization m v = ∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ v := by simp only [alternatization_def, smul_apply, sum_apply] end multilinear_map namespace alternating_map /-- Alternatizing a multilinear map that is already alternating results in a scale factor of `n!`, where `n` is the number of inputs. -/ lemma coe_alternatization [fintype ι] (a : alternating_map R M N' ι) : (↑a : multilinear_map R (λ ι, M) N').alternatization = nat.factorial (fintype.card ι) • a := begin apply alternating_map.coe_injective, simp_rw [multilinear_map.alternatization_def, ←coe_dom_dom_congr, dom_dom_congr_perm, coe_smul, smul_smul, int.units_mul_self, one_smul, finset.sum_const, finset.card_univ, fintype.card_perm, ←coe_multilinear_map, coe_smul], end end alternating_map namespace linear_map variables {N'₂ : Type*} [add_comm_group N'₂] [module R N'₂] [fintype ι] /-- Composition with a linear map before and after alternatization are equivalent. -/ lemma comp_multilinear_map_alternatization (g : N' →ₗ[R] N'₂) (f : multilinear_map R (λ _ : ι, M) N') : (g.comp_multilinear_map f).alternatization = g.comp_alternating_map (f.alternatization) := by { ext, simp [multilinear_map.alternatization_def] } end linear_map section coprod open_locale big_operators open_locale tensor_product variables {ιa ιb : Type*} [decidable_eq ιa] [decidable_eq ιb] [fintype ιa] [fintype ιb] variables {R' : Type*} {Mᵢ N₁ N₂ : Type*} [comm_semiring R'] [add_comm_group N₁] [module R' N₁] [add_comm_group N₂] [module R' N₂] [add_comm_monoid Mᵢ] [module R' Mᵢ] namespace equiv.perm /-- Elements which are considered equivalent if they differ only by swaps within α or β -/ abbreviation mod_sum_congr (α β : Type*) := _ ⧸ (equiv.perm.sum_congr_hom α β).range lemma mod_sum_congr.swap_smul_involutive {α β : Type*} [decidable_eq (α ⊕ β)] (i j : α ⊕ β) : function.involutive (has_smul.smul (equiv.swap i j) : mod_sum_congr α β → mod_sum_congr α β) := λ σ, begin apply σ.induction_on' (λ σ, _), exact _root_.congr_arg quotient.mk' (equiv.swap_mul_involutive i j σ) end end equiv.perm namespace alternating_map open equiv /-- summand used in `alternating_map.dom_coprod` -/ def dom_coprod.summand (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗[R'] N₂) := quotient.lift_on' σ (λ σ, σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ) (λ σ₁ σ₂ H, begin rw quotient_group.left_rel_apply at H, obtain ⟨⟨sl, sr⟩, h⟩ := H, ext v, simp only [multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, coe_multilinear_map, multilinear_map.smul_apply], replace h := inv_mul_eq_iff_eq_mul.mp (h.symm), have : (σ₁ * perm.sum_congr_hom _ _ (sl, sr)).sign = σ₁.sign * (sl.sign * sr.sign) := by simp, rw [h, this, mul_smul, mul_smul, smul_left_cancel_iff, ←tensor_product.tmul_smul, tensor_product.smul_tmul'], simp only [sum.map_inr, perm.sum_congr_hom_apply, perm.sum_congr_apply, sum.map_inl, function.comp_app, perm.coe_mul], rw [←a.map_congr_perm (λ i, v (σ₁ _)), ←b.map_congr_perm (λ i, v (σ₁ _))], end) lemma dom_coprod.summand_mk' (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : equiv.perm (ιa ⊕ ιb)) : dom_coprod.summand a b (quotient.mk' σ) = σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ := rfl /-- Swapping elements in `σ` with equal values in `v` results in an addition that cancels -/ lemma dom_coprod.summand_add_swap_smul_eq_zero (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : dom_coprod.summand a b σ v + dom_coprod.summand a b (swap i j • σ) v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', mul_action.quotient.smul_mk, dom_coprod.summand], rw [smul_eq_mul, perm.sign_mul, perm.sign_swap hij], simp only [one_mul, neg_mul, function.comp_app, units.neg_smul, perm.coe_mul, units.coe_neg, multilinear_map.smul_apply, multilinear_map.neg_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply], convert add_right_neg _; { ext k, rw equiv.apply_swap_eq_self hv }, end /-- Swapping elements in `σ` with equal values in `v` result in zero if the swap has no effect on the quotient. -/ lemma dom_coprod.summand_eq_zero_of_smul_invariant (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : swap i j • σ = σ → dom_coprod.summand a b σ v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', multilinear_map.smul_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, dom_coprod.summand], intro hσ, cases hi : σ⁻¹ i; cases hj : σ⁻¹ j; rw perm.inv_eq_iff_eq at hi hj; substs hi hj; revert val val_1, case [sum.inl sum.inr, sum.inr sum.inl] { -- the term pairs with and cancels another term all_goals { intros i' j' hv hij hσ, obtain ⟨⟨sl, sr⟩, hσ⟩ := quotient_group.left_rel_apply.mp (quotient.exact' hσ), }, work_on_goal 1 { replace hσ := equiv.congr_fun hσ (sum.inl i'), }, work_on_goal 2 { replace hσ := equiv.congr_fun hσ (sum.inr i'), }, all_goals { rw [smul_eq_mul, ←mul_swap_eq_swap_mul, mul_inv_rev, swap_inv, inv_mul_cancel_right] at hσ, simpa using hσ, }, }, case [sum.inr sum.inr, sum.inl sum.inl] { -- the term does not pair but is zero all_goals { intros i' j' hv hij hσ, convert smul_zero _, }, work_on_goal 1 { convert tensor_product.tmul_zero _ _, }, work_on_goal 2 { convert tensor_product.zero_tmul _ _, }, all_goals { exact alternating_map.map_eq_zero_of_eq _ _ hv (λ hij', hij (hij' ▸ rfl)), } }, end /-- Like `multilinear_map.dom_coprod`, but ensures the result is also alternating. Note that this is usually defined (for instance, as used in Proposition 22.24 in [Gallier2011Notes]) over integer indices `ιa = fin n` and `ιb = fin m`, as $$ (f \wedge g)(u_1, \ldots, u_{m+n}) = \sum_{\operatorname{shuffle}(m, n)} \operatorname{sign}(\sigma) f(u_{\sigma(1)}, \ldots, u_{\sigma(m)}) g(u_{\sigma(m+1)}, \ldots, u_{\sigma(m+n)}), $$ where $\operatorname{shuffle}(m, n)$ consists of all permutations of $[1, m+n]$ such that $\sigma(1) < \cdots < \sigma(m)$ and $\sigma(m+1) < \cdots < \sigma(m+n)$. Here, we generalize this by replacing: * the product in the sum with a tensor product * the filtering of $[1, m+n]$ to shuffles with an isomorphic quotient * the additions in the subscripts of $\sigma$ with an index of type `sum` The specialized version can be obtained by combining this definition with `fin_sum_fin_equiv` and `linear_map.mul'`. -/ @[simps] def dom_coprod (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := { to_fun := λ v, ⇑(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) v, map_eq_zero_of_eq' := λ v i j hv hij, begin dsimp only, rw multilinear_map.sum_apply, exact finset.sum_involution (λ σ _, equiv.swap i j • σ) (λ σ _, dom_coprod.summand_add_swap_smul_eq_zero a b σ hv hij) (λ σ _, mt $ dom_coprod.summand_eq_zero_of_smul_invariant a b σ hv hij) (λ σ _, finset.mem_univ _) (λ σ _, equiv.perm.mod_sum_congr.swap_smul_involutive i j σ), end, ..(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) } lemma dom_coprod_coe (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (↑(a.dom_coprod b) : multilinear_map R' (λ _, Mᵢ) _) = ∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ := multilinear_map.ext $ λ _, rfl /-- A more bundled version of `alternating_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : (alternating_map R' Mᵢ N₁ ιa ⊗[R'] alternating_map R' Mᵢ N₂ ιb) →ₗ[R'] alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := tensor_product.lift $ by refine linear_map.mk₂ R' (dom_coprod) (λ m₁ m₂ n, _) (λ c m n, _) (λ m n₁ n₂, _) (λ c m n, _); { ext, simp only [dom_coprod_apply, add_apply, smul_apply, ←finset.sum_add_distrib, finset.smul_sum, multilinear_map.sum_apply, dom_coprod.summand], congr, ext σ, apply σ.induction_on' (λ σ, _), simp only [quotient.lift_on'_mk', coe_add, coe_smul, multilinear_map.smul_apply, ←multilinear_map.dom_coprod'_apply], simp only [tensor_product.add_tmul, ←tensor_product.smul_tmul', tensor_product.tmul_add, tensor_product.tmul_smul, linear_map.map_add, linear_map.map_smul], rw ←smul_add <|> rw smul_comm, congr } @[simp] lemma dom_coprod'_apply (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : dom_coprod' (a ⊗ₜ[R'] b) = dom_coprod a b := by simp only [dom_coprod', tensor_product.lift.tmul, linear_map.mk₂_apply] end alternating_map open equiv /-- A helper lemma for `multilinear_map.dom_coprod_alternization`. -/ lemma multilinear_map.dom_coprod_alternization_coe (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : multilinear_map.dom_coprod ↑a.alternatization ↑b.alternatization = ∑ (σa : perm ιa) (σb : perm ιb), σa.sign • σb.sign • multilinear_map.dom_coprod (a.dom_dom_congr σa) (b.dom_dom_congr σb) := begin simp_rw [←multilinear_map.dom_coprod'_apply, multilinear_map.alternatization_coe], simp_rw [tensor_product.sum_tmul, tensor_product.tmul_sum, linear_map.map_sum, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower], end open alternating_map /-- Computing the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` is the same as computing the `alternating_map.dom_coprod` of the `multilinear_map.alternatization`s. -/ lemma multilinear_map.dom_coprod_alternization (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : (multilinear_map.dom_coprod a b).alternatization = a.alternatization.dom_coprod b.alternatization := begin apply coe_multilinear_map_injective, rw [dom_coprod_coe, multilinear_map.alternatization_coe, finset.sum_partition (quotient_group.left_rel (perm.sum_congr_hom ιa ιb).range)], congr' 1, ext1 σ, apply σ.induction_on' (λ σ, _), -- unfold the quotient mess left by `finset.sum_partition` conv in (_ = quotient.mk' _) { change quotient.mk' _ = quotient.mk' _, rw quotient_group.eq' }, -- eliminate a multiplication have : @finset.univ (perm (ιa ⊕ ιb)) _ = finset.univ.image ((*) σ) := (finset.eq_univ_iff_forall.mpr $ λ a, let ⟨a', ha'⟩ := mul_left_surjective σ a in finset.mem_image.mpr ⟨a', finset.mem_univ _, ha'⟩).symm, rw [this, finset.image_filter], simp only [function.comp, mul_inv_rev, inv_mul_cancel_right, subgroup.inv_mem_iff], simp only [monoid_hom.mem_range], -- needs to be separate from the above `simp only` rw [finset.filter_congr_decidable, finset.univ_filter_exists (perm.sum_congr_hom ιa ιb), finset.sum_image (λ x _ y _ (h : _ = _), mul_right_injective _ h), finset.sum_image (λ x _ y _ (h : _ = _), perm.sum_congr_hom_injective h)], dsimp only, -- now we're ready to clean up the RHS, pulling out the summation rw [dom_coprod.summand_mk', multilinear_map.dom_coprod_alternization_coe, ←finset.sum_product', finset.univ_product_univ, ←multilinear_map.dom_dom_congr_equiv_apply, add_equiv.map_sum, finset.smul_sum], congr' 1, ext1 ⟨al, ar⟩, dsimp only, -- pull out the pair of smuls on the RHS, by rewriting to `_ →ₗ[ℤ] _` and back rw [←add_equiv.coe_to_add_monoid_hom, ←add_monoid_hom.coe_to_int_linear_map, linear_map.map_smul_of_tower, linear_map.map_smul_of_tower, add_monoid_hom.coe_to_int_linear_map, add_equiv.coe_to_add_monoid_hom, multilinear_map.dom_dom_congr_equiv_apply], -- pick up the pieces rw [multilinear_map.dom_dom_congr_mul, perm.sign_mul, perm.sum_congr_hom_apply, multilinear_map.dom_coprod_dom_dom_congr_sum_congr, perm.sign_sum_congr, mul_smul, mul_smul], end /-- Taking the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` of two `alternating_map`s gives a scaled version of the `alternating_map.coprod` of those maps. -/ lemma multilinear_map.dom_coprod_alternization_eq (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (multilinear_map.dom_coprod a b : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗ N₂)) .alternatization = ((fintype.card ιa).factorial * (fintype.card ιb).factorial) • a.dom_coprod b := begin rw [multilinear_map.dom_coprod_alternization, coe_alternatization, coe_alternatization, mul_smul, ←dom_coprod'_apply, ←dom_coprod'_apply, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower dom_coprod', linear_map.map_smul_of_tower dom_coprod'], -- typeclass resolution is a little confused here apply_instance, apply_instance, end end coprod section basis open alternating_map variables {ι₁ : Type*} [finite ι] variables {R' : Type*} {N₁ N₂ : Type*} [comm_semiring R'] [add_comm_monoid N₁] [add_comm_monoid N₂] variables [module R' N₁] [module R' N₂] /-- Two alternating maps indexed by a `fintype` are equal if they are equal when all arguments are distinct basis vectors. -/ lemma basis.ext_alternating {f g : alternating_map R' N₁ N₂ ι} (e : basis ι₁ R' N₁) (h : ∀ v : ι → ι₁, function.injective v → f (λ i, e (v i)) = g (λ i, e (v i))) : f = g := begin refine alternating_map.coe_multilinear_map_injective (basis.ext_multilinear e $ λ v, _), by_cases hi : function.injective v, { exact h v hi }, { have : ¬function.injective (λ i, e (v i)) := hi.imp function.injective.of_comp, rw [coe_multilinear_map, coe_multilinear_map, f.map_eq_zero_of_not_injective _ this, g.map_eq_zero_of_not_injective _ this], } end end basis /-! ### Currying -/ section currying variables {R' : Type*} {M'' M₂'' N'' N₂'': Type*} [comm_semiring R'] [add_comm_monoid M''] [add_comm_monoid M₂''] [add_comm_monoid N''] [add_comm_monoid N₂''] [module R' M''] [module R' M₂''] [module R' N''] [module R' N₂''] namespace alternating_map /-- Given an alternating map `f` in `n+1` variables, split the first variable to obtain a linear map into alternating maps in `n` variables, given by `x ↦ (m ↦ f (matrix.vec_cons x m))`. It can be thought of as a map $Hom(\bigwedge^{n+1} M, N) \to Hom(M, Hom(\bigwedge^n M, N))$. This is `multilinear_map.curry_left` for `alternating_map`. See also `alternating_map.curry_left_linear_map`. -/ @[simps] def curry_left {n : ℕ} (f : alternating_map R' M'' N'' (fin n.succ)) : M'' →ₗ[R'] alternating_map R' M'' N'' (fin n) := { to_fun := λ m, { to_fun := λ v, f (matrix.vec_cons m v), map_eq_zero_of_eq' := λ v i j hv hij, f.map_eq_zero_of_eq _ (by rwa [matrix.cons_val_succ, matrix.cons_val_succ]) ((fin.succ_injective _).ne hij), .. f.to_multilinear_map.curry_left m }, map_add' := λ m₁ m₂, ext $ λ v, f.map_vec_cons_add _ _ _, map_smul' := λ r m, ext $ λ v, f.map_vec_cons_smul _ _ _ } @[simp] lemma curry_left_zero {n : ℕ} : curry_left (0 : alternating_map R' M'' N'' (fin n.succ)) = 0 := rfl @[simp] lemma curry_left_add {n : ℕ} (f g : alternating_map R' M'' N'' (fin n.succ)) : curry_left (f + g) = curry_left f + curry_left g := rfl @[simp] lemma curry_left_smul {n : ℕ} (r : R') (f : alternating_map R' M'' N'' (fin n.succ)) : curry_left (r • f) = r • curry_left f := rfl /-- `alternating_map.curry_left` as a `linear_map`. This is a separate definition as dot notation does not work for this version. -/ @[simps] def curry_left_linear_map {n : ℕ} : alternating_map R' M'' N'' (fin n.succ) →ₗ[R'] M'' →ₗ[R'] alternating_map R' M'' N'' (fin n) := { to_fun := λ f, f.curry_left, map_add' := curry_left_add, map_smul' := curry_left_smul } /-- Currying with the same element twice gives the zero map. -/ @[simp] lemma curry_left_same {n : ℕ} (f : alternating_map R' M'' N'' (fin n.succ.succ)) (m : M'') : (f.curry_left m).curry_left m = 0 := ext $ λ x, f.map_eq_zero_of_eq _ (by simp) fin.zero_ne_one @[simp] lemma curry_left_comp_alternating_map {n : ℕ} (g : N'' →ₗ[R'] N₂'') (f : alternating_map R' M'' N'' (fin n.succ)) (m : M'') : (g.comp_alternating_map f).curry_left m = g.comp_alternating_map (f.curry_left m) := rfl @[simp] lemma curry_left_comp_linear_map {n : ℕ} (g : M₂'' →ₗ[R'] M'') (f : alternating_map R' M'' N'' (fin n.succ)) (m : M₂'') : (f.comp_linear_map g).curry_left m = (f.curry_left (g m)).comp_linear_map g := ext $ λ v, congr_arg f $ funext $ begin refine fin.cases _ _, { refl }, { simp } end /-- The space of constant maps is equivalent to the space of maps that are alternating with respect to an empty family. -/ @[simps] def const_linear_equiv_of_is_empty [is_empty ι] : N'' ≃ₗ[R'] alternating_map R' M'' N'' ι := { to_fun := alternating_map.const_of_is_empty R' M'', map_add' := λ x y, rfl, map_smul' := λ t x, rfl, inv_fun := λ f, f 0, left_inv := λ _, rfl, right_inv := λ f, ext $ λ x, alternating_map.congr_arg f $ subsingleton.elim _ _ } end alternating_map end currying
d73bb8d2f5929f2410a8bc6bfc35bdcccd2b3772
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/bool/default.lean
329ef32c708c5d02b56f34d55b8566a2ef30644d
[]
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
300
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.bool.basic import Mathlib.Lean3Lib.init.data.bool.lemmas namespace Mathlib
8187b72cece2c17b75c884296a0d061ba00c5900
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/category/default.lean
4f5e87155588147f0ad537ea42adce3151492793
[ "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
10,169
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import tactic.basic /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces, * `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ -- The order in this declaration matters: v often needs to be explicitly specified while u often -- can be omitted universes v u namespace category_theory /-- A 'notation typeclass' on the way to defining a category. -/ class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h section prio set_option default_priority 100 -- see Note [default priority] /-- A preliminary structure on the way to defining a category, containing the data, but none of the axioms. -/ class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) end prio -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma comp_dite {P : Prop} [decidable P] {X Y Z : C} (f : X ⟶ Y) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) : (f ≫ if h : P then g h else g' h) = (if h : P then f ≫ g h else f ≫ g' h) := by { split_ifs; refl } lemma dite_comp {P : Prop} [decidable P] {X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) : (if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) := by { split_ifs; refl } /-- A morphism `f` is an epimorphism if it can be "cancelled" when precomposed: `f ≫ g = f ≫ h` implies `g = h`. -/ class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) /-- A morphism `f` is a monomorphism if it can be "cancelled" when postcomposed: `g ≫ f = h ≫ f` implies `g = h`. -/ class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { substI h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by substI h; exact epi_of_epi f g end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory open category_theory /-! We now put a category instance on any preorder. Because we do not allow the morphisms of a category to live in `Prop`, unfortunately we need to use `plift` and `ulift` when defining the morphisms. As convenience functions, we provide `hom_of_le` and `le_of_hom` to wrap and unwrap inequalities. -/ namespace preorder variables (α : Type u) @[priority 100] -- see Note [lower instance priority] instance small_category [preorder α] : small_category α := { 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 ⟩ ⟩ } end preorder namespace category_theory variables {α : Type u} [preorder α] /-- Express an inequality as a morphism in the corresponding preorder category. -/ def hom_of_le {U V : α} (h : U ≤ V) : U ⟶ V := ulift.up (plift.up h) /-- Extract the underlying inequality from a morphism in a preorder category. -/ lemma le_of_hom {U V : α} (h : U ⟶ V) : U ≤ V := h.down.down end category_theory /-- Many proofs in the category theory library use the `dsimp, simp` pattern, which typically isn't necessary elsewhere. One would usually hope that the same effect could be achieved simply with `simp`. The essential issue is that composition of morphisms involves dependent types. When you have a chain of morphisms being composed, say `f : X ⟶ Y` and `g : Y ⟶ Z`, then `simp` can operate succesfully on the morphisms (e.g. if `f` is the identity it can strip that off). However if we have an equality of objects, say `Y = Y'`, then `simp` can't operate because it would break the typing of the composition operations. We rarely have interesting equalities of objects (because that would be "evil" --- anything interesting should be expressed as an isomorphism and tracked explicitly), except of course that we have plenty of definitional equalities of objects. `dsimp` can apply these safely, even inside a composition. After `dsimp` has cleared up the object level, `simp` can resume work on the morphism level --- but without the `dsimp` step, because `simp` looks at expressions syntactically, the relevant lemmas might not fire. There's no bound on how many times you potentially could have to switch back and forth, if the `simp` introduced new objects we again need to `dsimp`. In practice this does occur, but only rarely, because `simp` tends to shorten chains of compositions (i.e. not introduce new objects at all). -/ library_note "dsimp, simp"
0b4084f1505119c61a0347b335bde421de130a62
222111140d2023e142b07e9cd5119ac2829b36f5
/src/row_equivalence.lean
7d67ba073b56d80d582d3503d2f095aff3c6798b
[]
no_license
jjcrawford/lean-gaussian-elimination
740dfdf2de89dc99c088c53e5221d9dfad3c0b92
c473d33c07fa6f141d17d9dc42ad07956c33dd03
refs/heads/master
1,585,793,867,436
1,540,443,865,000
1,540,443,865,000
153,901,939
0
0
null
null
null
null
UTF-8
Lean
false
false
13,851
lean
import ring_theory.matrix import .finset_sum universes u variables {m n : ℕ} variable (α : Type u) variable [ring α] variable [decidable_eq α] inductive elementary (m : ℕ) | scale : Π (i₁ : fin m) (s : α) (hs : s ≠ 0), elementary | swap : Π (i₁ i₂ : fin m), elementary | linear_add : Π (i₁ : fin m) (s : α) (i₂ : fin m) (h : i₁ ≠ i₂), elementary variable {α} def elementary.to_matrix {m : ℕ} : elementary α m → matrix (fin m) (fin m) α | (elementary.scale i₁ s hs) := λ i j, if (i = j) then (if (i = i₁) then s else 1) else 0 | (elementary.swap _ i₁ i₂) := λ i j, if (i = i₁) then (if i₂ = j then 1 else 0) else if (i = i₂) then (if i₁ = j then 1 else 0) else if (i = j) then 1 else 0--if (i ≠i₁ ∧i ≠i₂) then (if i = j then 1 else 0) else (if i = i₁ then (if i₂ = j then 1 else 0) else (if i₁ = j then 1 else 0)) | (elementary.linear_add i₁ s i₂ h) := λ i j, if (i = j) then 1 else if (i = i₁) then if (j = i₂) then s else 0 else 0 -- λ i j, if (i = j) then (if i = i₁ then s else 1) else 0 --λ i j, if (i ≠ i) then (if i = j then 1 else 0) else (if j = i₁ then 1 else if j = i₂ then s else 0) def elementary.apply : elementary α m → (matrix (fin m) (fin n) α) → matrix (fin m) (fin n) α | (elementary.scale i₁ s hs) M := λ i j, if (i = i₁) then s * M i j else M i j | (elementary.swap _ i₁ i₂) M := λ i j, if (i = i₁) then M i₂ j else if (i = i₂) then M i₁ j else M i j | (elementary.linear_add i₁ s i₂ h) M := λ i j, if (i = i₁) then M i j + s * M i₂ j else M i j structure row_equivalent_step (M N : matrix (fin m) (fin n) α) := (elem : elementary α m) (implements : matrix.mul (elem.to_matrix) M = N) @[simp] lemma mul_scale_scaled {i : fin m} {j : fin n} {s : α} {h : s ≠ 0} {M : matrix (fin m) (fin n) α} : (matrix.mul (elementary.scale i s h).to_matrix M) i j = s * M i j := begin dsimp [matrix.mul], dsimp [elementary.to_matrix], simp, rw finset.sum_ite_zero, end @[simp] lemma mul_swap_swapped_1 {i₁ i₂ : fin m} {j : fin n} {M : matrix (fin m) (fin n) α} : (matrix.mul (elementary.swap _ i₁ i₂).to_matrix M) i₁ j = M i₂ j := begin rw matrix.mul, dsimp [elementary.to_matrix], simp, rw finset.sum_ite_zero, end #check decidable_of_decidable_of_iff @[simp] lemma decidable_of_decidable_of_iff_refl {p : Prop} (hp : decidable p) (h : p ↔ p) : decidable_of_decidable_of_iff hp h = hp := begin dsimp [decidable_of_decidable_of_iff], tactic.unfreeze_local_instances, cases hp, dsimp [dite], refl, dsimp [dite], refl, end -- set_option pp.implicit true @[simp] lemma mul_swap_swapped_2 {i₁ i₂ : fin m} {j : fin n} {M : matrix (fin m) (fin n) α} : (matrix.mul (elementary.swap _ i₁ i₂).to_matrix M) i₂ j = M i₁ j := begin dsimp [matrix.mul], dsimp [elementary.to_matrix], simp, by_cases h : (i₂ = i₁); simp[h], swap, rw finset.sum_ite_zero, -- simp, cases h, conv { -- This is still gross, and we should ask for help... congr,congr,skip,funext, rw decidable_of_decidable_of_iff_refl, rw decidable_of_decidable_of_iff_refl, }, rw finset.sum_ite_zero, -- can't believe this is necessary -- have H₁ : (@finset.sum (fin m) α (@semiring.to_add_comm_monoid α (@ring.to_semiring α _inst_1)) -- (@finset.univ (fin m) (fin.fintype m)) -- (λ (x : fin m), -- @ite (i₁ = x) -- (@decidable_of_decidable_of_iff (i₂ = x) (i₁ = x) -- (@decidable_of_decidable_of_iff (i₂ = x) (i₂ = x) (fin.decidable_eq m i₂ x) _) -- _) -- α -- (M x j) -- 0) = -- M i₁ j) = (@finset.sum (fin m) α (@semiring.to_add_comm_monoid α (@ring.to_semiring α _inst_1)) -- (@finset.univ (fin m) (fin.fintype m)) -- (λ (x : fin m), -- @ite (i₁ = x) (@decidable_of_decidable_of_iff (i₁ = x) (i₁ = x) (fin.decidable_eq m i₁ x) _) α (M x j) -- 0) = -- M i₁ j), -- congr, -- funext, -- by_cases h₂ : (i₁ = x); -- simp[h₂], -- rw H₁, -- show i₁ = x ↔ i₁ = x, refl, -- -- -- -- repeat{rw finset.sum_ite_zero}, end -- set_option pp.all true @[simp] lemma mul_linear_add_added {i₁ i₂ : fin m} {s : α} {j : fin n} {h : i₁ ≠ i₂} {M : matrix (fin m) (fin n) α} : (matrix.mul (elementary.linear_add i₁ s i₂ h).to_matrix M) i₁ j = M i₁ j + s * M i₂ j := begin dsimp[matrix.mul], dsimp[elementary.to_matrix], simp, -- have H₁ : (λ (x : fin m), ite (i₁ = x) (M x j) (ite (x = i₂) (s * M x j) 0)) = (λ (x : fin m), ite (i₁ = x) (M x j) (ite (i₂ = x) (s * M x j) 0)), -- funext, -- by_cases h₁ : (i₁ = x); simp[h₁], -- by_cases h₂ : (x = i₂); simp[h₂], -- simp[λ x, h₂ (eq.symm x)], have H₁ : finset.sum finset.univ (λ (x : fin m), ite (i₁ = x) (M x j) (ite (x = i₂) (s * M x j) 0)) = finset.sum finset.univ (λ (x : fin m), ite (i₁ = x) (M x j) (ite (i₂ = x) (s * M x j) 0)), congr, funext, by_cases h₁ : (i₁ = x); simp[h₁], by_cases h₂ : (x = i₂); simp[h₂], simp[λ x, h₂ (eq.symm x)], apply eq.trans, show α, from finset.sum finset.univ (λ (x : fin m), ite (i₁ = x) (M x j) (ite (i₂ = x) (s * M x j) 0)), -- from H₁, -- erw H₁, have H₂ : (@finset.sum (fin m) α (@semimodule.to_add_comm_monoid α α (@ring.to_semiring α _inst_1) (@semiring.to_semimodule α (@ring.to_semiring α _inst_1))) (@finset.univ (fin m) (fin.fintype m)) (λ (x : fin m), @ite (i₁ = x) (fin.decidable_eq m i₁ x) α (M x j) (@ite (x = i₂) (fin.decidable_eq m x i₂) α (s * M x j) 0)) = @finset.sum (fin m) α (@semimodule.to_add_comm_monoid α α (@ring.to_semiring α _inst_1) (@semiring.to_semimodule α (@ring.to_semiring α _inst_1))) (@finset.univ (fin m) (fin.fintype m)) (λ (x : fin m), @ite (i₁ = x) (fin.decidable_eq m i₁ x) α (M x j) (@ite (i₂ = x) (fin.decidable_eq m i₂ x) α (s * M x j) 0)) )=( @finset.sum (fin m) α (@semimodule.to_add_comm_monoid α α (@ring.to_semiring α _inst_1) (@semiring.to_semimodule α (@ring.to_semiring α _inst_1))) (@finset.univ (fin m) (fin.fintype m)) (λ (x : fin m), @ite (i₁ = x) (@decidable_of_decidable_of_iff (i₁ = x) (i₁ = x) (@decidable_of_decidable_of_iff (i₁ = x) (i₁ = x) (fin.decidable_eq m i₁ x) _) _) α (M x j) (@ite (x = i₂) (@decidable_of_decidable_of_iff (x = i₂) (x = i₂) (fin.decidable_eq m x i₂) _) α (s * M x j) 0)) = @finset.sum (fin m) α (@semimodule.to_add_comm_monoid α α (@ring.to_semiring α _inst_1) (@semiring.to_semimodule α (@ring.to_semiring α _inst_1))) (@finset.univ (fin m) (fin.fintype m)) (λ (x : fin m), @ite (i₁ = x) (fin.decidable_eq m i₁ x) α (M x j) (@ite (i₂ = x) (fin.decidable_eq m i₂ x) α (s * M x j) 0))), congr, funext, by_cases h₁ : (i₁ = x); simp[h₁], by_cases h₂ : (x = i₂); simp[h₂], simp[H₂] at H₁, from H₁, clear H₁, have H₁, from @finset.sum_ite_zero₂ (fin m) _ _ i₁ i₂ α _ _ (λ i, M i j) (λ i, s * (M i j)) h, simp at H₁, apply eq.trans, from H₁, simp, end lemma elementary.mul_eq_apply : Π {M : matrix (fin m) (fin n) α} (e : elementary α m), ((e.to_matrix).mul M) = (e.apply M) := begin intros, cases e with i₁ s hs i₁ i₂ i₁ s i₂, -- scale case by { funext i j, simp[matrix.mul,elementary.apply,elementary.to_matrix,finset.sum_ite_zero], by_cases h : (i = i₁); simp[h], }, -- swap case by { funext i j, by_cases h : (i = i₁), simp[h, elementary.apply], by_cases h₁ : (i = i₂), simp[h₁, elementary.apply], rw ←h₁, repeat{simp[h, h₁, matrix.mul, elementary.apply,elementary.to_matrix, finset.sum_ite_zero]} }, -- linear_add case by { funext i j, by_cases h : (i = i₁), simp[h,elementary.apply], simp[matrix.mul, elementary.apply, elementary.to_matrix, h,finset.sum_ite_zero], } end def row_equivalent_step.of_elementary : Π {M : matrix (fin m) (fin n) α} (e : elementary α m), row_equivalent_step M ((e.to_matrix).mul M) := begin intros, cases e; {constructor, refl} end def row_equivalent_step.of_elementary_apply : Π {M : matrix (fin m) (fin n) α} (e : elementary α m), row_equivalent_step M (e.apply M) := begin intros, have H₃ : row_equivalent_step M (elementary.apply e M) = row_equivalent_step M (matrix.mul (elementary.to_matrix e) M), congr, from eq.symm(@elementary.mul_eq_apply m n α _ _ M e), rw H₃, from @row_equivalent_step.of_elementary m n α _ _ M e, end def row_equivalent_step.to_matrix : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent_step M N), matrix (fin m) (fin m) α := λ M N r, r.elem.to_matrix def row_equivalent_step.apply : Π (L : matrix (fin m) (fin n) α) {M N : matrix (fin m) (fin n) α} (r : row_equivalent_step M N), matrix (fin m) (fin n) α := λ L M N r, r.elem.apply L -- def row_equivalent_step.of_elementary : Π @[simp] lemma row_equivalent_step.matrix_implements : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent_step M N), (r.to_matrix).mul M = N := begin intros, cases r with elem implements, unfold row_equivalent_step.to_matrix, simp, assumption end @[simp] lemma row_equivalent_step.apply_implements : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent_step M N), r.apply M = N := begin intros, cases r with elem implements, unfold row_equivalent_step.apply, simp, rw ←elementary.mul_eq_apply, assumption, end inductive row_equivalent : matrix (fin m) (fin n) α → matrix (fin m) (fin n) α → Type u | nil : Π {N : matrix (fin m) (fin n) α}, row_equivalent N N | cons : Π {N M L : matrix (fin m) (fin n) α} (h₁ : row_equivalent N M) (h₂ : row_equivalent_step M L), row_equivalent N L def row_equivalent.of_step : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent_step M N), row_equivalent M N := λ _ _ r, row_equivalent.cons (row_equivalent.nil) r instance row_equivalent_step.has_coe_row_equivalent : Π {M N : matrix (fin m) (fin n) α}, has_coe (row_equivalent_step M N) (row_equivalent M N) := λ M N, ⟨λ r, row_equivalent.of_step r⟩ def row_equivalent.to_matrix : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent M N), matrix (fin m) (fin m) α | M N (row_equivalent.nil) := (1 : matrix (fin m) (fin m) α) | M N (row_equivalent.cons r₁ r₂) := (row_equivalent_step.to_matrix r₂).mul (row_equivalent.to_matrix r₁) def row_equivalent.apply (L : matrix (fin m) (fin n) α) : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent M N), matrix (fin m) (fin n) α | M N (row_equivalent.nil) := L | M N (row_equivalent.cons r₁ r₂) := (@elementary.apply m n α _ _ (row_equivalent_step.elem r₂)) (row_equivalent.apply r₁) @[simp] lemma row_equiv_nil {M : matrix (fin m) (fin n) α} : row_equivalent.to_matrix (@row_equivalent.nil m n α _ _ M) = (1 : matrix (fin m) (fin m) α) := by simp[row_equivalent.to_matrix] @[simp] lemma row_equiv_cons {M N L : matrix (fin m) (fin n) α} {r₁ : row_equivalent N M} {r₂ : row_equivalent_step M L}: row_equivalent.to_matrix (@row_equivalent.cons m n α _ _ N M L r₁ r₂) = (row_equivalent_step.to_matrix r₂).mul (row_equivalent.to_matrix r₁) := by simp[row_equivalent.to_matrix] @[simp] lemma row_equivalent.matrix_implements : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent M N), (r.to_matrix).mul M = N | M N (row_equivalent.nil) := by simp[row_equiv_nil, matrix.one_mul] | M N (row_equivalent.cons r₁ r₂) := begin rw row_equiv_cons, rw matrix.mul_assoc, rw row_equivalent.matrix_implements, apply row_equivalent_step.matrix_implements, end -- set_option pp.all true @[simp] lemma row_equivalent.apply_implements : Π {M N : matrix (fin m) (fin n) α} (r : row_equivalent M N), r.apply M = N | M N (row_equivalent.nil) := by simp[row_equivalent.apply] | M N (@row_equivalent.cons _ _ _ _ _ _ L _ r₁ r₂) := begin simp[row_equivalent.apply], have H₁, from row_equivalent.apply_implements r₁, have H₂ : elementary.apply (r₂.elem) (row_equivalent.apply M r₁) = elementary.apply (r₂.elem) L, congr, from H₁, rw H₂, apply row_equivalent_step.apply_implements, end theorem row_equivalent.mul_eq_apply : Π {M N : matrix (fin m) (fin n) α} (r₁ : row_equivalent M N), r₁.to_matrix.mul M = r₁.apply M := begin intros, cases r₁, simp[row_equivalent.to_matrix, row_equivalent.apply, matrix.one_mul], simp[row_equivalent.to_matrix, matrix.mul_assoc], end def row_equivalent.trans {M N L : (matrix (fin m) (fin n) α)} : (row_equivalent M N) → (row_equivalent N L) → row_equivalent M L := begin intros r₁ r₂, induction r₂ with M₁ M₁ N₁ L₁ h₁ h₂ h₃, from r₁, from row_equivalent.cons (h₃ r₁) h₂, end def row_equivalent.precons : Π {M N L : matrix (fin m) (fin n) α}, row_equivalent_step M N → row_equivalent N L → row_equivalent M L := begin intros M N L r₀ r₁, induction r₁ with M₁ M₁ N₁ L₁ h₁ h₂ h₃, from r₀, from row_equivalent.cons (h₃ r₀) h₂, end
38b1acea0b247e6adddae53acb1aa6043d2391b4
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/category_theory/instances/topological_spaces.lean
bae1d02ab994a485d207c7aa83e5e3d6dd2e51aa
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
5,371
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Scott Morrison, Mario Carneiro import category_theory.concrete_category import category_theory.full_subcategory import category_theory.functor_category import category_theory.adjunction import category_theory.limits.types import category_theory.natural_isomorphism import category_theory.eq_to_hom import topology.basic import topology.opens import order.galois_connection open category_theory open category_theory.nat_iso open topological_space universe u namespace category_theory.instances /-- The category of topological spaces and continuous maps. -/ @[reducible] def Top : Type (u+1) := bundled topological_space instance (x : Top) : topological_space x := x.str namespace Top instance : concrete_category @continuous := ⟨@continuous_id, @continuous.comp⟩ -- local attribute [class] continuous -- instance {R S : Top} (f : R ⟶ S) : continuous (f : R → S) := f.2 section open category_theory.limits variables {J : Type u} [small_category J] def limit (F : J ⥤ Top.{u}) : cone F := { X := ⟨limit (F ⋙ forget), ⨆ j, (F.obj j).str.induced (limit.π (F ⋙ forget) j)⟩, π := { app := λ j, ⟨limit.π (F ⋙ forget) j, continuous_iff_induced_le.mpr (lattice.le_supr _ j)⟩, naturality' := λ j j' f, subtype.eq ((limit.cone (F ⋙ forget)).π.naturality f) } } def limit_is_limit (F : J ⥤ Top.{u}) : is_limit (limit F) := by refine is_limit.of_faithful forget (limit.is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl); exact continuous_iff_le_coinduced.mpr (lattice.supr_le $ λ j, induced_le_iff_le_coinduced.mpr $ continuous_iff_le_coinduced.mp (s.π.app j).property) instance : has_limits.{u} Top.{u} := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } } instance : preserves_limits (forget : Top.{u} ⥤ Type u) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (limit.is_limit (F ⋙ forget)) } } def colimit (F : J ⥤ Top.{u}) : cocone F := { X := ⟨colimit (F ⋙ forget), ⨅ j, (F.obj j).str.coinduced (colimit.ι (F ⋙ forget) j)⟩, ι := { app := λ j, ⟨colimit.ι (F ⋙ forget) j, continuous_iff_le_coinduced.mpr (lattice.infi_le _ j)⟩, naturality' := λ j j' f, subtype.eq ((colimit.cocone (F ⋙ forget)).ι.naturality f) } } def colimit_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit F) := by refine is_colimit.of_faithful forget (colimit.is_colimit _) (λ s, ⟨_, _⟩) (λ s, rfl); exact continuous_iff_induced_le.mpr (lattice.le_infi $ λ j, induced_le_iff_le_coinduced.mpr $ continuous_iff_le_coinduced.mp (s.ι.app j).property) instance : has_colimits.{u} Top.{u} := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } } } instance : preserves_colimits (forget : Top.{u} ⥤ Type u) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (colimit.is_colimit (F ⋙ forget)) } } end def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, ⟨f, continuous_top⟩ } def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, ⟨f, continuous_bot⟩ } def adj₁ : adjunction discrete forget := { hom_equiv := λ X Y, { to_fun := λ f, f, inv_fun := λ f, ⟨f, continuous_top⟩, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, id }, counit := { app := λ X, ⟨id, continuous_top⟩ } } def adj₂ : adjunction forget trivial := { hom_equiv := λ X Y, { to_fun := λ f, ⟨f, continuous_bot⟩, inv_fun := λ f, f, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, ⟨id, continuous_bot⟩ }, counit := { app := λ X, id } } end Top variables {X : Top.{u}} instance : small_category (opens X) := by apply_instance def nbhd (x : X.α) := { U : opens X // x ∈ U } def nbhds (x : X.α) : small_category (nbhd x) := begin unfold nbhd, apply_instance end end category_theory.instances open category_theory.instances namespace topological_space.opens /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map {X Y : Top.{u}} (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f.val ⁻¹' U, f.property _ U.property ⟩, map := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }. @[simp] lemma map_id_obj (X : Top.{u}) (U : opens X) : (map (𝟙 X)).obj U = U := by tidy @[simp] def map_id (X : Top.{u}) : map (𝟙 X) ≅ functor.id (opens X) := { hom := { app := λ U, 𝟙 U }, inv := { app := λ U, 𝟙 U } } -- 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 {X Y : Top.{u}} (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg _ (congr_arg _ h)) _) ) (by obviously) @[simp] def map_iso_id {X : Top.{u}} (h) : map_iso (𝟙 X) (𝟙 X) h = iso.refl (map _) := rfl end topological_space.opens
b6fb270b1312da7346010425c8f57b1ca6519d7a
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Elab/Tactic/Induction.lean
33cb49ee35adef33cfbfac8f194890b757e91a10
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,506
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectFVars import Lean.Parser.Term import Lean.Meta.RecursorInfo import Lean.Meta.CollectMVars import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeVars import Lean.Elab.App import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Generalize namespace Lean.Elab.Tactic open Meta /- Given an `inductionAlt` of the form ``` nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser ``` -/ private def getAltName (alt : Syntax) : Name := -- alt[1] is of the form (("@"? ident) <|> "_") if alt[1].hasArgs then alt[1][1].getId.eraseMacroScopes else `_ private def altHasExplicitModifier (alt : Syntax) : Bool := alt[1].hasArgs && !alt[1][0].isNone private def getAltVarNames (alt : Syntax) : Array Name := alt[2].getArgs.map getNameOfIdent' private def getAltRHS (alt : Syntax) : Syntax := alt[4] private def getAltDArrow (alt : Syntax) : Syntax := alt[3] -- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic def isHoleRHS (rhs : Syntax) : Bool := rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole def evalAlt (mvarId : MVarId) (alt : Syntax) (remainingGoals : Array MVarId) : TacticM (Array MVarId) := let rhs := getAltRHS alt withCaseRef (getAltDArrow alt) rhs do if isHoleRHS rhs then let gs' ← withMVarContext mvarId $ withRef rhs do let mvarDecl ← getMVarDecl mvarId let val ← elabTermEnsuringType rhs mvarDecl.type assignExprMVar mvarId val let gs' ← getMVarsNoDelayed val tagUntaggedGoals mvarDecl.userName `induction gs'.toList pure gs' return remainingGoals ++ gs' else setGoals [mvarId] closeUsingOrAdmit (withTacticInfoContext alt (evalTactic rhs)) return remainingGoals /- Helper method for creating an user-defined eliminator/recursor application. -/ namespace ElimApp structure Context where elimInfo : ElimInfo targets : Array Expr -- targets provided by the user structure State where argPos : Nat := 0 -- current argument position targetPos : Nat := 0 -- current target at targetsStx f : Expr fType : Expr alts : Array (Name × MVarId) := #[] insts : Array MVarId := #[] abbrev M := ReaderT Context $ StateRefT State TermElabM private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! private def getFType : M Expr := do let fType ← whnfForall (← get).fType modify fun s => { s with fType := fType } pure fType structure Result where elimApp : Expr alts : Array (Name × MVarId) := #[] others : Array MVarId := #[] /-- Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for the eliminator. For example, the indices of builtin recursors are considered implicit targets. Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets from the explicit ones. -/ partial def mkElimApp (elimName : Name) (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do let rec loop : M Unit := do match (← getFType) with | Expr.forallE binderName _ _ c => let ctx ← read let argPos := (← get).argPos if ctx.elimInfo.motivePos == argPos then let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque addNewArg motive else if ctx.elimInfo.targetsPos.contains argPos then let s ← get let ctx ← read unless s.targetPos < ctx.targets.size do throwError "insufficient number of targets for '{elimName}'" let target := ctx.targets[s.targetPos] let expectedType ← getArgExpectedType let target ← Term.ensureHasType expectedType target modify fun s => { s with targetPos := s.targetPos + 1 } addNewArg target else match c.binderInfo with | BinderInfo.implicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.strictImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.instImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName) modify fun s => { s with insts := s.insts.push arg.mvarId! } addNewArg arg | _ => let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName) let x ← getBindingName modify fun s => { s with alts := s.alts.push (x, arg.mvarId!) } addNewArg arg loop | _ => pure () let f ← Term.mkConst elimName let fType ← inferType f let (_, s) ← loop.run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType } let mut others := #[] for mvarId in s.insts do try unless (← Term.synthesizeInstMVarCore mvarId) do setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId catch _ => setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId return { elimApp := (← instantiateMVars s.f), alts := s.alts, others := others } /- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign `motiveArg := fun targets => C[targets]` -/ def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do let type ← inferType (mkMVar mvarId) let motive ← mkLambdaFVars (targets.map mkFVar) type let motiverInferredType ← inferType motive let motiveType ← inferType (mkMVar motiveArg) unless (← isDefEqGuarded motiverInferredType motiveType) do throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}" assignExprMVar motiveArg motive private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do for altInfo in elimInfo.altsInfo do if altInfo.name == altName then return altInfo.numFields throwError "unknown alternative name '{altName}'" private def checkAltNames (alts : Array (Name × MVarId)) (altsSyntax : Array Syntax) : TacticM Unit := for altStx in altsSyntax do let altName := getAltName altStx if altName != `_ then unless alts.any fun (n, _) => n == altName do throwErrorAt altStx "invalid alternative name '{altName}'" def evalAlts (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (optPreTac : Syntax) (altsSyntax : Array Syntax) (initialInfo : Info) (numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do checkAltNames alts altsSyntax let hasAlts := altsSyntax.size > 0 if hasAlts then -- default to initial state outside of alts withInfoContext go initialInfo else go where go := do let hasAlts := altsSyntax.size > 0 let mut usedWildcard := false let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here let mut altsSyntax := altsSyntax for (altName, altMVarId) in alts do let numFields ← getAltNumFields elimInfo altName let mut isWildcard := false let altStx? ← match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with | some idx => let altStx := altsSyntax[idx] altsSyntax := altsSyntax.eraseIdx idx pure (some altStx) | none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with | some idx => isWildcard := true pure (some altsSyntax[idx]) | none => pure none match altStx? with | none => let mut (_, altMVarId) ← introN altMVarId numFields match (← Cases.unifyEqs numEqs altMVarId {}) with | none => pure () -- alternative is not reachable | some (altMVarId', _) => (_, altMVarId) ← introNP altMVarId' numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if !hasAlts then -- User did not provide alternatives using `|` subgoals := subgoals ++ altMVarIds.toArray else if altMVarIds.isEmpty then pure () else logError m!"alternative '{altName}' has not been provided" altMVarIds.forM fun mvarId => admitGoal mvarId | some altStx => (subgoals, usedWildcard) ← withRef altStx do let unusedAlt := if isWildcard then pure (#[], usedWildcard) else throwError "alternative '{altName}' is not needed" let altVarNames := getAltVarNames altStx if altVarNames.size > numFields then logError m!"too many variable names provided at alternative '{altName}', #{altVarNames.size} provided, but #{numFields} expected" let mut (_, altMVarId) ← introN altMVarId numFields altVarNames.toList (useNamesForExplicitOnly := !altHasExplicitModifier altStx) match (← Cases.unifyEqs numEqs altMVarId {}) with | none => unusedAlt | some (altMVarId', _) => (_, altMVarId) ← introNP altMVarId' numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if altMVarIds.isEmpty then unusedAlt else let mut subgoals := subgoals for altMVarId' in altMVarIds do subgoals ← evalAlt altMVarId' altStx subgoals pure (subgoals, usedWildcard || isWildcard) if usedWildcard then altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_ unless altsSyntax.isEmpty do logErrorAt altsSyntax[0] "unused alternative" setGoals subgoals.toList applyPreTac (mvarId : MVarId) : TacticM (List MVarId) := if optPreTac.isNone then return [mvarId] else evalTacticAt optPreTac[0] mvarId end ElimApp /- Recall that ``` generalizingVars := optional (" generalizing " >> many1 ident) «induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts ``` `stx` is syntax for `induction`. -/ private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) := withRef stx do let generalizingStx := stx[3] if generalizingStx.isNone then pure #[] else trace[Elab.induction] "{generalizingStx}" let vars := generalizingStx[1].getArgs getFVarIds vars -- process `generalizingVars` subterm of induction Syntax `stx`. private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) := withMVarContext mvarId do let userFVarIds ← getUserGeneralizingFVarIds stx let forbidden ← mkGeneralizationForbiddenSet targets let mut s ← getFVarSetToGeneralize targets forbidden for userFVarId in userFVarIds do if forbidden.contains userFVarId then throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}" if s.contains userFVarId then throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically" s := s.insert userFVarId let fvarIds ← sortFVars s let (fvarIds, mvarId') ← Meta.revert mvarId fvarIds return (fvarIds.size, mvarId') -- syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax := inductionAlts[2].getArgs private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax := if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0] private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax := if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1] /- We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names. The idea is to make sure users do not write unstructured tactics. -/ private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit := unless optInductionAlts.isNone do let mut found := false for alt in getAltsOfInductionAlts optInductionAlts[0] do let n := getAltName alt if n == `_ then unless (getAltVarNames alt).isEmpty do throwErrorAt alt "wildcard alternative must not specify variable names" if found then throwErrorAt alt "more than one wildcard alternative '| _ => ...' used" found := true def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal := liftMetaMAtMain fun mvarId => do let majorType ← inferType major let majorType ← whnf majorType matchConstInduct majorType.getAppFn (fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}") (fun val _ => pure val) private def generalizeTerm (term : Expr) : TacticM Expr := do match term with | Expr.fvar .. => pure term | _ => liftMetaTacticAux fun mvarId => do let mvarId ← Meta.generalize mvarId term `x false let (fvarId, mvarId) ← Meta.intro1 mvarId pure (mkFVar fvarId, [mvarId]) -- `optElimId` is of the form `("using" ident)?` private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM (Name × ElimInfo) := do if optElimId.isNone then unless targets.size == 1 do throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>')" let indVal ← getInductiveValFromMajor targets[0] let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name pure (elimName, ← getElimInfo elimName) else let elimId := optElimId[1] let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId pure (elimName, ← withRef elimId do getElimInfo elimName) @[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focus do let targets ← stx[1].getSepArgs.mapM fun target => do let target ← withMainContext <| elabTerm target none generalizeTerm target let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := true) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets checkTargets targets let targetFVarIds := targets.map (·.fvarId!) let (n, mvarId) ← generalizeVars mvarId stx targets withMVarContext mvarId do let result ← withRef stx[1] do -- use target position as reference ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let motiveType ← inferType elimArgs[elimInfo.motivePos] ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetFVarIds let optInductionAlts := stx[4] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds) appendGoals result.others.toList where checkTargets (targets : Array Expr) : MetaM Unit := do let mut foundFVars : NameSet := {} for target in targets do unless target.isFVar do throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}" if foundFVars.contains target.fvarId! then throwError "target (or one of its indices) occurs more than once{indentExpr target}" -- Recall that -- majorPremise := leading_parser optional (try (ident >> " : ")) >> termParser private def getTargetHypothesisName? (target : Syntax) : Option Name := if target[0].isNone then none else some target[0][0].getId private def getTargetTerm (target : Syntax) : Syntax := target[1] private def elabTaggedTerm (h? : Option Name) (termStx : Syntax) : TacticM Expr := withMainContext <| withRef termStx do let term ← elabTerm termStx none match h? with | none => pure term | some h => let lctx ← getLCtx let x ← mkFreshUserName `x evalGeneralizeAux h? term x withMainContext do let lctx ← getLCtx match lctx.findFromUserName? x with | some decl => pure decl.toExpr | none => throwError "failed to generalize" def elabTargets (targets : Array Syntax) : TacticM (Array Expr) := targets.mapM fun target => do let h? := getTargetHypothesisName? target let term ← elabTaggedTerm h? (getTargetTerm target) generalizeTerm term builtin_initialize registerTraceClass `Elab.cases @[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focus do -- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts let targets ← elabTargets stx[1].getSepArgs let optInductionAlts := stx[3] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts let targetRef := stx[1] let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := false) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets let result ← withRef targetRef <| ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i] let motiveType ← inferType elimArgs[elimInfo.motivePos] let mvarId ← generalizeTargets mvarId motiveType targets let (targetsNew, mvarId) ← introN mvarId targets.size withMVarContext mvarId do ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetsNew assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew) end Lean.Elab.Tactic
849013cc24e891e739c82176135d3ee3702a76a1
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/polynomial_algebra.lean
b977392f2a406e74da4b5c3f253864dfa5ec9ae3
[ "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
10,811
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import ring_theory.matrix_algebra import data.polynomial.algebra_map /-! # Algebra isomorphism between matrices of polynomials and polynomials of matrices Given `[comm_ring R] [ring A] [algebra R A]` we show `polynomial A ≃ₐ[R] (A ⊗[R] polynomial R)`. Combining this with the isomorphism `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)` proved earlier in `ring_theory.matrix_algebra`, we obtain the algebra isomorphism ``` def mat_poly_equiv : matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R) ``` which is characterized by ``` coeff (mat_poly_equiv m) k i j = coeff (m i j) k ``` We will use this algebra isomorphism to prove the Cayley-Hamilton theorem. -/ universes u v w open_locale tensor_product open polynomial open tensor_product open algebra.tensor_product (alg_hom_of_linear_map_tensor_product include_left) noncomputable theory variables (R A : Type*) variables [comm_semiring R] variables [semiring A] [algebra R A] namespace poly_equiv_tensor /-- (Implementation detail). The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, as a bilinear function of two arguments. -/ @[simps apply_apply] def to_fun_bilinear : A →ₗ[A] polynomial R →ₗ[R] polynomial A := linear_map.to_span_singleton A _ (aeval (polynomial.X : polynomial A)).to_linear_map lemma to_fun_bilinear_apply_eq_sum (a : A) (p : polynomial R) : to_fun_bilinear R A a p = p.sum (λ n r, monomial n (a * algebra_map R A r)) := begin dsimp [to_fun_bilinear_apply_apply, aeval_def, eval₂_eq_sum, polynomial.sum], rw finset.smul_sum, congr' with i : 1, rw [←algebra.smul_def, ←C_mul', mul_smul_comm, C_mul_X_pow_eq_monomial, ←algebra.commutes, ←algebra.smul_def, smul_monomial], end /-- (Implementation detail). The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, as a linear map. -/ def to_fun_linear : A ⊗[R] polynomial R →ₗ[R] polynomial A := tensor_product.lift (to_fun_bilinear R A) @[simp] lemma to_fun_linear_tmul_apply (a : A) (p : polynomial R) : to_fun_linear R A (a ⊗ₜ[R] p) = to_fun_bilinear R A a p := lift.tmul _ _ -- We apparently need to provide the decidable instance here -- in order to successfully rewrite by this lemma. lemma to_fun_linear_mul_tmul_mul_aux_1 (p : polynomial R) (k : ℕ) (h : decidable (¬p.coeff k = 0)) (a : A) : ite (¬coeff p k = 0) (a * (algebra_map R A) (coeff p k)) 0 = a * (algebra_map R A) (coeff p k) := by { classical, split_ifs; simp *, } lemma to_fun_linear_mul_tmul_mul_aux_2 (k : ℕ) (a₁ a₂ : A) (p₁ p₂ : polynomial R) : a₁ * a₂ * (algebra_map R A) ((p₁ * p₂).coeff k) = (finset.nat.antidiagonal k).sum (λ x, a₁ * (algebra_map R A) (coeff p₁ x.1) * (a₂ * (algebra_map R A) (coeff p₂ x.2))) := begin simp_rw [mul_assoc, algebra.commutes, ←finset.mul_sum, mul_assoc, ←finset.mul_sum], congr, simp_rw [algebra.commutes (coeff p₂ _), coeff_mul, ring_hom.map_sum, ring_hom.map_mul], end lemma to_fun_linear_mul_tmul_mul (a₁ a₂ : A) (p₁ p₂ : polynomial R) : (to_fun_linear R A) ((a₁ * a₂) ⊗ₜ[R] (p₁ * p₂)) = (to_fun_linear R A) (a₁ ⊗ₜ[R] p₁) * (to_fun_linear R A) (a₂ ⊗ₜ[R] p₂) := begin simp only [to_fun_linear_tmul_apply, to_fun_bilinear_apply_eq_sum], ext k, simp_rw [coeff_sum, coeff_monomial, sum_def, finset.sum_ite_eq', mem_support_iff, ne.def], conv_rhs { rw [coeff_mul] }, simp_rw [finset_sum_coeff, coeff_monomial, finset.sum_ite_eq', mem_support_iff, ne.def, mul_ite, mul_zero, ite_mul, zero_mul], simp_rw [ite_mul_zero_left (¬coeff p₁ _ = 0) (a₁ * (algebra_map R A) (coeff p₁ _))], simp_rw [ite_mul_zero_right (¬coeff p₂ _ = 0) _ (_ * _)], simp_rw [to_fun_linear_mul_tmul_mul_aux_1, to_fun_linear_mul_tmul_mul_aux_2], end lemma to_fun_linear_algebra_map_tmul_one (r : R) : (to_fun_linear R A) ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R (polynomial A)) r := by rw [to_fun_linear_tmul_apply, to_fun_bilinear_apply_apply, polynomial.aeval_one, algebra_map_smul, algebra.algebra_map_eq_smul_one] /-- (Implementation detail). The algebra homomorphism `A ⊗[R] polynomial R →ₐ[R] polynomial A`. -/ def to_fun_alg_hom : A ⊗[R] polynomial R →ₐ[R] polynomial A := alg_hom_of_linear_map_tensor_product (to_fun_linear R A) (to_fun_linear_mul_tmul_mul R A) (to_fun_linear_algebra_map_tmul_one R A) @[simp] lemma to_fun_alg_hom_apply_tmul (a : A) (p : polynomial R) : to_fun_alg_hom R A (a ⊗ₜ[R] p) = p.sum (λ n r, monomial n (a * (algebra_map R A) r)) := begin dsimp [to_fun_alg_hom], rw [to_fun_linear_tmul_apply, to_fun_bilinear_apply_eq_sum], end /-- (Implementation detail.) The bare function `polynomial A → A ⊗[R] polynomial R`. (We don't need to show that it's an algebra map, thankfully --- just that it's an inverse.) -/ def inv_fun (p : polynomial A) : A ⊗[R] polynomial R := p.eval₂ (include_left : A →ₐ[R] A ⊗[R] polynomial R) ((1 : A) ⊗ₜ[R] (X : polynomial R)) @[simp] lemma inv_fun_add {p q} : inv_fun R A (p + q) = inv_fun R A p + inv_fun R A q := by simp only [inv_fun, eval₂_add] lemma inv_fun_monomial (n : ℕ) (a : A) : inv_fun R A (monomial n a) = include_left a * ((1 : A) ⊗ₜ[R] (X : polynomial R)) ^ n := eval₂_monomial _ _ lemma left_inv (x : A ⊗ polynomial R) : inv_fun R A ((to_fun_alg_hom R A) x) = x := begin apply tensor_product.induction_on x, { simp [inv_fun], }, { intros a p, dsimp only [inv_fun], rw [to_fun_alg_hom_apply_tmul, eval₂_sum], simp_rw [eval₂_monomial, alg_hom.coe_to_ring_hom, algebra.tensor_product.tmul_pow, one_pow, algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_mul_tmul, mul_one, one_mul, ←algebra.commutes, ←algebra.smul_def'', smul_tmul, sum_def, ←tmul_sum], conv_rhs { rw [←sum_C_mul_X_eq p], }, simp only [algebra.smul_def''], refl, }, { intros p q hp hq, simp only [alg_hom.map_add, inv_fun_add, hp, hq], }, end lemma right_inv (x : polynomial A) : (to_fun_alg_hom R A) (inv_fun R A x) = x := begin apply polynomial.induction_on' x, { intros p q hp hq, simp only [inv_fun_add, alg_hom.map_add, hp, hq], }, { intros n a, rw [inv_fun_monomial, algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_pow, one_pow, algebra.tensor_product.tmul_mul_tmul, mul_one, one_mul, to_fun_alg_hom_apply_tmul, X_pow_eq_monomial, sum_monomial_index]; simp, } end /-- (Implementation detail) The equivalence, ignoring the algebra structure, `(A ⊗[R] polynomial R) ≃ polynomial A`. -/ def equiv : (A ⊗[R] polynomial R) ≃ polynomial A := { to_fun := to_fun_alg_hom R A, inv_fun := inv_fun R A, left_inv := left_inv R A, right_inv := right_inv R A, } end poly_equiv_tensor open poly_equiv_tensor /-- The `R`-algebra isomorphism `polynomial A ≃ₐ[R] (A ⊗[R] polynomial R)`. -/ def poly_equiv_tensor : polynomial A ≃ₐ[R] (A ⊗[R] polynomial R) := alg_equiv.symm { ..(poly_equiv_tensor.to_fun_alg_hom R A), ..(poly_equiv_tensor.equiv R A) } @[simp] lemma poly_equiv_tensor_apply (p : polynomial A) : poly_equiv_tensor R A p = p.eval₂ (include_left : A →ₐ[R] A ⊗[R] polynomial R) ((1 : A) ⊗ₜ[R] (X : polynomial R)) := rfl @[simp] lemma poly_equiv_tensor_symm_apply_tmul (a : A) (p : polynomial R) : (poly_equiv_tensor R A).symm (a ⊗ₜ p) = p.sum (λ n r, monomial n (a * algebra_map R A r)) := to_fun_alg_hom_apply_tmul _ _ _ _ open dmatrix matrix open_locale big_operators variables {R} variables {n : Type w} [decidable_eq n] [fintype n] /-- The algebra isomorphism stating "matrices of polynomials are the same as polynomials of matrices". (You probably shouldn't attempt to use this underlying definition --- it's an algebra equivalence, and characterised extensionally by the lemma `mat_poly_equiv_coeff_apply` below.) -/ noncomputable def mat_poly_equiv : matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R) := (((matrix_equiv_tensor R (polynomial R) n)).trans (algebra.tensor_product.comm R _ _)).trans (poly_equiv_tensor R (matrix n n R)).symm open finset lemma mat_poly_equiv_coeff_apply_aux_1 (i j : n) (k : ℕ) (x : R) : mat_poly_equiv (std_basis_matrix i j $ monomial k x) = monomial k (std_basis_matrix i j x) := begin simp only [mat_poly_equiv, alg_equiv.trans_apply, matrix_equiv_tensor_apply_std_basis], apply (poly_equiv_tensor R (matrix n n R)).injective, simp only [alg_equiv.apply_symm_apply], convert algebra.tensor_product.comm_tmul _ _ _ _ _, simp only [poly_equiv_tensor_apply], convert eval₂_monomial _ _, simp only [algebra.tensor_product.tmul_mul_tmul, one_pow, one_mul, matrix.mul_one, algebra.tensor_product.tmul_pow, algebra.tensor_product.include_left_apply, mul_eq_mul], rw [monomial_eq_smul_X, ← tensor_product.smul_tmul], congr' with i' j'; simp end lemma mat_poly_equiv_coeff_apply_aux_2 (i j : n) (p : polynomial R) (k : ℕ) : coeff (mat_poly_equiv (std_basis_matrix i j p)) k = std_basis_matrix i j (coeff p k) := begin apply polynomial.induction_on' p, { intros p q hp hq, ext, simp [hp, hq, coeff_add, add_apply, std_basis_matrix_add], }, { intros k x, simp only [mat_poly_equiv_coeff_apply_aux_1, coeff_monomial], split_ifs; { funext, simp, }, } end @[simp] lemma mat_poly_equiv_coeff_apply (m : matrix n n (polynomial R)) (k : ℕ) (i j : n) : coeff (mat_poly_equiv m) k i j = coeff (m i j) k := begin apply matrix.induction_on' m, { simp, }, { intros p q hp hq, simp [hp, hq], }, { intros i' j' x, erw mat_poly_equiv_coeff_apply_aux_2, dsimp [std_basis_matrix], split_ifs, { rcases h with ⟨rfl, rfl⟩, simp [std_basis_matrix], }, { simp [std_basis_matrix, h], }, }, end @[simp] lemma mat_poly_equiv_symm_apply_coeff (p : polynomial (matrix n n R)) (i j : n) (k : ℕ) : coeff (mat_poly_equiv.symm p i j) k = coeff p k i j := begin have t : p = mat_poly_equiv (mat_poly_equiv.symm p) := by simp, conv_rhs { rw t, }, simp only [mat_poly_equiv_coeff_apply], end lemma mat_poly_equiv_smul_one (p : polynomial R) : mat_poly_equiv (p • 1) = p.map (algebra_map R (matrix n n R)) := begin ext m i j, simp only [coeff_map, one_apply, algebra_map_matrix_apply, mul_boole, pi.smul_apply, mat_poly_equiv_coeff_apply], split_ifs; simp, end lemma support_subset_support_mat_poly_equiv (m : matrix n n (polynomial R)) (i j : n) : support (m i j) ⊆ support (mat_poly_equiv m) := begin assume k, contrapose, simp only [not_mem_support_iff], assume hk, rw [← mat_poly_equiv_coeff_apply, hk], refl end
e1f1e4ef63235d13771f2c37ad173f24a79b10fd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/basic.lean
fd001b1f818f2d1fb805bedb8839ded5df6311d1
[]
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
61,261
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.filter.lift import Mathlib.topology.separation import Mathlib.PostPort universes u_1 u u_2 l u_3 u_4 u_6 namespace Mathlib /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ /-! ### Relations, seen as `set (α × α)` -/ /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type u_1} : set (α × α) := set_of fun (p : α × α) => prod.fst p = prod.snd p @[simp] theorem mem_id_rel {α : Type u_1} {a : α} {b : α} : (a, b) ∈ id_rel ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {α : Type u_1} {s : set (α × α)} : id_rel ⊆ s ↔ ∀ (a : α), (a, a) ∈ s := sorry /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ : set (α × α)) (r₂ : set (α × α)) : set (α × α) := set_of fun (p : α × α) => ∃ (z : α), (prod.fst p, z) ∈ r₁ ∧ (z, prod.snd p) ∈ r₂ @[simp] theorem mem_comp_rel {α : Type u_1} {r₁ : set (α × α)} {r₂ : set (α × α)} {x : α} {y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ (z : α), (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel {α : Type u_1} : prod.swap '' id_rel = id_rel := sorry theorem monotone_comp_rel {α : Type u_1} {β : Type u_2} [preorder β] {f : β → set (α × α)} {g : β → set (α × α)} (hf : monotone f) (hg : monotone g) : monotone fun (x : β) => comp_rel (f x) (g x) := sorry theorem comp_rel_mono {α : Type u_1} {f : set (α × α)} {g : set (α × α)} {h : set (α × α)} {k : set (α × α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : comp_rel f g ⊆ comp_rel h k := sorry theorem prod_mk_mem_comp_rel {α : Type u_1} {a : α} {b : α} {c : α} {s : set (α × α)} {t : set (α × α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := Exists.intro c { left := h₁, right := h₂ } @[simp] theorem id_comp_rel {α : Type u_1} {r : set (α × α)} : comp_rel id_rel r = r := sorry theorem comp_rel_assoc {α : Type u_1} {r : set (α × α)} {s : set (α × α)} {t : set (α × α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := sorry theorem subset_comp_self {α : Type u_1} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ comp_rel s s := sorry /-- The relation is invariant under swapping factors. -/ def symmetric_rel {α : Type u_1} (V : set (α × α)) := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel {α : Type u_1} (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V theorem symmetric_symmetrize_rel {α : Type u_1} (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := sorry theorem symmetrize_rel_subset_self {α : Type u_1} (V : set (α × α)) : symmetrize_rel V ⊆ V := set.sep_subset V fun (a : α × α) => a ∈ prod.swap ⁻¹' V theorem symmetrize_mono {α : Type u_1} {V : set (α × α)} {W : set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := set.inter_subset_inter h (set.preimage_mono h) theorem symmetric_rel_inter {α : Type u_1} {U : set (α × α)} {V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := sorry /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) where uniformity : filter (α × α) refl : filter.principal id_rel ≤ uniformity symm : filter.tendsto prod.swap uniformity uniformity comp : (filter.lift' uniformity fun (s : set (α × α)) => comp_rel s s) ≤ uniformity /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r : set (α × α)), r ∈ U → ∀ (x : α), (x, x) ∈ r) (symm : ∀ (r : set (α × α)), r ∈ U → prod.swap ⁻¹' r ∈ U) (comp : ∀ (r : set (α × α)) (H : r ∈ U), ∃ (t : set (α × α)), ∃ (H : t ∈ U), comp_rel t t ⊆ r) : uniform_space.core α := uniform_space.core.mk U sorry symm sorry /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := topological_space.mk (fun (s : set α) => ∀ (x : α), x ∈ s → (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniform_space.core.uniformity u) sorry sorry sorry theorem uniform_space.core_eq {α : Type u_1} {u₁ : uniform_space.core α} {u₂ : uniform_space.core α} : uniform_space.core.uniformity u₁ = uniform_space.core.uniformity u₂ → u₁ = u₂ := sorry /-- Suppose that one can put two mathematical structures on a type, a rich one `R` and a poor one `P`, and that one can deduce the poor structure from the rich structure through a map `F` (called a forgetful functor) (think `R = metric_space` and `P = topological_space`). A possible implementation would be to have a type class `rich` containing a field `R`, a type class `poor` containing a field `P`, and an instance from `rich` to `poor`. However, this creates diamond problems, and a better approach is to let `rich` extend `poor` and have a field saying that `F R = P`. To illustrate this, consider the pair `metric_space` / `topological_space`. Consider the topology on a product of two metric spaces. With the first approach, it could be obtained by going first from each metric space to its topology, and then taking the product topology. But it could also be obtained by considering the product metric space (with its sup distance) and then the topology coming from this distance. These would be the same topology, but not definitionally, which means that from the point of view of Lean's kernel, there would be two different `topological_space` instances on the product. This is not compatible with the way instances are designed and used: there should be at most one instance of a kind on each type. This approach has created an instance diamond that does not commute definitionally. The second approach solves this issue. Now, a metric space contains both a distance, a topology, and a proof that the topology coincides with the one coming from the distance. When one defines the product of two metric spaces, one uses the sup distance and the product topology, and one has to give the proof that the sup distance induces the product topology. Following both sides of the instance diamond then gives rise (definitionally) to the product topology on the product space. Another approach would be to have the rich type class take the poor type class as an instance parameter. It would solve the diamond problem, but it would lead to a blow up of the number of type classes one would need to declare to work with complicated classes, say a real inner product space, and would create exponential complexity when working with products of such complicated spaces, that are avoided by bundling things carefully as above. Note that this description of this specific case of the product of metric spaces is oversimplified compared to mathlib, as there is an intermediate typeclass between `metric_space` and `topological_space` called `uniform_space`. The above scheme is used at both levels, embedding a topology in the uniform space structure, and a uniform structure in the metric space structure. Note also that, when `P` is a proposition, there is no such issue as any two proofs of `P` are definitionally equivalent in Lean. To avoid boilerplate, there are some designs that can automatically fill the poor fields when creating a rich structure if one doesn't want to do something special about them. For instance, in the definition of metric spaces, default tactics fill the uniform space fields if they are not given explicitly. One can also have a helper function creating the rich structure from a structure with less fields, where the helper function fills the remaining fields. See for instance `uniform_space.of_core` or `real_inner_product.of_core`. For more details on this question, called the forgetful inheritance pattern, see [Competing inheritance paths in dependent type theory: a case study in functional analysis](https://hal.inria.fr/hal-02463336). -/ /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends uniform_space.core α, topological_space α where is_open_uniformity : ∀ (s : set α), topological_space.is_open _to_topological_space s ↔ ∀ (x : α), x ∈ s → (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniform_space.core.uniformity _to_core /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ def uniform_space.mk' {α : Type u_1} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀ (s : set α), topological_space.is_open t s ↔ ∀ (x : α), x ∈ s → (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniform_space.core.uniformity c) : uniform_space α := uniform_space.mk c is_open_uniformity /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := uniform_space.mk u sorry /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = uniform_space.core.to_topological_space u) : uniform_space α := uniform_space.mk u sorry theorem uniform_space.to_core_to_topological_space {α : Type u_1} (u : uniform_space α) : uniform_space.core.to_topological_space uniform_space.to_core = uniform_space.to_topological_space := sorry theorem uniform_space_eq {α : Type u_1} {u₁ : uniform_space α} {u₂ : uniform_space α} : uniform_space.core.uniformity uniform_space.to_core = uniform_space.core.uniformity uniform_space.to_core → u₁ = u₂ := sorry theorem uniform_space.of_core_eq_to_core {α : Type u_1} (u : uniform_space α) (t : topological_space α) (h : t = uniform_space.core.to_topological_space uniform_space.to_core) : uniform_space.of_core_eq uniform_space.to_core t h = u := uniform_space_eq rfl /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := uniform_space.core.uniformity uniform_space.to_core theorem is_open_uniformity {α : Type u_1} [uniform_space α] {s : set α} : is_open s ↔ ∀ (x : α), x ∈ s → (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniformity α := uniform_space.is_open_uniformity s theorem refl_le_uniformity {α : Type u_1} [uniform_space α] : filter.principal id_rel ≤ uniformity α := uniform_space.core.refl uniform_space.to_core theorem refl_mem_uniformity {α : Type u_1} [uniform_space α] {x : α} {s : set (α × α)} (h : s ∈ uniformity α) : (x, x) ∈ s := refl_le_uniformity h rfl theorem symm_le_uniformity {α : Type u_1} [uniform_space α] : filter.map prod.swap (uniformity α) ≤ uniformity α := uniform_space.core.symm uniform_space.to_core theorem comp_le_uniformity {α : Type u_1} [uniform_space α] : (filter.lift' (uniformity α) fun (s : set (α × α)) => comp_rel s s) ≤ uniformity α := uniform_space.core.comp uniform_space.to_core theorem tendsto_swap_uniformity {α : Type u_1} [uniform_space α] : filter.tendsto prod.swap (uniformity α) (uniformity α) := symm_le_uniformity theorem comp_mem_uniformity_sets {α : Type u_1} [uniform_space α] {s : set (α × α)} (hs : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), comp_rel t t ⊆ s := (fun (this : s ∈ filter.lift' (uniformity α) fun (t : set (α × α)) => comp_rel t t) => iff.mp (filter.mem_lift'_sets (monotone_comp_rel monotone_id monotone_id)) this) (comp_le_uniformity hs) /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ theorem filter.tendsto.uniformity_trans {α : Type u_1} {β : Type u_2} [uniform_space α] {l : filter β} {f₁ : β → α} {f₂ : β → α} {f₃ : β → α} (h₁₂ : filter.tendsto (fun (x : β) => (f₁ x, f₂ x)) l (uniformity α)) (h₂₃ : filter.tendsto (fun (x : β) => (f₂ x, f₃ x)) l (uniformity α)) : filter.tendsto (fun (x : β) => (f₁ x, f₃ x)) l (uniformity α) := sorry /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ theorem filter.tendsto.uniformity_symm {α : Type u_1} {β : Type u_2} [uniform_space α] {l : filter β} {f : β → α × α} (h : filter.tendsto f l (uniformity α)) : filter.tendsto (fun (x : β) => (prod.snd (f x), prod.fst (f x))) l (uniformity α) := filter.tendsto.comp tendsto_swap_uniformity h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ theorem tendsto_diag_uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] (f : β → α) (l : filter β) : filter.tendsto (fun (x : β) => (f x, f x)) l (uniformity α) := fun (s : set (α × α)) (hs : s ∈ uniformity α) => iff.mpr filter.mem_map (filter.univ_mem_sets' fun (x : β) => refl_mem_uniformity hs) theorem tendsto_const_uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] {a : α} {f : filter β} : filter.tendsto (fun (_x : β) => (a, a)) f (uniformity α) := tendsto_diag_uniformity (fun (_x : β) => a) f theorem symm_of_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)} (hs : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), (∀ (a b : α), (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := sorry theorem comp_symm_of_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)} (hs : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), (∀ {a b : α}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := sorry theorem uniformity_le_symm {α : Type u_1} [uniform_space α] : uniformity α ≤ prod.swap <$> uniformity α := eq.mpr (id (Eq._oldrec (Eq.refl (uniformity α ≤ prod.swap <$> uniformity α)) filter.map_swap_eq_comap_swap)) (iff.mp filter.map_le_iff_le_comap tendsto_swap_uniformity) theorem uniformity_eq_symm {α : Type u_1} [uniform_space α] : uniformity α = prod.swap <$> uniformity α := le_antisymm uniformity_le_symm symm_le_uniformity theorem symmetrize_mem_uniformity {α : Type u_1} [uniform_space α] {V : set (α × α)} (h : V ∈ uniformity α) : symmetrize_rel V ∈ uniformity α := sorry theorem uniformity_lift_le_swap {α : Type u_1} {β : Type u_2} [uniform_space α] {g : set (α × α) → filter β} {f : filter β} (hg : monotone g) (h : (filter.lift (uniformity α) fun (s : set (α × α)) => g (prod.swap ⁻¹' s)) ≤ f) : filter.lift (uniformity α) g ≤ f := sorry theorem uniformity_lift_le_comp {α : Type u_1} {β : Type u_2} [uniform_space α] {f : set (α × α) → filter β} (h : monotone f) : (filter.lift (uniformity α) fun (s : set (α × α)) => f (comp_rel s s)) ≤ filter.lift (uniformity α) f := sorry theorem comp_le_uniformity3 {α : Type u_1} [uniform_space α] : (filter.lift' (uniformity α) fun (s : set (α × α)) => comp_rel s (comp_rel s s)) ≤ uniformity α := sorry theorem comp_symm_mem_uniformity_sets {α : Type u_1} [uniform_space α] {s : set (α × α)} (hs : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), symmetric_rel t ∧ comp_rel t t ⊆ s := sorry theorem subset_comp_self_of_mem_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)} (h : s ∈ uniformity α) : s ⊆ comp_rel s s := subset_comp_self (refl_le_uniformity h) theorem comp_comp_symm_mem_uniformity_sets {α : Type u_1} [uniform_space α] {s : set (α × α)} (hs : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), symmetric_rel t ∧ comp_rel (comp_rel t t) t ⊆ s := sorry /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball {β : Type u_2} (x : β) (V : set (β × β)) : set β := Prod.mk x ⁻¹' V theorem uniform_space.mem_ball_self {α : Type u_1} [uniform_space α] (x : α) {V : set (α × α)} (hV : V ∈ uniformity α) : x ∈ uniform_space.ball x V := refl_mem_uniformity hV /-- The triangle inequality for `uniform_space.ball` -/ theorem mem_ball_comp {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {x : β} {y : β} {z : β} (h : y ∈ uniform_space.ball x V) (h' : z ∈ uniform_space.ball y W) : z ∈ uniform_space.ball x (comp_rel V W) := prod_mk_mem_comp_rel h h' theorem ball_subset_of_comp_subset {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {x : β} {y : β} (h : x ∈ uniform_space.ball y W) (h' : comp_rel W W ⊆ V) : uniform_space.ball x W ⊆ uniform_space.ball y V := fun (z : β) (z_in : z ∈ uniform_space.ball x W) => h' (mem_ball_comp h z_in) theorem ball_mono {β : Type u_2} {V : set (β × β)} {W : set (β × β)} (h : V ⊆ W) (x : β) : uniform_space.ball x V ⊆ uniform_space.ball x W := id fun (a : β) (ᾰ : a ∈ uniform_space.ball x V) => h ᾰ theorem mem_ball_symmetry {β : Type u_2} {V : set (β × β)} (hV : symmetric_rel V) {x : β} {y : β} : x ∈ uniform_space.ball y V ↔ y ∈ uniform_space.ball x V := sorry theorem ball_eq_of_symmetry {β : Type u_2} {V : set (β × β)} (hV : symmetric_rel V) {x : β} : uniform_space.ball x V = set_of fun (y : β) => (y, x) ∈ V := sorry theorem mem_comp_of_mem_ball {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {x : β} {y : β} {z : β} (hV : symmetric_rel V) (hx : x ∈ uniform_space.ball z V) (hy : y ∈ uniform_space.ball z W) : (x, y) ∈ comp_rel V W := Exists.intro z { left := eq.mp (Eq._oldrec (Eq.refl (x ∈ uniform_space.ball z V)) (propext (mem_ball_symmetry hV))) hx, right := hy } theorem uniform_space.is_open_ball {α : Type u_1} [uniform_space α] (x : α) {V : set (α × α)} (hV : is_open V) : is_open (uniform_space.ball x V) := is_open.preimage (continuous.prod_mk continuous_const continuous_id) hV theorem mem_comp_comp {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ comp_rel (comp_rel V M) W ↔ set.nonempty (set.prod (uniform_space.ball (prod.fst p) V) (uniform_space.ball (prod.snd p) W) ∩ M) := sorry /-! ### Neighborhoods in uniform spaces -/ theorem mem_nhds_uniformity_iff_right {α : Type u_1} [uniform_space α] {x : α} {s : set α} : s ∈ nhds x ↔ (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniformity α := sorry theorem mem_nhds_uniformity_iff_left {α : Type u_1} [uniform_space α] {x : α} {s : set α} : s ∈ nhds x ↔ (set_of fun (p : α × α) => prod.snd p = x → prod.fst p ∈ s) ∈ uniformity α := sorry theorem nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ F ↔ s ∈ filter.comap (Prod.mk x) F := sorry theorem nhds_eq_comap_uniformity {α : Type u_1} [uniform_space α] {x : α} : nhds x = filter.comap (Prod.mk x) (uniformity α) := sorry theorem is_open_iff_ball_subset {α : Type u_1} [uniform_space α] {s : set α} : is_open s ↔ ∀ (x : α) (H : x ∈ s), ∃ (V : set (α × α)), ∃ (H : V ∈ uniformity α), uniform_space.ball x V ⊆ s := sorry theorem nhds_basis_uniformity' {α : Type u_1} {β : Type u_2} [uniform_space α] {p : β → Prop} {s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s) {x : α} : filter.has_basis (nhds x) p fun (i : β) => uniform_space.ball x (s i) := sorry theorem nhds_basis_uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] {p : β → Prop} {s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s) {x : α} : filter.has_basis (nhds x) p fun (i : β) => set_of fun (y : α) => (y, x) ∈ s i := sorry theorem uniform_space.mem_nhds_iff {α : Type u_1} [uniform_space α] {x : α} {s : set α} : s ∈ nhds x ↔ ∃ (V : set (α × α)), ∃ (H : V ∈ uniformity α), uniform_space.ball x V ⊆ s := sorry theorem uniform_space.ball_mem_nhds {α : Type u_1} [uniform_space α] (x : α) {V : set (α × α)} (V_in : V ∈ uniformity α) : uniform_space.ball x V ∈ nhds x := eq.mpr (id (Eq._oldrec (Eq.refl (uniform_space.ball x V ∈ nhds x)) (propext uniform_space.mem_nhds_iff))) (Exists.intro V (Exists.intro V_in (set.subset.refl (uniform_space.ball x V)))) theorem uniform_space.mem_nhds_iff_symm {α : Type u_1} [uniform_space α] {x : α} {s : set α} : s ∈ nhds x ↔ ∃ (V : set (α × α)), ∃ (H : V ∈ uniformity α), symmetric_rel V ∧ uniform_space.ball x V ⊆ s := sorry theorem uniform_space.has_basis_nhds {α : Type u_1} [uniform_space α] (x : α) : filter.has_basis (nhds x) (fun (s : set (α × α)) => s ∈ uniformity α ∧ symmetric_rel s) fun (s : set (α × α)) => uniform_space.ball x s := sorry theorem uniform_space.has_basis_nhds_prod {α : Type u_1} [uniform_space α] (x : α) (y : α) : filter.has_basis (nhds (x, y)) (fun (s : set (α × α)) => s ∈ uniformity α ∧ symmetric_rel s) fun (s : set (α × α)) => set.prod (uniform_space.ball x s) (uniform_space.ball y s) := sorry theorem nhds_eq_uniformity {α : Type u_1} [uniform_space α] {x : α} : nhds x = filter.lift' (uniformity α) (uniform_space.ball x) := filter.has_basis.eq_binfi (nhds_basis_uniformity' (filter.basis_sets (uniformity α))) theorem mem_nhds_left {α : Type u_1} [uniform_space α] (x : α) {s : set (α × α)} (h : s ∈ uniformity α) : (set_of fun (y : α) => (x, y) ∈ s) ∈ nhds x := uniform_space.ball_mem_nhds x h theorem mem_nhds_right {α : Type u_1} [uniform_space α] (y : α) {s : set (α × α)} (h : s ∈ uniformity α) : (set_of fun (x : α) => (x, y) ∈ s) ∈ nhds y := mem_nhds_left y (symm_le_uniformity h) theorem tendsto_right_nhds_uniformity {α : Type u_1} [uniform_space α] {a : α} : filter.tendsto (fun (a' : α) => (a', a)) (nhds a) (uniformity α) := fun (s : set (α × α)) => mem_nhds_right a theorem tendsto_left_nhds_uniformity {α : Type u_1} [uniform_space α] {a : α} : filter.tendsto (fun (a' : α) => (a, a')) (nhds a) (uniformity α) := fun (s : set (α × α)) => mem_nhds_left a theorem lift_nhds_left {α : Type u_1} {β : Type u_2} [uniform_space α] {x : α} {g : set α → filter β} (hg : monotone g) : filter.lift (nhds x) g = filter.lift (uniformity α) fun (s : set (α × α)) => g (set_of fun (y : α) => (x, y) ∈ s) := sorry theorem lift_nhds_right {α : Type u_1} {β : Type u_2} [uniform_space α] {x : α} {g : set α → filter β} (hg : monotone g) : filter.lift (nhds x) g = filter.lift (uniformity α) fun (s : set (α × α)) => g (set_of fun (y : α) => (y, x) ∈ s) := sorry theorem nhds_nhds_eq_uniformity_uniformity_prod {α : Type u_1} [uniform_space α] {a : α} {b : α} : filter.prod (nhds a) (nhds b) = filter.lift (uniformity α) fun (s : set (α × α)) => filter.lift' (uniformity α) fun (t : set (α × α)) => set.prod (set_of fun (y : α) => (y, a) ∈ s) (set_of fun (y : α) => (b, y) ∈ t) := sorry theorem nhds_eq_uniformity_prod {α : Type u_1} [uniform_space α] {a : α} {b : α} : nhds (a, b) = filter.lift' (uniformity α) fun (s : set (α × α)) => set.prod (set_of fun (y : α) => (y, a) ∈ s) (set_of fun (y : α) => (b, y) ∈ s) := sorry theorem nhdset_of_mem_uniformity {α : Type u_1} [uniform_space α] {d : set (α × α)} (s : set (α × α)) (hd : d ∈ uniformity α) : ∃ (t : set (α × α)), is_open t ∧ s ⊆ t ∧ t ⊆ set_of fun (p : α × α) => ∃ (x : α), ∃ (y : α), (prod.fst p, x) ∈ d ∧ (x, y) ∈ s ∧ (y, prod.snd p) ∈ d := sorry /-- Entourages are neighborhoods of the diagonal. -/ theorem nhds_le_uniformity {α : Type u_1} [uniform_space α] (x : α) : nhds (x, x) ≤ uniformity α := sorry /-- Entourages are neighborhoods of the diagonal. -/ theorem supr_nhds_le_uniformity {α : Type u_1} [uniform_space α] : (supr fun (x : α) => nhds (x, x)) ≤ uniformity α := supr_le nhds_le_uniformity /-! ### Closure and interior in uniform spaces -/ theorem closure_eq_uniformity {α : Type u_1} [uniform_space α] (s : set (α × α)) : closure s = set.Inter fun (V : set (α × α)) => set.Inter fun (H : V ∈ set_of fun (V : set (α × α)) => V ∈ uniformity α ∧ symmetric_rel V) => comp_rel (comp_rel V s) V := sorry theorem uniformity_has_basis_closed {α : Type u_1} [uniform_space α] : filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α ∧ is_closed V) id := sorry /-- Closed entourages form a basis of the uniformity filter. -/ theorem uniformity_has_basis_closure {α : Type u_1} [uniform_space α] : filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α) closure := sorry theorem closure_eq_inter_uniformity {α : Type u_1} [uniform_space α] {t : set (α × α)} : closure t = set.Inter fun (d : set (α × α)) => set.Inter fun (H : d ∈ uniformity α) => comp_rel d (comp_rel t d) := sorry theorem uniformity_eq_uniformity_closure {α : Type u_1} [uniform_space α] : uniformity α = filter.lift' (uniformity α) closure := sorry theorem uniformity_eq_uniformity_interior {α : Type u_1} [uniform_space α] : uniformity α = filter.lift' (uniformity α) interior := sorry theorem interior_mem_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)} (hs : s ∈ uniformity α) : interior s ∈ uniformity α := eq.mpr (id (Eq._oldrec (Eq.refl (interior s ∈ uniformity α)) uniformity_eq_uniformity_interior)) (filter.mem_lift' hs) theorem mem_uniformity_is_closed {α : Type u_1} [uniform_space α] {s : set (α × α)} (h : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), is_closed t ∧ t ⊆ s := sorry /-- The uniform neighborhoods of all points of a dense set cover the whole space. -/ theorem dense.bUnion_uniformity_ball {α : Type u_1} [uniform_space α] {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ uniformity α) : (set.Union fun (x : α) => set.Union fun (H : x ∈ s) => uniform_space.ball x U) = set.univ := sorry /-! ### Uniformity bases -/ /-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/ theorem uniformity_has_basis_open {α : Type u_1} [uniform_space α] : filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α ∧ is_open V) id := sorry theorem filter.has_basis.mem_uniformity_iff {α : Type u_1} {β : Type u_2} [uniform_space α] {p : β → Prop} {s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s) {t : set (α × α)} : t ∈ uniformity α ↔ ∃ (i : β), ∃ (hi : p i), ∀ (a b : α), (a, b) ∈ s i → (a, b) ∈ t := sorry /-- Symmetric entourages form a basis of `𝓤 α` -/ theorem uniform_space.has_basis_symmetric {α : Type u_1} [uniform_space α] : filter.has_basis (uniformity α) (fun (s : set (α × α)) => s ∈ uniformity α ∧ symmetric_rel s) id := sorry /-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis of `𝓤 α`. -/ theorem uniformity_has_basis_open_symmetric {α : Type u_1} [uniform_space α] : filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α ∧ is_open V ∧ symmetric_rel V) id := sorry theorem uniform_space.has_seq_basis {α : Type u_1} [uniform_space α] (h : filter.is_countably_generated (uniformity α)) : ∃ (V : ℕ → set (α × α)), filter.has_antimono_basis (uniformity α) (fun (_x : ℕ) => True) V ∧ ∀ (n : ℕ), symmetric_rel (V n) := sorry /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] (f : α → β) := filter.tendsto (fun (x : α × α) => (f (prod.fst x), f (prod.snd x))) (uniformity α) (uniformity β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] (f : α → β) (s : set α) := filter.tendsto (fun (x : α × α) => (f (prod.fst x), f (prod.snd x))) (uniformity α ⊓ filter.principal (set.prod s s)) (uniformity β) theorem uniform_continuous_def {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ (r : set (β × β)), r ∈ uniformity β → (set_of fun (x : α × α) => (f (prod.fst x), f (prod.snd x)) ∈ r) ∈ uniformity α := iff.rfl theorem uniform_continuous_iff_eventually {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ (r : set (β × β)), r ∈ uniformity β → filter.eventually (fun (x : α × α) => (f (prod.fst x), f (prod.snd x)) ∈ r) (uniformity α) := iff.rfl theorem uniform_continuous_of_const {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {c : α → β} (h : ∀ (a b : α), c a = c b) : uniform_continuous c := sorry theorem uniform_continuous_id {α : Type u_1} [uniform_space α] : uniform_continuous id := sorry theorem uniform_continuous_const {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {b : β} : uniform_continuous fun (a : α) => b := uniform_continuous_of_const fun (_x _x : α) => rfl theorem uniform_continuous.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := filter.tendsto.comp hg hf theorem filter.has_basis.uniform_continuous_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [uniform_space α] [uniform_space β] {p : γ → Prop} {s : γ → set (α × α)} (ha : filter.has_basis (uniformity α) p s) {q : δ → Prop} {t : δ → set (β × β)} (hb : filter.has_basis (uniformity β) q t) {f : α → β} : uniform_continuous f ↔ ∀ (i : δ), q i → ∃ (j : γ), ∃ (hj : p j), ∀ (x y : α), (x, y) ∈ s j → (f x, f y) ∈ t i := sorry theorem filter.has_basis.uniform_continuous_on_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [uniform_space α] [uniform_space β] {p : γ → Prop} {s : γ → set (α × α)} (ha : filter.has_basis (uniformity α) p s) {q : δ → Prop} {t : δ → set (β × β)} (hb : filter.has_basis (uniformity β) q t) {f : α → β} {S : set α} : uniform_continuous_on f S ↔ ∀ (i : δ), q i → ∃ (j : γ), ∃ (hj : p j), ∀ (x y : α), x ∈ S → y ∈ S → (x, y) ∈ s j → (f x, f y) ∈ t i := sorry protected instance uniform_space.partial_order {α : Type u_1} : partial_order (uniform_space α) := partial_order.mk (fun (t s : uniform_space α) => uniform_space.core.uniformity uniform_space.to_core ≤ uniform_space.core.uniformity uniform_space.to_core) (preorder.lt._default fun (t s : uniform_space α) => uniform_space.core.uniformity uniform_space.to_core ≤ uniform_space.core.uniformity uniform_space.to_core) sorry sorry sorry protected instance uniform_space.has_Inf {α : Type u_1} : has_Inf (uniform_space α) := has_Inf.mk fun (s : set (uniform_space α)) => uniform_space.of_core (uniform_space.core.mk (infi fun (u : uniform_space α) => infi fun (H : u ∈ s) => uniformity α) sorry sorry sorry) protected instance uniform_space.has_top {α : Type u_1} : has_top (uniform_space α) := has_top.mk (uniform_space.of_core (uniform_space.core.mk ⊤ sorry sorry sorry)) protected instance uniform_space.has_bot {α : Type u_1} : has_bot (uniform_space α) := has_bot.mk (uniform_space.mk (uniform_space.core.mk (filter.principal id_rel) sorry sorry sorry) sorry) protected instance uniform_space.complete_lattice {α : Type u_1} : complete_lattice (uniform_space α) := complete_lattice.mk (fun (a b : uniform_space α) => Inf (set_of fun (x : uniform_space α) => a ≤ x ∧ b ≤ x)) partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry (fun (a b : uniform_space α) => Inf (insert a (singleton b))) sorry sorry sorry ⊤ sorry ⊥ sorry (fun (tt : set (uniform_space α)) => Inf (set_of fun (t : uniform_space α) => ∀ (t' : uniform_space α), t' ∈ tt → t' ≤ t)) Inf sorry sorry sorry sorry theorem infi_uniformity {α : Type u_1} {ι : Sort u_2} {u : ι → uniform_space α} : uniform_space.core.uniformity uniform_space.to_core = infi fun (i : ι) => uniform_space.core.uniformity uniform_space.to_core := sorry theorem inf_uniformity {α : Type u_1} {u : uniform_space α} {v : uniform_space α} : uniform_space.core.uniformity uniform_space.to_core = uniform_space.core.uniformity uniform_space.to_core ⊓ uniform_space.core.uniformity uniform_space.to_core := sorry protected instance inhabited_uniform_space {α : Type u_1} : Inhabited (uniform_space α) := { default := ⊥ } protected instance inhabited_uniform_space_core {α : Type u_1} : Inhabited (uniform_space.core α) := { default := uniform_space.to_core } /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap {α : Type u_1} {β : Type u_2} (f : α → β) (u : uniform_space β) : uniform_space α := uniform_space.mk (uniform_space.core.mk (filter.comap (fun (p : α × α) => (f (prod.fst p), f (prod.snd p))) (uniform_space.core.uniformity uniform_space.to_core)) sorry sorry sorry) sorry theorem uniformity_comap {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} (h : _inst_1 = uniform_space.comap f _inst_2) : uniformity α = filter.comap (prod.map f f) (uniformity β) := eq.mpr (id (Eq._oldrec (Eq.refl (uniformity α = filter.comap (prod.map f f) (uniformity β))) h)) (Eq.refl (uniformity α)) theorem uniform_space_comap_id {α : Type u_1} : uniform_space.comap id = id := sorry theorem uniform_space.comap_comap {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := sorry theorem uniform_continuous_iff {α : Type u_1} {β : Type u_2} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uniform_space.comap f uβ := filter.map_le_iff_le_comap theorem uniform_continuous_comap {α : Type u_1} {β : Type u_2} {f : α → β} [u : uniform_space β] : uniform_continuous f := filter.tendsto_comap theorem to_topological_space_comap {α : Type u_1} {β : Type u_2} {f : α → β} {u : uniform_space β} : uniform_space.to_topological_space = topological_space.induced f uniform_space.to_topological_space := rfl theorem uniform_continuous_comap' {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : uniform_continuous g := iff.mpr filter.tendsto_comap_iff h theorem to_topological_space_mono {α : Type u_1} {u₁ : uniform_space α} {u₂ : uniform_space α} (h : u₁ ≤ u₂) : uniform_space.to_topological_space ≤ uniform_space.to_topological_space := sorry theorem uniform_continuous.continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := iff.mpr continuous_iff_le_induced (to_topological_space_mono (iff.mp uniform_continuous_iff hf)) theorem to_topological_space_bot {α : Type u_1} : uniform_space.to_topological_space = ⊥ := rfl theorem to_topological_space_top {α : Type u_1} : uniform_space.to_topological_space = ⊤ := sorry theorem to_topological_space_infi {α : Type u_1} {ι : Sort u_2} {u : ι → uniform_space α} : uniform_space.to_topological_space = infi fun (i : ι) => uniform_space.to_topological_space := sorry theorem to_topological_space_Inf {α : Type u_1} {s : set (uniform_space α)} : uniform_space.to_topological_space = infi fun (i : uniform_space α) => infi fun (H : i ∈ s) => uniform_space.to_topological_space := sorry theorem to_topological_space_inf {α : Type u_1} {u : uniform_space α} {v : uniform_space α} : uniform_space.to_topological_space = uniform_space.to_topological_space ⊓ uniform_space.to_topological_space := sorry protected instance empty.uniform_space : uniform_space empty := ⊥ protected instance unit.uniform_space : uniform_space Unit := ⊥ protected instance bool.uniform_space : uniform_space Bool := ⊥ protected instance nat.uniform_space : uniform_space ℕ := ⊥ protected instance int.uniform_space : uniform_space ℤ := ⊥ protected instance subtype.uniform_space {α : Type u_1} {p : α → Prop} [t : uniform_space α] : uniform_space (Subtype p) := uniform_space.comap subtype.val t theorem uniformity_subtype {α : Type u_1} {p : α → Prop} [t : uniform_space α] : uniformity (Subtype p) = filter.comap (fun (q : Subtype p × Subtype p) => (subtype.val (prod.fst q), subtype.val (prod.snd q))) (uniformity α) := rfl theorem uniform_continuous_subtype_val {α : Type u_1} {p : α → Prop} [uniform_space α] : uniform_continuous subtype.val := uniform_continuous_comap theorem uniform_continuous_subtype_mk {α : Type u_1} {β : Type u_2} {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀ (x : β), p (f x)) : uniform_continuous fun (x : β) => { val := f x, property := h x } := uniform_continuous_comap' hf theorem uniform_continuous_on_iff_restrict {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ uniform_continuous (set.restrict f s) := sorry theorem tendsto_of_uniform_continuous_subtype {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous fun (x : ↥s) => f (subtype.val x)) (ha : s ∈ nhds a) : filter.tendsto f (nhds a) (nhds (f a)) := sorry theorem uniform_continuous_on.continuous_on {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s := eq.mpr (id (Eq._oldrec (Eq.refl (continuous_on f s)) (propext continuous_on_iff_continuous_restrict))) (uniform_continuous.continuous (eq.mp (Eq._oldrec (Eq.refl (uniform_continuous_on f s)) (propext uniform_continuous_on_iff_restrict)) h)) /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ protected instance prod.uniform_space {α : Type u_1} {β : Type u_2} [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq uniform_space.to_core prod.topological_space sorry theorem uniformity_prod {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniformity (α × β) = filter.comap (fun (p : (α × β) × α × β) => (prod.fst (prod.fst p), prod.fst (prod.snd p))) (uniformity α) ⊓ filter.comap (fun (p : (α × β) × α × β) => (prod.snd (prod.fst p), prod.snd (prod.snd p))) (uniformity β) := inf_uniformity theorem uniformity_prod_eq_prod {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniformity (α × β) = filter.map (fun (p : (α × α) × β × β) => ((prod.fst (prod.fst p), prod.fst (prod.snd p)), prod.snd (prod.fst p), prod.snd (prod.snd p))) (filter.prod (uniformity α) (uniformity β)) := sorry theorem mem_map_sets_iff' {α : Type u_1} {β : Type u_2} {f : filter α} {m : α → β} {t : set β} : t ∈ filter.sets (filter.map m f) ↔ ∃ (s : set α), ∃ (H : s ∈ f), m '' s ⊆ t := filter.mem_map_sets_iff theorem mem_uniformity_of_uniform_continuous_invariant {α : Type u_1} [uniform_space α] {s : set (α × α)} {f : α → α → α} (hf : uniform_continuous fun (p : α × α) => f (prod.fst p) (prod.snd p)) (hs : s ∈ uniformity α) : ∃ (u : set (α × α)), ∃ (H : u ∈ uniformity α), ∀ (a b c : α), (a, b) ∈ u → (f a c, f b c) ∈ s := sorry theorem mem_uniform_prod {α : Type u_1} {β : Type u_2} [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ uniformity α) (hb : b ∈ uniformity β) : (set_of fun (p : (α × β) × α × β) => (prod.fst (prod.fst p), prod.fst (prod.snd p)) ∈ a ∧ (prod.snd (prod.fst p), prod.snd (prod.snd p)) ∈ b) ∈ uniformity (α × β) := sorry theorem tendsto_prod_uniformity_fst {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : filter.tendsto (fun (p : (α × β) × α × β) => (prod.fst (prod.fst p), prod.fst (prod.snd p))) (uniformity (α × β)) (uniformity α) := le_trans (filter.map_mono inf_le_left) filter.map_comap_le theorem tendsto_prod_uniformity_snd {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : filter.tendsto (fun (p : (α × β) × α × β) => (prod.snd (prod.fst p), prod.snd (prod.snd p))) (uniformity (α × β)) (uniformity β) := le_trans (filter.map_mono inf_le_right) filter.map_comap_le theorem uniform_continuous_fst {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniform_continuous fun (p : α × β) => prod.fst p := tendsto_prod_uniformity_fst theorem uniform_continuous_snd {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniform_continuous fun (p : α × β) => prod.snd p := tendsto_prod_uniformity_snd theorem uniform_continuous.prod_mk {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous fun (a : α) => (f₁ a, f₂ a) := sorry theorem uniform_continuous.prod_mk_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] {f : α × β → γ} (h : uniform_continuous f) (b : β) : uniform_continuous fun (a : α) => f (a, b) := uniform_continuous.comp h (uniform_continuous.prod_mk uniform_continuous_id uniform_continuous_const) theorem uniform_continuous.prod_mk_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] {f : α × β → γ} (h : uniform_continuous f) (a : α) : uniform_continuous fun (b : β) => f (a, b) := uniform_continuous.comp h (uniform_continuous.prod_mk uniform_continuous_const uniform_continuous_id) theorem uniform_continuous.prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := uniform_continuous.prod_mk (uniform_continuous.comp hf uniform_continuous_fst) (uniform_continuous.comp hg uniform_continuous_snd) theorem to_topological_space_prod {α : Type u_1} {β : Type u_2} [u : uniform_space α] [v : uniform_space β] : uniform_space.to_topological_space = prod.topological_space := rfl /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] (f : α → β → γ) := uniform_continuous (function.uncurry f) theorem uniform_continuous₂_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (function.uncurry f) := iff.rfl theorem uniform_continuous₂.uniform_continuous {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (function.uncurry f) := h theorem uniform_continuous₂_curry {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α] [uniform_space β] [uniform_space γ] (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := sorry theorem uniform_continuous₂.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (function.bicompr g f) := uniform_continuous.comp hg hf theorem uniform_continuous₂.bicompl {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {δ' : Type u_6} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (function.bicompl f ga gb) := uniform_continuous.comp (uniform_continuous₂.uniform_continuous hf) (uniform_continuous.prod_map hga hgb) theorem to_topological_space_subtype {α : Type u_1} [u : uniform_space α] {p : α → Prop} : uniform_space.to_topological_space = subtype.topological_space := rfl /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (filter.map (fun (p : α × α) => (sum.inl (prod.fst p), sum.inl (prod.snd p))) (uniformity α) ⊔ filter.map (fun (p : β × β) => (sum.inr (prod.fst p), sum.inr (prod.snd p))) (uniformity β)) sorry sorry sorry /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ theorem union_mem_uniformity_sum {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {a : set (α × α)} (ha : a ∈ uniformity α) {b : set (β × β)} (hb : b ∈ uniformity β) : (fun (p : α × α) => (sum.inl (prod.fst p), sum.inl (prod.snd p))) '' a ∪ (fun (p : β × β) => (sum.inr (prod.fst p), sum.inr (prod.snd p))) '' b ∈ uniform_space.core.uniformity uniform_space.core.sum := sorry /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ theorem uniformity_sum_of_open_aux {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : (set_of fun (p : (α ⊕ β) × (α ⊕ β)) => prod.fst p = x → prod.snd p ∈ s) ∈ uniform_space.core.uniformity uniform_space.core.sum := sorry theorem open_of_uniformity_sum_aux {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {s : set (α ⊕ β)} (hs : ∀ (x : α ⊕ β), x ∈ s → (set_of fun (p : (α ⊕ β) × (α ⊕ β)) => prod.fst p = x → prod.snd p ∈ s) ∈ uniform_space.core.uniformity uniform_space.core.sum) : is_open s := sorry /- We can now define the uniform structure on the disjoint union -/ protected instance sum.uniform_space {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniform_space (α ⊕ β) := uniform_space.mk uniform_space.core.sum sorry theorem sum.uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] : uniformity (α ⊕ β) = filter.map (fun (p : α × α) => (sum.inl (prod.fst p), sum.inl (prod.snd p))) (uniformity α) ⊔ filter.map (fun (p : β × β) => (sum.inr (prod.fst p), sum.inr (prod.snd p))) (uniformity β) := rfl -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ theorem lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι : Sort u_1} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ (i : ι), is_open (c i)) (hc₂ : s ⊆ set.Union fun (i : ι) => c i) : ∃ (n : set (α × α)), ∃ (H : n ∈ uniformity α), ∀ (x : α), x ∈ s → ∃ (i : ι), (set_of fun (y : α) => (x, y) ∈ n) ⊆ c i := sorry /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ theorem lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ (t : set α), t ∈ c → is_open t) (hc₂ : s ⊆ ⋃₀c) : ∃ (n : set (α × α)), ∃ (H : n ∈ uniformity α), ∀ (x : α) (H : x ∈ s), ∃ (t : set α), ∃ (H : t ∈ c), ∀ (y : α), (x, y) ∈ n → y ∈ t := sorry /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform theorem tendsto_nhds_right {α : Type u_1} {β : Type u_2} [uniform_space α] {f : filter β} {u : β → α} {a : α} : filter.tendsto u f (nhds a) ↔ filter.tendsto (fun (x : β) => (a, u x)) f (uniformity α) := sorry theorem tendsto_nhds_left {α : Type u_1} {β : Type u_2} [uniform_space α] {f : filter β} {u : β → α} {a : α} : filter.tendsto u f (nhds a) ↔ filter.tendsto (fun (x : β) => (u x, a)) f (uniformity α) := sorry theorem continuous_at_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ filter.tendsto (fun (x : β) => (f b, f x)) (nhds b) (uniformity α) := sorry theorem continuous_at_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ filter.tendsto (fun (x : β) => (f x, f b)) (nhds b) (uniformity α) := sorry theorem continuous_at_iff_prod {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ filter.tendsto (fun (x : β × β) => (f (prod.fst x), f (prod.snd x))) (nhds (b, b)) (uniformity α) := sorry theorem continuous_within_at_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ filter.tendsto (fun (x : β) => (f b, f x)) (nhds_within b s) (uniformity α) := sorry theorem continuous_within_at_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ filter.tendsto (fun (x : β) => (f x, f b)) (nhds_within b s) (uniformity α) := sorry theorem continuous_on_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b : β), b ∈ s → filter.tendsto (fun (x : β) => (f b, f x)) (nhds_within b s) (uniformity α) := sorry theorem continuous_on_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b : β), b ∈ s → filter.tendsto (fun (x : β) => (f x, f b)) (nhds_within b s) (uniformity α) := sorry theorem continuous_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} : continuous f ↔ ∀ (b : β), filter.tendsto (fun (x : β) => (f b, f x)) (nhds b) (uniformity α) := iff.trans continuous_iff_continuous_at (forall_congr fun (b : β) => tendsto_nhds_right) theorem continuous_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β] {f : β → α} : continuous f ↔ ∀ (b : β), filter.tendsto (fun (x : β) => (f x, f b)) (nhds b) (uniformity α) := iff.trans continuous_iff_continuous_at (forall_congr fun (b : β) => tendsto_nhds_left) end uniform theorem filter.tendsto.congr_uniformity {α : Type u_1} {β : Type u_2} [uniform_space β] {f : α → β} {g : α → β} {l : filter α} {b : β} (hf : filter.tendsto f l (nhds b)) (hg : filter.tendsto (fun (x : α) => (f x, g x)) l (uniformity β)) : filter.tendsto g l (nhds b) := iff.mpr uniform.tendsto_nhds_right (filter.tendsto.uniformity_trans (iff.mp uniform.tendsto_nhds_right hf) hg) theorem uniform.tendsto_congr {α : Type u_1} {β : Type u_2} [uniform_space β] {f : α → β} {g : α → β} {l : filter α} {b : β} (hfg : filter.tendsto (fun (x : α) => (f x, g x)) l (uniformity β)) : filter.tendsto f l (nhds b) ↔ filter.tendsto g l (nhds b) := { mp := fun (h : filter.tendsto f l (nhds b)) => filter.tendsto.congr_uniformity h hfg, mpr := fun (h : filter.tendsto g l (nhds b)) => filter.tendsto.congr_uniformity h (filter.tendsto.uniformity_symm hfg) }
a569bc55068f38eed59d2371c154a62dc04b5f18
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/library_search/ring_theory.lean
a1af0c494f53822c48fef9d2b9c037030489cfaf
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
755
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 tactic.suggest import ring_theory.principal_ideal_domain import ring_theory.polynomial /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true example {α : Type} [euclidean_domain α] {S : ideal α} {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := by library_search -- exact mod_mem_iff hy variables {R : Type} [comm_ring R] [decidable_eq R] variables {I : ideal (polynomial R)} example {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := by library_search -- exact ideal.leading_coeff_nth_mono I H
95ea0c9f05a9405f1d3bd61b2cb2e5a9d888e51e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/complex/roots_of_unity.lean
2daba90e3502df94902a5af932172dd0d3ca7325
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,574
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import analysis.special_functions.trigonometric.complex import ring_theory.roots_of_unity /-! # Complex roots of unity In this file we show that the `n`-th complex roots of unity are exactly the complex numbers `e ^ (2 * real.pi * complex.I * (i / n))` for `i ∈ finset.range n`. ## Main declarations * `complex.mem_roots_of_unity`: the complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. * `complex.card_roots_of_unity`: the number of `n`-th roots of unity is exactly `n`. -/ namespace complex open polynomial real open_locale nat real lemma is_primitive_root_exp_of_coprime (i n : ℕ) (h0 : n ≠ 0) (hi : i.coprime n) : is_primitive_root (exp (2 * π * I * (i / n))) n := begin rw is_primitive_root.iff_def, simp only [← exp_nat_mul, exp_eq_one_iff], have hn0 : (n : ℂ) ≠ 0, by exact_mod_cast h0, split, { use i, field_simp [hn0, mul_comm (i : ℂ), mul_comm (n : ℂ)] }, { simp only [hn0, mul_right_comm _ _ ↑n, mul_left_inj' two_pi_I_ne_zero, ne.def, not_false_iff, mul_comm _ (i : ℂ), ← mul_assoc _ (i : ℂ), exists_imp_distrib] with field_simps, norm_cast, rintro l k hk, have : n ∣ i * l, { rw [← int.coe_nat_dvd, hk], apply dvd_mul_left }, exact hi.symm.dvd_of_dvd_mul_left this } end lemma is_primitive_root_exp (n : ℕ) (h0 : n ≠ 0) : is_primitive_root (exp (2 * π * I / n)) n := by simpa only [nat.cast_one, one_div] using is_primitive_root_exp_of_coprime 1 n h0 n.coprime_one_left lemma is_primitive_root_iff (ζ : ℂ) (n : ℕ) (hn : n ≠ 0) : is_primitive_root ζ n ↔ (∃ (i < (n : ℕ)) (hi : i.coprime n), exp (2 * π * I * (i / n)) = ζ) := begin have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast hn, split, swap, { rintro ⟨i, -, hi, rfl⟩, exact is_primitive_root_exp_of_coprime i n hn hi }, intro h, obtain ⟨i, hi, rfl⟩ := (is_primitive_root_exp n hn).eq_pow_of_pow_eq_one h.pow_eq_one (nat.pos_of_ne_zero hn), refine ⟨i, hi, ((is_primitive_root_exp n hn).pow_iff_coprime (nat.pos_of_ne_zero hn) i).mp h, _⟩, rw [← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] end /-- The complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. -/ lemma mem_roots_of_unity (n : ℕ+) (x : units ℂ) : x ∈ roots_of_unity n ℂ ↔ (∃ i < (n : ℕ), exp (2 * π * I * (i / n)) = x) := begin rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, units.coe_one], have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast (n.ne_zero), split, { intro h, obtain ⟨i, hi, H⟩ : ∃ i < (n : ℕ), exp (2 * π * I / n) ^ i = x, { simpa only using (is_primitive_root_exp n n.ne_zero).eq_pow_of_pow_eq_one h n.pos }, refine ⟨i, hi, _⟩, rw [← H, ← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] }, { rintro ⟨i, hi, H⟩, rw [← H, ← exp_nat_mul, exp_eq_one_iff], use i, field_simp [hn0, mul_comm ((n : ℕ) : ℂ), mul_comm (i : ℂ)] } end lemma card_roots_of_unity (n : ℕ+) : fintype.card (roots_of_unity n ℂ) = n := (is_primitive_root_exp n n.ne_zero).card_roots_of_unity lemma card_primitive_roots (k : ℕ) (h : k ≠ 0) : (primitive_roots k ℂ).card = φ k := (is_primitive_root_exp k h).card_primitive_roots (nat.pos_of_ne_zero h) end complex
4ff8ab33f8bf24b83f402694e6aa3fc1d2280fd2
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170322-type-classes.lean
6bb0acadecf140e00b7269404f44760cd73c5bf4
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
704
lean
universe variables u v class has_compose (Obj : Type u) (Hom : Obj → Obj → Type v) := ( compose : ∀ { X Y Z : Obj } ( f : Hom X Y ) ( g: Hom Y Z ), Hom X Z ) ( associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z), compose (compose f g) h = compose f (compose g h) ) class has_identity (Obj : Type u) (Hom : Obj → Obj → Type v) extends has_compose Obj Hom := ( identity : Π X : Obj, Hom X X ) ( left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f ) ( right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity Y) = f ) structure Category (Obj : Type u) (Hom : Obj → Obj → Type v) extends has_identity Obj Hom
414848fcf73ef1335f41b73a9b76554afc0ca75f
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/280.lean
5b738c92f9a9fd0080ffeef3c19a5e8209502910
[ "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
303
lean
inductive S where | P | I open S inductive Expr : S → Type where | lit : Int → Expr I | eq : Expr I → Expr I → Expr P def Val : S → Type | P => Prop | I => Int def eval : {s : S} → Expr s → Val s | _, (Expr.lit n) => n | _, (Expr.eq e₁ e₂) => eval e₁ = eval e₂
dd786a5d9687ffad848933c151e8ee1d1eca6dbd
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/monad/adjunction.lean
f99f604e3f96eb8bbbfb774cdd323a86e0acbe38
[ "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
5,778
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.monad.algebra import category_theory.adjunction.fully_faithful namespace category_theory open category universes v₁ v₂ 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] variables (R : D ⥤ C) namespace adjunction instance monad (R : D ⥤ C) [is_right_adjoint R] : monad ((left_adjoint R) ⋙ R) := let L := left_adjoint R in let h : L ⊣ R := is_right_adjoint.adj in { η := h.unit, μ := whisker_right (whisker_left L h.counit) R, assoc' := λ X, by { dsimp, erw [←R.map_comp, h.counit.naturality, R.map_comp], refl }, right_unit' := λ X, by { dsimp, rw [←R.map_comp], simp }, } @[simp] lemma monad_η_app [is_right_adjoint R] (X) : (η_ ((left_adjoint R) ⋙ R)).app X = is_right_adjoint.adj.unit.app X := rfl @[simp] lemma monad_μ_app [is_right_adjoint R] (X) : (μ_ ((left_adjoint R) ⋙ R)).app X = R.map (is_right_adjoint.adj.counit.app ((left_adjoint R).obj X)) := rfl end adjunction namespace monad -- We can't use `@[simps]` here because it can't cope with `let` statements. def comparison [is_right_adjoint R] : D ⥤ algebra ((left_adjoint R) ⋙ R) := let h : _ ⊣ R := is_right_adjoint.adj in { obj := λ X, { A := R.obj X, a := R.map (h.counit.app X), assoc' := by { dsimp, conv { to_rhs, erw [←R.map_comp, h.counit.naturality, R.map_comp], }, refl } }, map := λ X Y f, { f := R.map f, h' := begin dsimp, erw [←R.map_comp, h.counit.naturality, R.map_comp, functor.id_map], refl, end } }. @[simp] lemma comparison_map_f [is_right_adjoint R] {X Y} (f : X ⟶ Y) : ((comparison R).map f).f = R.map f := rfl @[simp] lemma comparison_obj_a [is_right_adjoint R] (X) : ((comparison R).obj X).a = R.map (is_right_adjoint.adj.counit.app X) := rfl def comparison_forget [is_right_adjoint R] : comparison R ⋙ forget ((left_adjoint R) ⋙ R) ≅ R := { hom := { app := λ X, 𝟙 _, }, inv := { app := λ X, 𝟙 _, } } end monad section prio set_option default_priority 100 -- see Note [default priority] /-- A functor is *reflective*, or *a reflective inclusion*, if it is fully faithful and right adjoint. -/ class reflective (R : D ⥤ C) extends is_right_adjoint R, full R, faithful R. /-- A right adjoint functor `R : D ⥤ C` is *monadic* if the comparison function `monad.comparison R` from `D` to the category of Eilenberg-Moore algebras for the adjunction is an equivalence. -/ class monadic_right_adjoint (R : D ⥤ C) extends is_right_adjoint R := (eqv : is_equivalence (monad.comparison R)) end prio instance μ_iso_of_reflective [reflective R] : is_iso (μ_ ((left_adjoint R) ⋙ R)) := by { dsimp [adjunction.monad], apply_instance } attribute [instance] monadic_right_adjoint.eqv -- PROJECT prove Beck's monadicity theorem, e.g. from Section 5.5 of [Riehl][riehl2017] namespace reflective lemma comparison_ess_surj_aux [reflective R] (X : monad.algebra ((left_adjoint R) ⋙ R)) : ((is_right_adjoint.adj).unit).app (R.obj ((left_adjoint R).obj (X.A))) = R.map ((left_adjoint R).map ((is_right_adjoint.adj).unit.app X.A)) := begin -- both are left inverses to μ_X. apply (cancel_mono ((μ_ ((left_adjoint R) ⋙ R)).app _)).1, { dsimp, erw [adjunction.right_triangle_components, ←R.map_comp], simp, }, { apply is_iso.mono_of_iso _, apply nat_iso.is_iso_app_of_is_iso } end instance [reflective R] (X : monad.algebra ((left_adjoint R) ⋙ R)) : is_iso ((is_right_adjoint.adj : _ ⊣ R).unit.app X.A) := let L := left_adjoint R in let h : L ⊣ R := (is_right_adjoint.adj) in { inv := X.a, hom_inv_id' := X.unit, inv_hom_id' := begin dsimp, erw [h.unit.naturality, comparison_ess_surj_aux, ←R.map_comp, ←L.map_comp, X.unit, L.map_id, R.map_id], refl end } instance comparison_ess_surj [reflective R]: ess_surj (monad.comparison R) := let L := left_adjoint R in let h : L ⊣ R := is_right_adjoint.adj in { obj_preimage := λ X, L.obj X.A, iso' := λ X, { hom := { f := (as_iso (h.unit.app X.A)).inv, h' := begin dsimp, apply (cancel_epi (R.map (L.map ((h.unit).app (X.A))))).1, rw [is_iso.hom_inv_id_assoc, ←category.assoc, ←R.map_comp,adjunction.left_triangle_components], erw [functor.map_id, category.id_comp], apply (cancel_epi ((h.unit).app (X.A))).1, rw is_iso.hom_inv_id, exact X.unit, end }, inv := { f := (as_iso (h.unit.app X.A)).hom, h' := begin dsimp, erw [←R.map_comp, adjunction.left_triangle_components, R.map_id], apply (cancel_epi ((h.unit).app (X.A))).1, conv { to_rhs, erw [←category.assoc, X.unit] }, erw [comp_id, id_comp], end }, hom_inv_id' := by { ext, exact (as_iso (h.unit.app X.A)).inv_hom_id, }, inv_hom_id' := by { ext, exact (as_iso (h.unit.app X.A)).hom_inv_id, }, } } instance comparison_full [full R] [is_right_adjoint R] : full (monad.comparison R) := { preimage := λ X Y f, R.preimage f.f } instance comparison_faithful [faithful R] [is_right_adjoint R] : faithful (monad.comparison R) := { map_injective' := λ X Y f g w, by { have w' := (congr_arg monad.algebra.hom.f w), exact R.map_injective w' } } end reflective /-- Any reflective inclusion has a monadic right adjoint. cf Prop 5.3.3 of [Riehl][riehl2017] -/ @[priority 100] -- see Note [lower instance priority] instance monadic_of_reflective [reflective R] : monadic_right_adjoint R := { eqv := equivalence.equivalence_of_fully_faithfully_ess_surj _ } end category_theory
275039f6a83ee49203a8d6b2485e47b7b7e8901f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/part.lean
c85a0e1a1de8896ac9eeca1351d78556c97a5f11
[ "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
24,380
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import data.set.basic import logic.equiv.defs /-! # Partial values of a type This file defines `part α`, the partial values of a type. `o : part α` carries a proposition `o.dom`, its domain, along with a function `get : o.dom → α`, its value. The rule is then that every partial value has a value but, to access it, you need to provide a proof of the domain. `part α` behaves the same as `option α` except that `o : option α` is decidably `none` or `some a` for some `a : α`, while the domain of `o : part α` doesn't have to be decidable. That means you can translate back and forth between a partial value with a decidable domain and an option, and `option α` and `part α` are classically equivalent. In general, `part α` is bigger than `option α`. In current mathlib, `part ℕ`, aka `part_enat`, is used to move decidability of the order to decidability of `part_enat.find` (which is the smallest natural satisfying a predicate, or `∞` if there's none). ## Main declarations `option`-like declarations: * `part.none`: The partial value whose domain is `false`. * `part.some a`: The partial value whose domain is `true` and whose value is `a`. * `part.of_option`: Converts an `option α` to a `part α` by sending `none` to `none` and `some a` to `some a`. * `part.to_option`: Converts a `part α` with a decidable domain to an `option α`. * `part.equiv_option`: Classical equivalence between `part α` and `option α`. Monadic structure: * `part.bind`: `o.bind f` has value `(f (o.get _)).get _` (`f o` morally) and is defined when `o` and `f (o.get _)` are defined. * `part.map`: Maps the value and keeps the same domain. Other: * `part.restrict`: `part.restrict p o` replaces the domain of `o : part α` by `p : Prop` so long as `p → o.dom`. * `part.assert`: `assert p f` appends `p` to the domains of the values of a partial function. * `part.unwrap`: Gets the value of a partial value regardless of its domain. Unsound. ## Notation For `a : α`, `o : part α`, `a ∈ o` means that `o` is defined and equal to `a`. Formally, it means `o.dom` and `o.get _ = a`. -/ open function /-- `part α` is the type of "partial values" of type `α`. It is similar to `option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure {u} part (α : Type u) : Type u := (dom : Prop) (get : dom → α) namespace part variables {α : Type*} {β : Type*} {γ : Type*} /-- Convert a `part α` with a decidable domain to an option -/ def to_option (o : part α) [decidable o.dom] : option α := if h : dom o then some (o.get h) else none /-- `part` extensionality -/ theorem ext' : ∀ {o p : part α} (H1 : o.dom ↔ p.dom) (H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p | ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1, by cases t; rw [show o = p, from funext $ λp, H2 p p] /-- `part` eta expansion -/ @[simp] theorem eta : Π (o : part α), (⟨o.dom, λ h, o.get h⟩ : part α) = o | ⟨h, f⟩ := rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def mem (a : α) (o : part α) : Prop := ∃ h, o.get h = a instance : has_mem α (part α) := ⟨part.mem⟩ theorem mem_eq (a : α) (o : part α) : (a ∈ o) = (∃ h, o.get h = a) := rfl theorem dom_iff_mem : ∀ {o : part α}, o.dom ↔ ∃ y, y ∈ o | ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩ theorem get_mem {o : part α} (h) : get o h ∈ o := ⟨_, rfl⟩ @[simp] lemma mem_mk_iff {p : Prop} {o : p → α} {a : α} : a ∈ part.mk p o ↔ ∃ h, o h = a := iff.rfl /-- `part` extensionality -/ @[ext] theorem ext {o p : part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst, λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $ λ a b, ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `part` has a `false` domain and an empty function. -/ def none : part α := ⟨false, false.rec _⟩ instance : inhabited (part α) := ⟨none⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst /-- The `some a` value in `part` has a `true` domain and the function returns `a`. -/ def some (a : α) : part α := ⟨true, λ_, a⟩ @[simp] lemma some_dom (a : α) : (some a).dom := trivial theorem mem_unique : ∀ {a b : α} {o : part α}, a ∈ o → b ∈ o → a = b | _ _ ⟨p, f⟩ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl theorem mem.left_unique : relator.left_unique ((∈) : α → part α → Prop) := λ a o b, mem_unique theorem get_eq_of_mem {o : part α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h protected theorem subsingleton (o : part α) : set.subsingleton {a | a ∈ o} := λ a ha b hb, mem_unique ha hb @[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : part α) ↔ b = a := ⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : part α} : o = some a ↔ a ∈ o := ⟨λ e, e.symm ▸ mem_some _, λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩ theorem eq_none_iff {o : part α} : o = none ↔ ∀ a, a ∉ o := ⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa)⟩ theorem eq_none_iff' {o : part α} : o = none ↔ ¬ o.dom := ⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩ @[simp] lemma not_none_dom : ¬ (none : part α).dom := id @[simp] lemma some_ne_none (x : α) : some x ≠ none := by { intro h, change none.dom, rw [← h], trivial } @[simp] lemma none_ne_some (x : α) : none ≠ some x := (some_ne_none x).symm lemma ne_none_iff {o : part α} : o ≠ none ↔ ∃ x, o = some x := begin split, { rw [ne, eq_none_iff', not_not], exact λ h, ⟨o.get h, eq_some_iff.2 (get_mem h)⟩ }, { rintro ⟨x, rfl⟩, apply some_ne_none } end lemma eq_none_or_eq_some (o : part α) : o = none ∨ ∃ x, o = some x := or_iff_not_imp_left.2 ne_none_iff.1 lemma some_injective : injective (@part.some α) := λ a b h, congr_fun (eq_of_heq (part.mk.inj h).2) trivial @[simp] lemma some_inj {a b : α} : part.some a = some b ↔ a = b := some_injective.eq_iff @[simp] lemma some_get {a : part α} (ha : a.dom) : part.some (part.get a ha) = a := eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) lemma get_eq_iff_eq_some {a : part α} {ha : a.dom} {b : α} : a.get ha = b ↔ a = some b := ⟨λ h, by simp [h.symm], λ h, by simp [h]⟩ lemma get_eq_get_of_eq (a : part α) (ha : a.dom) {b : part α} (h : a = b) : a.get ha = b.get (h ▸ ha) := by { congr, exact h } lemma get_eq_iff_mem {o : part α} {a : α} (h : o.dom) : o.get h = a ↔ a ∈ o := ⟨λ H, ⟨h, H⟩, λ ⟨h', H⟩, H⟩ lemma eq_get_iff_mem {o : part α} {a : α} (h : o.dom) : a = o.get h ↔ a ∈ o := eq_comm.trans (get_eq_iff_mem h) @[simp] lemma none_to_option [decidable (@none α).dom] : (none : part α).to_option = option.none := dif_neg id @[simp] lemma some_to_option (a : α) [decidable (some a).dom] : (some a).to_option = option.some a := dif_pos trivial instance none_decidable : decidable (@none α).dom := decidable.false instance some_decidable (a : α) : decidable (some a).dom := decidable.true /-- Retrieves the value of `a : part α` if it exists, and return the provided default value otherwise. -/ def get_or_else (a : part α) [decidable a.dom] (d : α) := if ha : a.dom then a.get ha else d lemma get_or_else_of_dom (a : part α) (h : a.dom) [decidable a.dom] (d : α) : get_or_else a d = a.get h := dif_pos h lemma get_or_else_of_not_dom (a : part α) (h : ¬ a.dom) [decidable a.dom] (d : α) : get_or_else a d = d := dif_neg h @[simp] lemma get_or_else_none (d : α) [decidable (none : part α).dom] : get_or_else none d = d := none.get_or_else_of_not_dom not_none_dom d @[simp] lemma get_or_else_some (a : α) (d : α) [decidable (some a).dom] : get_or_else (some a) d = a := (some a).get_or_else_of_dom (some_dom a) d @[simp] theorem mem_to_option {o : part α} [decidable o.dom] {a : α} : a ∈ to_option o ↔ a ∈ o := begin unfold to_option, by_cases h : o.dom; simp [h], { exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ }, { exact mt Exists.fst h } end protected lemma dom.to_option {o : part α} [decidable o.dom] (h : o.dom) : o.to_option = o.get h := dif_pos h lemma to_option_eq_none_iff {a : part α} [decidable a.dom] : a.to_option = option.none ↔ ¬ a.dom := ne.dite_eq_right_iff $ λ h, option.some_ne_none _ @[simp] lemma elim_to_option {α β : Type*} (a : part α) [decidable a.dom] (b : β) (f : α → β) : a.to_option.elim b f = if h : a.dom then f (a.get h) else b := begin split_ifs, { rw h.to_option, refl }, { rw part.to_option_eq_none_iff.2 h, refl } end /-- Converts an `option α` into a `part α`. -/ def of_option : option α → part α | option.none := none | (option.some a) := some a @[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o | option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩ | (option.some b) := ⟨λ h, congr_arg option.some h.snd, λ h, ⟨trivial, option.some.inj h⟩⟩ @[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some | option.none := by simp [of_option, none] | (option.some a) := by simp [of_option] theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ := part.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl] instance : has_coe (option α) (part α) := ⟨of_option⟩ @[simp] theorem mem_coe {a : α} {o : option α} : a ∈ (o : part α) ↔ a ∈ o := mem_of_option @[simp] theorem coe_none : (@option.none α : part α) = none := rfl @[simp] theorem coe_some (a : α) : (option.some a : part α) = some a := rfl @[elab_as_eliminator] protected lemma induction_on {P : part α → Prop} (a : part α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (classical.em a.dom).elim (λ h, part.some_get h ▸ hsome _) (λ h, (eq_none_iff'.2 h).symm ▸ hnone) instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom | option.none := part.none_decidable | (option.some a) := part.some_decidable a @[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o := by cases o; refl @[simp] theorem of_to_option (o : part α) [decidable o.dom] : of_option (to_option o) = o := ext $ λ a, mem_of_option.trans mem_to_option /-- `part α` is (classically) equivalent to `option α`. -/ noncomputable def equiv_option : part α ≃ option α := by haveI := classical.dec; exact ⟨λ o, to_option o, of_option, λ o, of_to_option o, λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩ /-- We give `part α` the order where everything is greater than `none`. -/ instance : partial_order (part α) := { le := λ x y, ∀ i, i ∈ x → i ∈ y, le_refl := λ x y, id, le_trans := λ x y z f g i, g _ ∘ f _, le_antisymm := λ x y f g, part.ext $ λ z, ⟨f _, g _⟩ } instance : order_bot (part α) := { bot := none, bot_le := by { introv x, rintro ⟨⟨_⟩,_⟩, } } lemma le_total_of_le_of_le {x y : part α} (z : part α) (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x := begin rcases part.eq_none_or_eq_some x with h | ⟨b, h₀⟩, { rw h, left, apply order_bot.bot_le _ }, right, intros b' h₁, rw part.eq_some_iff at h₀, replace hx := hx _ h₀, replace hy := hy _ h₁, replace hx := part.mem_unique hx hy, subst hx, exact h₀ end /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → part α) : part α := ⟨∃ h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : part α) (g : α → part β) : part β := assert (dom f) (λb, g (f.get b)) /-- The map operation for `part` just maps the value and maintains the same domain. -/ @[simps] def map (f : α → β) (o : part α) : part β := ⟨o.dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : part α} : ∀ {a}, a ∈ o → f a ∈ map f o | _ ⟨h, rfl⟩ := ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : part α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end, λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 $ mem_map f $ mem_some _ theorem mem_assert {p : Prop} {f : p → part α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _ x ⟨h, rfl⟩ := ⟨⟨x, h⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → part α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end, λ ⟨a, h⟩, mem_assert _ h⟩ lemma assert_pos {p : Prop} {f : p → part α} (h : p) : assert p f = f h := begin dsimp [assert], cases h' : f h, simp only [h', h, true_and, iff_self, exists_prop_of_true, eq_iff_iff], apply function.hfunext, { simp only [h, h', exists_prop_of_true] }, { cc } end lemma assert_neg {p : Prop} {f : p → part α} (h : ¬ p) : assert p f = none := begin dsimp [assert,none], congr, { simp only [h, not_false_iff, exists_prop_of_false] }, { apply function.hfunext, { simp only [h, not_false_iff, exists_prop_of_false] }, cc }, end theorem mem_bind {f : part α} {g : α → part β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨h, h₂⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : part α} {g : α → part β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end, λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩ protected lemma dom.bind {o : part α} (h : o.dom) (f : α → part β) : o.bind f = f (o.get h) := begin ext b, simp only [part.mem_bind_iff, exists_prop], refine ⟨_, λ hb, ⟨o.get h, part.get_mem _, hb⟩⟩, rintro ⟨a, ha, hb⟩, rwa part.get_eq_of_mem ha, end lemma dom.of_bind {f : α → part β} {a : part α} (h : (a.bind f).dom) : a.dom := h.some @[simp] theorem bind_none (f : α → part β) : none.bind f = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem bind_some (a : α) (f : α → part β) : (some a).bind f = f a := ext $ by simp theorem bind_of_mem {o : part α} {a : α} (h : a ∈ o) (f : α → part β) : o.bind f = f a := by rw [eq_some_iff.2 h, bind_some] theorem bind_some_eq_map (f : α → β) (x : part α) : x.bind (some ∘ f) = map f x := ext $ by simp [eq_comm] lemma bind_to_option (f : α → part β) (o : part α) [decidable o.dom] [Π a, decidable (f a).dom] [decidable (o.bind f).dom] : (o.bind f).to_option = o.to_option.elim option.none (λ a, (f a).to_option) := begin by_cases o.dom, { simp_rw [h.to_option, h.bind], refl }, { rw part.to_option_eq_none_iff.2 h, exact part.to_option_eq_none_iff.2 (λ ho, h ho.of_bind) } end theorem bind_assoc {γ} (f : part α) (g : α → part β) (k : β → part γ) : (f.bind g).bind k = f.bind (λ x, (g x).bind k) := ext $ λ a, by simp; exact ⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩, λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → part γ) : (map f x).bind g = x.bind (λ y, g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → part β) (x : part α) (g : β → γ) : map g (x.bind f) = x.bind (λ y, map g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : part α) : map g (map f o) = map (g ∘ f) o := by rw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : monad part := { pure := @some, map := @map, bind := @part.bind } instance : is_lawful_monad part := { bind_pure_comp_eq_map := @bind_some_eq_map, id_map := λ β f, by cases f; refl, pure_bind := @bind_some, bind_assoc := @bind_assoc } theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o := by rw [show f = id, from funext H]; exact id_map o @[simp] theorem bind_some_right (x : part α) : x.bind some = x := by rw [bind_some_eq_map]; simp [map_id'] @[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl @[simp] theorem ret_eq_some (a : α) : return a = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : part α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : part α) (g : α → part β) : f >>= g = f.bind g := rfl lemma bind_le {α} (x : part α) (f : α → part β) (y : part β) : x >>= f ≤ y ↔ (∀ a, a ∈ x → f a ≤ y) := begin split; intro h, { intros a h' b, replace h := h b, simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp_distrib] at h, apply h _ h' }, { intros b h', simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h', rcases h' with ⟨a,h₀,h₁⟩, apply h _ h₀ _ h₁ }, end instance : monad_fail part := { fail := λ_ _, none, ..part.monad } /-- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) (o : part α) (H : p → o.dom) : part α := ⟨p, λh, o.get (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : part α) (h : p → o.dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := begin dsimp [restrict, mem_eq], split, { rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ }, rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩ end /-- `unwrap o` gets the value at `o`, ignoring the condition. This function is unsound. -/ meta def unwrap (o : part α) : α := o.get undefined theorem assert_defined {p : Prop} {f : p → part α} : ∀ (h : p), (f h).dom → (assert p f).dom := exists.intro theorem bind_defined {f : part α} {g : α → part β} : ∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined @[simp] theorem bind_dom {f : part α} {g : α → part β} : (f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl section instances /- We define several instances for constants and operations on `part α` inherited from `α`. -/ @[to_additive] instance [has_one α] : has_one (part α) := { one := pure 1 } @[to_additive] instance [has_mul α] : has_mul (part α) := { mul := λ a b, (*) <$> a <*> b } @[to_additive] instance [has_inv α] : has_inv (part α) := { inv := map has_inv.inv } @[to_additive] instance [has_div α] : has_div (part α) := { div := λ a b, (/) <$> a <*> b } instance [has_mod α] : has_mod (part α) := { mod := λ a b, (%) <$> a <*> b } instance [has_append α] : has_append (part α) := { append := λ a b, (++) <$> a <*> b } instance [has_inter α] : has_inter (part α) := { inter := λ a b, (∩) <$> a <*> b } instance [has_union α] : has_union (part α) := { union := λ a b, (∪) <$> a <*> b } instance [has_sdiff α] : has_sdiff (part α) := { sdiff := λ a b, (\) <$> a <*> b } @[to_additive] lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : part α) := ⟨trivial, rfl⟩ @[to_additive] lemma mul_mem_mul [has_mul α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma * mb ∈ a * b := by tidy @[to_additive] lemma left_dom_of_mul_dom [has_mul α] {a b : part α} (hab : dom (a * b)) : a.dom := by tidy @[to_additive] lemma right_dom_of_mul_dom [has_mul α] {a b : part α} (hab : dom (a * b)) : b.dom := by tidy @[simp, to_additive] lemma mul_get_eq [has_mul α] (a b : part α) (hab : dom (a * b)) : (a * b).get hab = a.get (left_dom_of_mul_dom hab) * b.get (right_dom_of_mul_dom hab) := by tidy @[to_additive] lemma some_mul_some [has_mul α] (a b : α) : some a * some b = some (a * b) := by tidy @[to_additive] lemma inv_mem_inv [has_inv α] (a : part α) (ma : α) (ha : ma ∈ a) : ma⁻¹ ∈ a⁻¹ := by tidy @[to_additive] lemma inv_some [has_inv α] (a : α) : (some a)⁻¹ = some (a⁻¹) := rfl @[to_additive] lemma div_mem_div [has_div α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma / mb ∈ a / b := by tidy @[to_additive] lemma left_dom_of_div_dom [has_div α] {a b : part α} (hab : dom (a / b)) : a.dom := by tidy @[to_additive] lemma right_dom_of_div_dom [has_div α] {a b : part α} (hab : dom (a / b)) : b.dom := by tidy @[simp, to_additive] lemma div_get_eq [has_div α] (a b : part α) (hab : dom (a / b)) : (a / b).get hab = a.get (left_dom_of_div_dom hab) / b.get (right_dom_of_div_dom hab) := by tidy @[to_additive] lemma some_div_some [has_div α] (a b : α) : some a / some b = some (a / b) := by tidy lemma mod_mem_mod [has_mod α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma % mb ∈ a % b := by tidy lemma left_dom_of_mod_dom [has_mod α] {a b : part α} (hab : dom (a % b)) : a.dom := by tidy lemma right_dom_of_mod_dom [has_mod α] {a b : part α} (hab : dom (a % b)) : b.dom := by tidy @[simp] lemma mod_get_eq [has_mod α] (a b : part α) (hab : dom (a % b)) : (a % b).get hab = a.get (left_dom_of_mod_dom hab) % b.get (right_dom_of_mod_dom hab) := by tidy lemma some_mod_some [has_mod α] (a b : α) : some a % some b = some (a % b) := by tidy lemma append_mem_append [has_append α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma ++ mb ∈ a ++ b := by tidy lemma left_dom_of_append_dom [has_append α] {a b : part α} (hab : dom (a ++ b)) : a.dom := by tidy lemma right_dom_of_append_dom [has_append α] {a b : part α} (hab : dom (a ++ b)) : b.dom := by tidy @[simp] lemma append_get_eq [has_append α] (a b : part α) (hab : dom (a ++ b)) : (a ++ b).get hab = a.get (left_dom_of_append_dom hab) ++ b.get (right_dom_of_append_dom hab) := by tidy lemma some_append_some [has_append α] (a b : α) : some a ++ some b = some (a ++ b) := by tidy lemma inter_mem_inter [has_inter α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma ∩ mb ∈ a ∩ b := by tidy lemma left_dom_of_inter_dom [has_inter α] {a b : part α} (hab : dom (a ∩ b)) : a.dom := by tidy lemma right_dom_of_inter_dom [has_inter α] {a b : part α} (hab : dom (a ∩ b)) : b.dom := by tidy @[simp] lemma inter_get_eq [has_inter α] (a b : part α) (hab : dom (a ∩ b)) : (a ∩ b).get hab = a.get (left_dom_of_inter_dom hab) ∩ b.get (right_dom_of_inter_dom hab) := by tidy lemma some_inter_some [has_inter α] (a b : α) : some a ∩ some b = some (a ∩ b) := by tidy lemma union_mem_union [has_union α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma ∪ mb ∈ a ∪ b := by tidy lemma left_dom_of_union_dom [has_union α] {a b : part α} (hab : dom (a ∪ b)) : a.dom := by tidy lemma right_dom_of_union_dom [has_union α] {a b : part α} (hab : dom (a ∪ b)) : b.dom := by tidy @[simp] lemma union_get_eq [has_union α] (a b : part α) (hab : dom (a ∪ b)) : (a ∪ b).get hab = a.get (left_dom_of_union_dom hab) ∪ b.get (right_dom_of_union_dom hab) := by tidy lemma some_union_some [has_union α] (a b : α) : some a ∪ some b = some (a ∪ b) := by tidy lemma sdiff_mem_sdiff [has_sdiff α] (a b : part α) (ma mb : α) (ha : ma ∈ a) (hb : mb ∈ b) : ma \ mb ∈ a \ b := by tidy lemma left_dom_of_sdiff_dom [has_sdiff α] {a b : part α} (hab : dom (a \ b)) : a.dom := by tidy lemma right_dom_of_sdiff_dom [has_sdiff α] {a b : part α} (hab : dom (a \ b)) : b.dom := by tidy @[simp] lemma sdiff_get_eq [has_sdiff α] (a b : part α) (hab : dom (a \ b)) : (a \ b).get hab = a.get (left_dom_of_sdiff_dom hab) \ b.get (right_dom_of_sdiff_dom hab) := by tidy lemma some_sdiff_some [has_sdiff α] (a b : α) : some a \ some b = some (a \ b) := by tidy end instances end part
986a675a07278f23d530ef91d041bc53513f131c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/compacts.lean
0b207d72cef260bdbf3479d1ad10b7342156bc84
[ "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
5,365
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import topology.homeomorph /-! # Compact sets ## Summary We define the subtype of compact sets in a topological space. ## Main Definitions - `closeds α` is the type of closed subsets of a topological space `α`. - `compacts α` is the type of compact subsets of a topological space `α`. - `nonempty_compacts α` is the type of non-empty compact subsets. - `positive_compacts α` is the type of compact subsets with non-empty interior. -/ open set variables (α : Type*) {β : Type*} [topological_space α] [topological_space β] namespace topological_space /-- The type of closed subsets of a topological space. -/ def closeds := {s : set α // is_closed s} /-- The type of closed subsets is inhabited, with default element the empty set. -/ instance : inhabited (closeds α) := ⟨⟨∅, is_closed_empty ⟩⟩ /-- The compact sets of a topological space. See also `nonempty_compacts`. -/ def compacts : Type* := { s : set α // is_compact s } /-- The type of non-empty compact subsets of a topological space. The non-emptiness will be useful in metric spaces, as we will be able to put a distance (and not merely an edistance) on this space. -/ def nonempty_compacts := {s : set α // s.nonempty ∧ is_compact s} /-- In an inhabited space, the type of nonempty compact subsets is also inhabited, with default element the singleton set containing the default element. -/ instance nonempty_compacts_inhabited [inhabited α] : inhabited (nonempty_compacts α) := ⟨⟨{default α}, singleton_nonempty (default α), is_compact_singleton ⟩⟩ /-- The compact sets with nonempty interior of a topological space. See also `compacts` and `nonempty_compacts`. -/ @[nolint has_inhabited_instance] def positive_compacts: Type* := { s : set α // is_compact s ∧ (interior s).nonempty } /-- In a nonempty compact space, `set.univ` is a member of `positive_compacts`, the compact sets with nonempty interior. -/ def positive_compacts_univ {α : Type*} [topological_space α] [compact_space α] [nonempty α] : positive_compacts α := ⟨set.univ, compact_univ, by simp⟩ @[simp] lemma positive_compacts_univ_val (α : Type*) [topological_space α] [compact_space α] [nonempty α] : (positive_compacts_univ : positive_compacts α).val = univ := rfl variables {α} namespace compacts instance : semilattice_sup_bot (compacts α) := subtype.semilattice_sup_bot is_compact_empty (λ K₁ K₂, is_compact.union) instance [t2_space α]: semilattice_inf_bot (compacts α) := subtype.semilattice_inf_bot is_compact_empty (λ K₁ K₂, is_compact.inter) instance [t2_space α] : lattice (compacts α) := subtype.lattice (λ K₁ K₂, is_compact.union) (λ K₁ K₂, is_compact.inter) @[simp] lemma bot_val : (⊥ : compacts α).1 = ∅ := rfl @[simp] lemma sup_val {K₁ K₂ : compacts α} : (K₁ ⊔ K₂).1 = K₁.1 ∪ K₂.1 := rfl @[ext] protected lemma ext {K₁ K₂ : compacts α} (h : K₁.1 = K₂.1) : K₁ = K₂ := subtype.eq h @[simp] lemma finset_sup_val {β} {K : β → compacts α} {s : finset β} : (s.sup K).1 = s.sup (λ x, (K x).1) := finset.sup_coe _ _ instance : inhabited (compacts α) := ⟨⊥⟩ /-- The image of a compact set under a continuous function. -/ protected def map (f : α → β) (hf : continuous f) (K : compacts α) : compacts β := ⟨f '' K.1, K.2.image hf⟩ @[simp] lemma map_val {f : α → β} (hf : continuous f) (K : compacts α) : (K.map f hf).1 = f '' K.1 := rfl /-- A homeomorphism induces an equivalence on compact sets, by taking the image. -/ @[simp] protected def equiv (f : α ≃ₜ β) : compacts α ≃ compacts β := { to_fun := compacts.map f f.continuous, inv_fun := compacts.map _ f.symm.continuous, left_inv := by { intro K, ext1, simp only [map_val, ← image_comp, f.symm_comp_self, image_id] }, right_inv := by { intro K, ext1, simp only [map_val, ← image_comp, f.self_comp_symm, image_id] } } /-- The image of a compact set under a homeomorphism can also be expressed as a preimage. -/ lemma equiv_to_fun_val (f : α ≃ₜ β) (K : compacts α) : (compacts.equiv f K).1 = f.symm ⁻¹' K.1 := congr_fun (image_eq_preimage_of_inverse f.left_inv f.right_inv) K.1 end compacts section nonempty_compacts open topological_space set variable {α} instance nonempty_compacts.to_compact_space {p : nonempty_compacts α} : compact_space p.val := ⟨is_compact_iff_is_compact_univ.1 p.property.2⟩ instance nonempty_compacts.to_nonempty {p : nonempty_compacts α} : nonempty p.val := p.property.1.to_subtype /-- Associate to a nonempty compact subset the corresponding closed subset -/ def nonempty_compacts.to_closeds [t2_space α] : nonempty_compacts α → closeds α := set.inclusion $ λ s hs, hs.2.is_closed end nonempty_compacts section positive_compacts variable (α) /-- In a nonempty locally compact space, there exists a compact set with nonempty interior. -/ instance nonempty_positive_compacts [locally_compact_space α] [nonempty α] : nonempty (positive_compacts α) := begin inhabit α, rcases exists_compact_subset is_open_univ (mem_univ (default α)) with ⟨K, hK⟩, exact ⟨⟨K, hK.1, ⟨_, hK.2.1⟩⟩⟩ end end positive_compacts end topological_space
02e24c5783a8e7bcc24da66ee953042dd26932fe
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/sheaves/sheaf_condition/sites.lean
ebc32d829f9d0d54a62a9bf98e8b40069c111e50
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,022
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer -/ import category_theory.sites.spaces import topology.sheaves.sheaf import category_theory.sites.dense_subsite /-! # Coverings and sieves; from sheaves on sites and sheaves on spaces In this file, we connect coverings in a topological space to sieves in the associated Grothendieck topology, in preparation of connecting the sheaf condition on sites to the various sheaf conditions on spaces. We also specialize results about sheaves on sites to sheaves on spaces; we show that the inclusion functor from a topological basis to `topological_space.opens` is cover_dense, that open maps induce cover_preserving functors, and that open embeddings induce compatible_preserving functors. -/ noncomputable theory universes w v u open category_theory topological_space namespace Top.presheaf variables {X : Top.{w}} /-- Given a presieve `R` on `U`, we obtain a covering family of open sets in `X`, by taking as index type the type of dependent pairs `(V, f)`, where `f : V ⟶ U` is in `R`. -/ def covering_of_presieve (U : opens X) (R : presieve U) : (Σ V, {f : V ⟶ U // R f}) → opens X := λ f, f.1 @[simp] lemma covering_of_presieve_apply (U : opens X) (R : presieve U) (f : Σ V, {f : V ⟶ U // R f}) : covering_of_presieve U R f = f.1 := rfl namespace covering_of_presieve variables (U : opens X) (R : presieve U) /-- If `R` is a presieve in the grothendieck topology on `opens X`, the covering family associated to `R` really is _covering_, i.e. the union of all open sets equals `U`. -/ lemma supr_eq_of_mem_grothendieck (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : supr (covering_of_presieve U R) = U := begin apply le_antisymm, { refine supr_le _, intro f, exact f.2.1.le, }, intros x hxU, rw [opens.mem_coe, opens.mem_supr], obtain ⟨V, iVU, ⟨W, iVW, iWU, hiWU, -⟩, hxV⟩ := hR x hxU, exact ⟨⟨W, ⟨iWU, hiWU⟩⟩, iVW.le hxV⟩, end end covering_of_presieve /-- Given a family of opens `U : ι → opens X` and any open `Y : opens X`, we obtain a presieve on `Y` by declaring that a morphism `f : V ⟶ Y` is a member of the presieve if and only if there exists an index `i : ι` such that `V = U i`. -/ def presieve_of_covering_aux {ι : Type v} (U : ι → opens X) (Y : opens X) : presieve Y := λ V f, ∃ i, V = U i /-- Take `Y` to be `supr U` and obtain a presieve over `supr U`. -/ def presieve_of_covering {ι : Type v} (U : ι → opens X) : presieve (supr U) := presieve_of_covering_aux U (supr U) /-- Given a presieve `R` on `Y`, if we take its associated family of opens via `covering_of_presieve` (which may not cover `Y` if `R` is not covering), and take the presieve on `Y` associated to the family of opens via `presieve_of_covering_aux`, then we get back the original presieve `R`. -/ @[simp] lemma covering_presieve_eq_self {Y : opens X} (R : presieve Y) : presieve_of_covering_aux (covering_of_presieve Y R) Y = R := by { ext Z f, exact ⟨λ ⟨⟨_,_,h⟩,rfl⟩, by convert h, λ h, ⟨⟨Z,f,h⟩,rfl⟩⟩ } namespace presieve_of_covering variables {ι : Type v} (U : ι → opens X) /-- The sieve generated by `presieve_of_covering U` is a member of the grothendieck topology. -/ lemma mem_grothendieck_topology : sieve.generate (presieve_of_covering U) ∈ opens.grothendieck_topology X (supr U) := begin intros x hx, obtain ⟨i, hxi⟩ := opens.mem_supr.mp hx, exact ⟨U i, opens.le_supr U i, ⟨U i, 𝟙 _, opens.le_supr U i, ⟨i, rfl⟩, category.id_comp _⟩, hxi⟩, end /-- An index `i : ι` can be turned into a dependent pair `(V, f)`, where `V` is an open set and `f : V ⟶ supr U` is a member of `presieve_of_covering U f`. -/ def hom_of_index (i : ι) : Σ V, {f : V ⟶ supr U // presieve_of_covering U f} := ⟨U i, opens.le_supr U i, i, rfl⟩ /-- By using the axiom of choice, a dependent pair `(V, f)` where `f : V ⟶ supr U` is a member of `presieve_of_covering U f` can be turned into an index `i : ι`, such that `V = U i`. -/ def index_of_hom (f : Σ V, {f : V ⟶ supr U // presieve_of_covering U f}) : ι := f.2.2.some lemma index_of_hom_spec (f : Σ V, {f : V ⟶ supr U // presieve_of_covering U f}) : f.1 = U (index_of_hom U f) := f.2.2.some_spec end presieve_of_covering end Top.presheaf namespace Top.opens variables {X : Top} {ι : Type*} lemma cover_dense_iff_is_basis [category ι] (B : ι ⥤ opens X) : cover_dense (opens.grothendieck_topology X) B ↔ opens.is_basis (set.range B.obj) := begin rw opens.is_basis_iff_nbhd, split, intros hd U x hx, rcases hd.1 U x hx with ⟨V,f,⟨i,f₁,f₂,hc⟩,hV⟩, exact ⟨B.obj i, ⟨i,rfl⟩, f₁.le hV, f₂.le⟩, intro hb, split, intros U x hx, rcases hb hx with ⟨_,⟨i,rfl⟩,hx,hi⟩, exact ⟨B.obj i, ⟨⟨hi⟩⟩, ⟨⟨i, 𝟙 _, ⟨⟨hi⟩⟩, rfl⟩⟩, hx⟩, end lemma cover_dense_induced_functor {B : ι → opens X} (h : opens.is_basis (set.range B)) : cover_dense (opens.grothendieck_topology X) (induced_functor B) := (cover_dense_iff_is_basis _).2 h end Top.opens section open_embedding open Top.presheaf opposite variables {C : Type u} [category.{v} C] variables {X Y : Top.{w}} {f : X ⟶ Y} {F : Y.presheaf C} lemma open_embedding.compatible_preserving (hf : open_embedding f) : compatible_preserving (opens.grothendieck_topology Y) hf.is_open_map.functor := begin haveI : mono f := (Top.mono_iff_injective f).mpr hf.inj, apply compatible_preserving_of_downwards_closed, intros U V i, refine ⟨(opens.map f).obj V, eq_to_iso $ opens.ext $ set.image_preimage_eq_of_subset $ λ x h, _⟩, obtain ⟨_, _, rfl⟩ := i.le h, exact ⟨_, rfl⟩ end lemma is_open_map.cover_preserving (hf : is_open_map f) : cover_preserving (opens.grothendieck_topology X) (opens.grothendieck_topology Y) hf.functor := begin constructor, rintros U S hU _ ⟨x, hx, rfl⟩, obtain ⟨V, i, hV, hxV⟩ := hU x hx, exact ⟨_, hf.functor.map i, ⟨_, i, 𝟙 _, hV, rfl⟩, set.mem_image_of_mem f hxV⟩ end lemma Top.presheaf.is_sheaf_of_open_embedding (h : open_embedding f) (hF : F.is_sheaf) : is_sheaf (h.is_open_map.functor.op ⋙ F) := pullback_is_sheaf_of_cover_preserving h.compatible_preserving h.is_open_map.cover_preserving ⟨_, hF⟩ end open_embedding namespace Top.sheaf open Top opposite variables {C : Type u} [category.{v} C] variables {X : Top.{w}} {ι : Type*} {B : ι → opens X} variables (F : X.presheaf C) (F' : sheaf C X) (h : opens.is_basis (set.range B)) /-- The empty component of a sheaf is terminal -/ def is_terminal_of_empty (F : sheaf C X) : limits.is_terminal (F.val.obj (op ∅)) := F.is_terminal_of_bot_cover ∅ (by tidy) /-- A variant of `is_terminal_of_empty` that is easier to `apply`. -/ def is_terminal_of_eq_empty (F : X.sheaf C) {U : opens X} (h : U = ∅) : limits.is_terminal (F.val.obj (op U)) := by convert F.is_terminal_of_empty /-- If a family `B` of open sets forms a basis of the topology on `X`, and if `F'` is a sheaf on `X`, then a homomorphism between a presheaf `F` on `X` and `F'` is equivalent to a homomorphism between their restrictions to the indexing type `ι` of `B`, with the induced category structure on `ι`. -/ def restrict_hom_equiv_hom : ((induced_functor B).op ⋙ F ⟶ (induced_functor B).op ⋙ F'.1) ≃ (F ⟶ F'.1) := @cover_dense.restrict_hom_equiv_hom _ _ _ _ _ _ _ _ (opens.cover_dense_induced_functor h) _ F F' @[simp] lemma extend_hom_app (α : ((induced_functor B).op ⋙ F ⟶ (induced_functor B).op ⋙ F'.1)) (i : ι) : (restrict_hom_equiv_hom F F' h α).app (op (B i)) = α.app (op i) := by { nth_rewrite 1 ← (restrict_hom_equiv_hom F F' h).left_inv α, refl } include h lemma hom_ext {α β : F ⟶ F'.1} (he : ∀ i, α.app (op (B i)) = β.app (op (B i))) : α = β := by { apply (restrict_hom_equiv_hom F F' h).symm.injective, ext i, exact he i.unop } end Top.sheaf
2244f43f76145b074608ffe6c9999b19cf76e3ee
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/list/default.lean
048d5a3c11c2725deb826ef99e08be22af165f2c
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,704
lean
import galois.tactic .init .tail .inter .map_accum_lemmas .nth .take_drop_lemmas .preds .fin_nth .mem universe u def second {X A B : Type} (f : A -> B) : X × A -> X × B | (x, y) := (x, f y) lemma second_simpl {X A B : Type} (f : A -> B) (x : X) (y : A) : second f (x, y) = (x, f y) := rfl namespace list -- This runs a function over a list returning the intermediate results and a -- a final result. def map_accuml {α σ β : Type} (f : σ → α → β × σ) : σ → list α → (list β × σ) | c [] := ([], c) | c (y::yr) := let z := f c y in let r := map_accuml z.2 yr in (z.1 :: r.1, r.2) def first_index_of_core {α : Type} (p : α → bool) : ℕ → list α → option (ℕ × α) | c [] := option.none | c (h::r) := if p h = tt then option.some (c,h) else first_index_of_core (c+1) r -- This searches a list for an element that satisfies a predicate. -- -- If it finds an element, it returns the index and element. Otherwise, it -- returns none. def first_index_of {α : Type} (p : α → bool) (l : list α) : option (ℕ × α) := first_index_of_core p 0 l def find_option {A} [decidable_eq A] (item: A) (l : list A) : option ℕ := let index := list.index_of item l in if index = l.length then none else some index lemma find_option_mem_len {A} [decidable_eq A] {x : A} {xs : list A} (H : x ∈ xs) : ∃ n, xs.find_option x = some n ∧ n < xs.length := begin rw ← list.index_of_lt_length at H, destruct (find_option x xs), { intros Hnone, exfalso, unfold find_option at Hnone, dsimp at Hnone, rw if_neg at Hnone, injection Hnone, apply ne_of_lt, assumption }, { intros n Hn, constructor, split, assumption, unfold find_option at Hn, dsimp at Hn, have H : index_of x xs ≠ length xs, apply ne_of_lt, assumption, rw (if_neg H) at Hn, injection Hn with Hn', rw ← Hn', assumption } end lemma find_option_mem {A} [decidable_eq A] {x : A} {xs : list A} (H : x ∈ xs) : ∃ n, xs.find_option x = some n := begin apply_in H find_option_mem_len, induction H with n H, induction H with H H', constructor, assumption, end lemma find_index_append {A} {P : A → Prop} [decidable_pred P] (xs ys : list A) (n : ℕ) (Hn : n ≠ xs.length) (H : xs.find_index P = n) : (xs ++ ys).find_index P = n := begin revert n, induction xs; intros, { dsimp [list.index_of, list.find_index] at H, subst n, exfalso, apply Hn, reflexivity, }, { dsimp [list.index_of, list.find_index] at H, rename a x, apply (if HPx : P x then _ else _), { rw (if_pos HPx) at H, subst n, dsimp [list.index_of, list.find_index], rw (if_pos HPx), }, { rw (if_neg HPx) at H, dsimp, dsimp [list.index_of, list.find_index], rw (if_neg HPx), cases n, injection H, rename a n, injection H with H', clear H, f_equal, apply ih_1, intros contra, apply Hn, dsimp [list.length], dsimp [has_add.add, nat.add], f_equal, assumption, assumption } } end lemma index_of_append {A} [decidable_eq A] (x : A) (xs ys : list A) (n : ℕ) (Hn : n ≠ xs.length) (H : list.index_of x xs = n) : list.index_of x (xs ++ ys) = n := begin apply list.find_index_append; assumption end lemma not_not_iff {a : Prop} [decidable a] : ¬¬a ↔ a := iff.intro by_contradiction not_not_intro lemma find_option_append {A} [decidable_eq A] (x : A) (xs ys : list A) (n : ℕ) (Hn : xs.find_option x = some n) : (xs ++ ys).find_option x = some n := begin unfold find_option at Hn, dsimp at Hn, apply (if H : list.index_of x xs = list.length xs then _ else _), { rw (if_pos H) at Hn, contradiction, }, { rw (if_neg H) at Hn, injection Hn with Hn', clear Hn, dsimp, dsimp [find_option], rw list.index_of_append, tactic.rotate 2, assumption, tactic.swap, intros contra, apply H, subst n, assumption, rw list.index_of_eq_length at H, subst Hn', rw [not_not_iff] at H, rw ← list.index_of_lt_length at H, have H1 : list.index_of x xs ≠ list.length (xs ++ ys), apply ne_of_lt, rw list.length_append, apply lt_of_lt_of_le, assumption, rw add_comm, apply le_add_of_nonneg_left, apply nat.zero_le, simp [H1], } end lemma nth_cons_drop {A : Type} : forall h t n (i :A), n ≠ 0 -> list.nth (h :: t) (n) = some i -> list.nth t (n - 1) = some i := begin intros, cases n, { contradiction }, { dsimp at *, simp at *, assumption, } end lemma pair_induction_same_length {X Y} (P : list X → list Y → Sort u) (P0 : P [] []) (PS : ∀ x y xs ys, P xs ys → P (x :: xs) (y :: ys)) (xs : list X) (ys : list Y) (H : xs.length = ys.length) : P xs ys := begin revert xs, induction ys; intros; dsimp at H, { apply_in H list.eq_nil_of_length_eq_zero, subst xs, assumption, }, { cases xs; dsimp at H, contradiction, apply PS, apply ih_1, apply nat.add_right_cancel, assumption, } end lemma map_compose {A B C : Type} (f : A -> B) (g : B -> C) (xs : list A) : map (g ∘ f) xs = map g (map f xs) := begin induction xs, { reflexivity }, { simp [map] } end lemma reverse_core_app {A : Type} (xs ys zs : list A) : list.reverse_core xs (ys ++ zs) = list.reverse_core xs ys ++ zs := begin revert ys zs, induction xs; intros, { simp [list.reverse_core] }, { simp [list.reverse_core], rw <- list.cons_append, rw ih_1 } end lemma cons_reverse {A : Type} (x : A) (xs : list A) : list.reverse (x :: xs) = list.reverse xs ++ [x] := begin unfold list.reverse, simp [list.reverse_core], induction xs, { reflexivity }, { simp [list.reverse_core], rw <- (reverse_core_app a_1 [a] [x]), dsimp, reflexivity } end lemma cons_reverse_app {A : Type} (x : A) (xs : list A) : (list.reverse ∘ list.cons x) xs = ((λ xs, xs ++ [x]) ∘ list.reverse) xs := begin induction xs, { reflexivity }, { simp [function.comp], } end lemma zip_same_length {X Y} (xs ys : list X) (xs' ys' : list Y) (H : xs.length = xs'.length) : zip (xs ++ ys) (xs' ++ ys') = zip xs xs' ++ zip ys ys' := begin revert H xs' xs, apply list.pair_induction_same_length, reflexivity, intros, dsimp [list.zip, list.zip_with], f_equal, assumption end lemma zip_map_r {X Y Z} (xs : list X) (ys : list Y) (f : Y → Z) : zip xs (map f ys) = list.map (second f) (list.zip xs ys) := begin revert ys, induction xs; intros, { reflexivity }, { cases ys, { reflexivity }, { dsimp [list.zip, list.zip_with], f_equal, specialize (ih_1 a_3), unfold list.zip at ih_1, rw ih_1, } } end lemma map_fst_second {X A B : Type} (xs : list (X × A)) (f : A -> B) : map (prod.fst ∘ second f) xs = map prod.fst xs := begin induction xs, { reflexivity }, { simp only [list.map], cases a with i1 i2, simp only [second], rw ih_1, reflexivity } end lemma map_not_nil {A B} (xs) (f : A -> B) (H : xs ≠ []) : list.map f xs ≠ [] := begin cases xs, { contradiction }, { simp [list.map], } end lemma map_nil {A B : Type} (f : A -> B) (xs : list A) (H : xs = []) : list.map f xs = [] := begin rw H, reflexivity end lemma repeat_length {A} (x : A) (n : ℕ) : (list.repeat x n).length = n := begin induction n; simp [list.repeat, list.length], end end list universe variable v namespace list variables {α : Type u} {β : Type v} /- null theorems -/ -- Return true if list is empty -- -- null x is equivalent to x = nil, but always decidable even if equality -- of list elements is undecidable def null : list α → Prop := λx, x = nil instance null_decidable : ∀ xs : list α, decidable (null xs) | nil := is_true (begin unfold null end) | (x :: xs) := is_false (begin unfold null, contradiction end) /- foldl theorem -/ -- Recursor to prove properties about a list and a left-fold over that list protected lemma foldl_rec_gen (P : list β → α → Prop) (f : α → β → α) (h : ∀(l : list β) (t : α) (e : β), P l t → P (l ++ [e]) (f t e)) : ∀(r : list β) (s : α), P r s → ∀ (l : list β), P (r ++ l) (foldl f s l) | r s p l := begin revert r s p, induction l, case list.nil { intros r s p, simp, exact p, }, case list.cons e l ind { intros r s p, simp [foldl], have g := ind (r ++ [e]) (f s e) (h r s e p), simp at g, exact g, } end -- Recursor to prove properties about a list and a left-fold over that list protected theorem foldl_rec (P : list β → α → Prop) (f : α → β → α) (ind_step : ∀(l : list β) (t : α) (e : β), P l t → P (l ++ [e]) (f t e)) (s : α) (base_case : P nil s) (l : list β) : P l (foldl f s l) := list.foldl_rec_gen P f ind_step nil s base_case l def drop_last {a : Type} (l : list a) := list.remove_nth l (list.length l - 1) end list
c50b04786645b479fa0b8bb3338a55d0793a8742
193da933cf42f2f9188bb47e3c973205bc2abc5c
/12_Sets/00_intro_sets.lean
a27e2f991392dc8aa7c4d3a21212817cf1ae4301
[]
no_license
pandaman64/cs-dm
aa4e2621c7a19e2dae911bc237c33e02fcb0c7a3
bfd2f5fd2612472e15bd970c7870b5d0dd73bd1c
refs/heads/master
1,647,620,340,607
1,570,055,187,000
1,570,055,187,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,128
lean
/- In Lean, set is a type constructor. It takes a type, T, as an argument and returns, as a result, the type, set T, which we read as the type of any set with elements of type, T. The type of set is thus Type → Type. Lean tells us that this type constructor can take a type in any type universe, i.e., Type, Type 1, etc. We needn't be concerned with that here. -/ #check set /- EXERCISE: Is set a type? Discuss. -/ #check set nat /- The type, set nat, or set T more generally, represents a property of value of type nat (or T): the property of "being in a given set!" -/ #reduce set nat /- We now define e to be the empty set of natural numbers. Lean gives us ordinary set display notation (using curly braces around a list of elements) for this purpose. -/ def e: set nat := { } /- The symbol, ∅, is often used to represent the empty set (of values of some type). -/ def e': set nat := ∅ /- We can't just say "e : set := {}"", because then Lean does not have enough context to infer the type of the elements. -/ /- EXERCISE: What is the property of natural numbers that characterizes the empty set of natural numbers? -/ #reduce e /- Study that carefully. The predicate that defines the empty set is, as we've alreadydiscussed, false(n): i.e., the function of type ℕ → Prop that for any value, n : ℕ, returns the proposition false. No natural number can makes the (proposition derived from the) predicate true, so no natural number is in the set that it represents. -/ /- We can also represent the empty set using set builder notation. -/ def e'' : set nat := { n | false } def ev(n : ℕ):Prop := ∃ m, m + m = n def v : set nat := { n | ev n } /- We read the right hand side as "the set of values, n, for which the predicate, false, is true." As there is no value that makes false true, the set is empty. It has no elements. -/ /- Here's another set of ℕ, containing only the number, 1. We call such a set a singleton set. -/ def x: set nat := { 1 } /- EXERCISE: What property of natural numbers defines the property of being in this set? Try to come up with the answer before you look! -/ #reduce x /- The answer is a little surprising. The predicate λ n, n = 1, would do to define this set, but instead Lean uses λ n, n = 1 ∨ false. The basic intuition is that, were we to remove the 1 from this set, we'd be left with the empty set, the predicate for which is that predicate false. -/ def x' := { n | n = 1 } #reduce x' /- The two notations give rise to slightly different but equivalent predicates. -/ -- SET MEMBERSHIP /- By the notation 1 ∈ x we mean the proposition that "1 is in, or is a member of the set, x." This is simplythe proposition obtained by applying the predicate, x, to the value, 1. The proposition is literally the value (x 1). Recall that function application works by substituting the argument (1) for the parameter (a) in the body of the predicate (function). In this case, the predicate, x, is λ (n : ℕ), n = 1. Applying this predicate/function the value, 1, reduces to the proposition that: 1 = 1 ∨ false. This proposition, in turn, is easy to prove, and so, yes, indeed, 1 is in the set x. -/ #reduce 1 ∈ x example : 1 ∈ x := -- 1 = 1 ∨ false begin apply or.intro_left, exact rfl, end /- Because the proposition, 1 ∈ x, is defined to be the disjunction, (1 = 1 ∨ false), you can ask Lean to change the format of the goal accordingly. If doing this makes it easier for you to see how to proceed with the proof, feel free to use it. You can cut and paste the disjunction from the string that #reduce 3 ∈ u prints out. -/ example : 1 ∈ x := -- 1 = 1 begin change 1 = 1 ∨ false, -- now or.intro_left, but with a shortcut left, -- and now exact rfl, but with a shortcut trivial, end -- ANOTHER EXAMPLE /- Here's two sets with three elements each. -/ def y : set nat := { 1, 2, 3 } def z : set nat := { 2, 3, 4 } /- EXERCISE: What is a predicate that characterizes membership in the set, y? -/ #reduce y /- EXERCISE: Define the same set, y, with the name, y', using set builder notation. -/ def y' : set nat := { n | n = 1 ∨ n = 2 ∨ n = 3 } #reduce y /- With these basics in hand, we can define, understand, and work with the full range of set operations. Set operations are like operations with numbers but their operands and results are sets. -/ -- SET UNION /- The union of two sets, y and z, which we denote as y ∪ z, is the combined set of values from y and z. An element is either in or not in a given, but cannot be in a more than one time (otherwise you have what is called a multiset). The union of y and z as defined above is thus the set { 1, 2, 3, 4 }. -/ def u := y ∪ z /- EXERCISE: What predicate defines the set that is the union of y and z? -/ #reduce u /- Answer: It is the predicate that defines what it means to be in y or to be in z. That is, it is the disjunction of the predicates that define y and z, respectively. Union corresponds to "or." -/ /- Let's prove that 3 ∈ u. Let's start by reminding ourselves of the predicate that defines u and of the proposition represented by 3 ∈ u. -/ #reduce u /- The set, u, is defined as a predicate that takes a : ℕ and returns the proposition that that a is one of the values in the set, expressed as a somewhat long disjunction. Lean selects the variable name, a, for purposes of printing out the value of u. There is no special meaning to a; it is just an otherwise unbound name. -/ /- Now that we know that 3 ∈ u is just a proposition involving a bunch of disjunctions, it's easy to prove. -/ example : 3 ∈ u := begin /- Notice again that Lean leaves the goal written using set membership notation. Just bear in mind that the goal is just the disjunction, (3 = 3 ∨ 3 = 2 ∨ 3 = 1 ∨ false) ∨ 3 = 4 ∨ 3 = 3 ∨ 3 = 2 ∨ false. -/ left, left, trivial, end /- Or, if you prefer, make the goal explicit as a disjunction. -/ example : 3 ∈ y ∪ z := begin change (3 = 3 ∨ 3 = 2 ∨ 3 = 1 ∨ false) ∨ 3 = 4 ∨ 3 = 3 ∨ 3 = 2 ∨ false, apply or.inl, apply or.inl, trivial, end -- SET INTERSECTION /- The intersection of two sets, y and z, which we denote as y ∩ z, is the set containing those values that are in y and that are in z. Intersection thus corresponds to the conjunction of the predicates defining the two individual sets. -/ def w := y ∩ z #reduce w example : 2 ∈ y ∩ z := -- (a = 3 ∨ a = 2 ∨ a = 1 ∨ false) ∧ (a = 4 ∨ a = 3 ∨ a = 2 ∨ false) begin apply and.intro, right, left, trivial, right, right, left, trivial, end -- SET DIFFERENCE /- The set difference y - z, also writen as y \ z, is the set of values that are in y but not in z. Think of the subtraction as saying that from y you take away z, and the result is what is left of y. EXERCISE: What predicate defines a set difference, y \ z? -/ #reduce y \ z example : 1 ∈ y \ z := begin -- apply and.intro, split, right, right, left, trivial, /- The goal looks funny, but think about what it means. It is the predicate, (λ (a : ℕ), a ∉ z), applied to the value, 1, which is to say it's the proposition, 1 ∉ z. That in turn is ¬ 1 ∈ z. And that, in turn, is just the proposition that 1 ∈ z → false. So assume 1 ∈ z and show false to prove it. What is 1 ∈ z? It's the proposition that 1 is one of the elements in the set, written as a disjunction, so use case analysis! -/ assume pf, cases pf, /- Now we need a proof that 1 ≠ 4. The dec_trivial tactic defined in the Lean's standard library "decides" many purely arithmetic propositions. That is, it generates either a proof that such a proposition is true if it's true. It will also generate a proof that its negation is true if that is the case. The dec_trivial tactic implements a "decision procedure" for sufficiently simple propositions involved numbers. Here we use it to give us a proof of 1 ≠ 4. We can then use that to get a proof of false and use false elim to eliminate the current case on grounds that it is based on contradictory assumptions (and thus can't happen). -/ have h : 1 ≠ 4 := dec_trivial, /- The contradiction tactic looks for a explicit contradiction in the context and if it finds one, applies false.elim to finish proving the goal. -/ contradiction, cases pf, have h : 1 ≠ 3 := dec_trivial, contradiction, cases pf, have h : 1 ≠ 2 := dec_trivial, contradiction, have f : false := pf, contradiction, end -- SUMMARY SO FAR /- A set can be characterized by a predicate: one that is true for each member of the set and false otherwise. The union of two sets is given by the disjunction (or) of the predicates: (a ∈ y ∪ z) = (a ∈ y) ∨ (a ∈ z) The conjunction is defined by their conjunction: (x ∈ y ∩ z) = (x ∈ y ∧ a ∈ z) Their difference is defined by the conjunction of the first and the negation of the second: (a ∈ y \ z) = ( a ∈ y) ∧ (¬ a ∈ z) -/ -- PART II /- Now we introduce addition basic set theory concepts: subsets, power sets, and product sets. -/ -- Subset /- Subset, denoted ⊂, is a binary relation on sets, denoted X ⊂ Y, where X and Y are sets, that is true iff every element of X is also in (an element of) Y. So, { 1, 2 } ⊂ { 1, 2, 3 } but ¬ { 1, 2 } ⊂ { 1, 3, 4}. In the first case, every element of the set, { 1, 2 }, is also in the set { 1, 2, 3 }, so { 1, 2 } is a subset of { 1, 2, 3 }, but that is not the case for { 1, 2 } and { 1, 3, 4 }. Remember that in Lean, "set" is not a type but a type constructor, a.k.a., a polymorphic type. Rather, for any type, T, set T is a type, namely the type of sets containing elements of type T. Even the empty set always has an element type, so, for example, the empty set of ℕ is not the same as the empty set of strings. -/ /- EXERCISE: List all of the subsets of each of the following sets of ℕ. * ∅ * { 1 } * { 1, 2 } * { 1, 2, 3 } EXERCISE: How many subsets are there f a set containing n elements. Does your formula work even for the empty set, containing 0 elements? -/ theorem foo : x ⊂ y := _
86516d1392c94f44411699b00e2ba530f1f56451
947b78d97130d56365ae2ec264df196ce769371a
/src/Init/Data/Option/Basic.lean
1209ab27650173a570d728a873f65b9fb1c6c311
[ "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
3,350
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 -/ prelude import Init.Core import Init.Control.Monad import Init.Control.Alternative import Init.Coe open Decidable universes u v namespace Option def toMonad {m : Type → Type} [Monad m] [Alternative m] {A} : Option A → m A | none => failure | some a => pure a @[macroInline] def getD {α : Type u} : Option α → α → α | some x, _ => x | none, e => e @[inline] def toBool {α : Type u} : Option α → Bool | some _ => true | none => false @[inline] def isSome {α : Type u} : Option α → Bool | some _ => true | none => false @[inline] def isNone {α : Type u} : Option α → Bool | some _ => false | none => true @[inline] protected def bind {α : Type u} {β : Type v} : Option α → (α → Option β) → Option β | none, b => none | some a, b => b a @[inline] protected def map {α β} (f : α → β) (o : Option α) : Option β := Option.bind o (some ∘ f) theorem mapId {α} : (Option.map id : Option α → Option α) = id := funext (fun o => match o with | none => rfl | some x => rfl) instance : Monad Option := {pure := @some, bind := @Option.bind, map := @Option.map} @[inline] protected def filter {α} (p : α → Bool) : Option α → Option α | some a => if p a then some a else none | none => none @[inline] protected def all {α} (p : α → Bool) : Option α → Bool | some a => p a | none => true @[inline] protected def any {α} (p : α → Bool) : Option α → Bool | some a => p a | none => false @[macroInline] protected def orelse {α : Type u} : Option α → Option α → Option α | some a, _ => some a | none, b => b /- Remark: when using the polymorphic notation `a <|> b` is not a `[macroInline]`. Thus, `a <|> b` will make `Option.orelse` to behave like it was marked as `[inline]`. -/ instance : Alternative Option := { Option.Monad with failure := @none, orelse := @Option.orelse } @[inline] protected def lt {α : Type u} (r : α → α → Prop) : Option α → Option α → Prop | none, some x => True | some x, some y => r x y | _, _ => False instance decidableRelLt {α : Type u} (r : α → α → Prop) [s : DecidableRel r] : DecidableRel (Option.lt r) | none, some y => isTrue trivial | some x, some y => s x y | some x, none => isFalse notFalse | none, none => isFalse notFalse end Option instance (α : Type u) : Inhabited (Option α) := ⟨none⟩ instance {α : Type u} [DecidableEq α] : DecidableEq (Option α) := fun a b => match a, b with | none, none => isTrue rfl | none, (some v₂) => isFalse (fun h => Option.noConfusion h) | (some v₁), none => isFalse (fun h => Option.noConfusion h) | (some v₁), (some v₂) => match decEq v₁ v₂ with | (isTrue e) => isTrue (congrArg (@some α) e) | (isFalse n) => isFalse (fun h => Option.noConfusion h (fun e => absurd e n)) instance {α : Type u} [HasBeq α] : HasBeq (Option α) := ⟨fun a b => match a, b with | none, none => true | none, (some v₂) => false | (some v₁), none => false | (some v₁), (some v₂) => v₁ == v₂⟩ instance {α : Type u} [HasLess α] : HasLess (Option α) := ⟨Option.lt HasLess.Less⟩
545c71f34363221ac5d61a1f064ab030a0e35801
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world7/level6.lean
53890293003be9942a07fde45f624adc0828f646
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
86
lean
example (P Q : Prop) : Q → P ∨ Q := begin intro q, right, exact q, end
96dcc5e3c0d75ac0e9c0dafab45220656ab88d85
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/inner_product_space/euclidean_dist.lean
d8a0b8fb792832fecba75776b928c3ffe00ff09e
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
4,858
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.inner_product_space.calculus import analysis.inner_product_space.pi_L2 /-! # Euclidean distance on a finite dimensional space When we define a smooth bump function on a normed space, it is useful to have a smooth distance on the space. Since the default distance is not guaranteed to be smooth, we define `to_euclidean` to be an equivalence between a finite dimensional topological vector space and the standard Euclidean space of the same dimension. Then we define `euclidean.dist x y = dist (to_euclidean x) (to_euclidean y)` and provide some definitions (`euclidean.ball`, `euclidean.closed_ball`) and simple lemmas about this distance. This way we hide the usage of `to_euclidean` behind an API. -/ open_locale topology open set variables {E : Type*} [add_comm_group E] [topological_space E] [topological_add_group E] [t2_space E] [module ℝ E] [has_continuous_smul ℝ E] [finite_dimensional ℝ E] noncomputable theory open finite_dimensional /-- If `E` is a finite dimensional space over `ℝ`, then `to_euclidean` is a continuous `ℝ`-linear equivalence between `E` and the Euclidean space of the same dimension. -/ def to_euclidean : E ≃L[ℝ] euclidean_space ℝ (fin $ finrank ℝ E) := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm namespace euclidean /-- If `x` and `y` are two points in a finite dimensional space over `ℝ`, then `euclidean.dist x y` is the distance between these points in the metric defined by some inner product space structure on `E`. -/ def dist (x y : E) : ℝ := dist (to_euclidean x) (to_euclidean y) /-- Closed ball w.r.t. the euclidean distance. -/ def closed_ball (x : E) (r : ℝ) : set E := {y | dist y x ≤ r} /-- Open ball w.r.t. the euclidean distance. -/ def ball (x : E) (r : ℝ) : set E := {y | dist y x < r} lemma ball_eq_preimage (x : E) (r : ℝ) : ball x r = to_euclidean ⁻¹' (metric.ball (to_euclidean x) r) := rfl lemma closed_ball_eq_preimage (x : E) (r : ℝ) : closed_ball x r = to_euclidean ⁻¹' (metric.closed_ball (to_euclidean x) r) := rfl lemma ball_subset_closed_ball {x : E} {r : ℝ} : ball x r ⊆ closed_ball x r := λ y (hy : _ < _), le_of_lt hy lemma is_open_ball {x : E} {r : ℝ} : is_open (ball x r) := metric.is_open_ball.preimage to_euclidean.continuous lemma mem_ball_self {x : E} {r : ℝ} (hr : 0 < r) : x ∈ ball x r := metric.mem_ball_self hr lemma closed_ball_eq_image (x : E) (r : ℝ) : closed_ball x r = to_euclidean.symm '' metric.closed_ball (to_euclidean x) r := by rw [to_euclidean.image_symm_eq_preimage, closed_ball_eq_preimage] lemma is_compact_closed_ball {x : E} {r : ℝ} : is_compact (closed_ball x r) := begin rw closed_ball_eq_image, exact (is_compact_closed_ball _ _).image to_euclidean.symm.continuous end lemma is_closed_closed_ball {x : E} {r : ℝ} : is_closed (closed_ball x r) := is_compact_closed_ball.is_closed lemma closure_ball (x : E) {r : ℝ} (h : r ≠ 0) : closure (ball x r) = closed_ball x r := by rw [ball_eq_preimage, ← to_euclidean.preimage_closure, closure_ball (to_euclidean x) h, closed_ball_eq_preimage] lemma exists_pos_lt_subset_ball {R : ℝ} {s : set E} {x : E} (hR : 0 < R) (hs : is_closed s) (h : s ⊆ ball x R) : ∃ r ∈ Ioo 0 R, s ⊆ ball x r := begin rw [ball_eq_preimage, ← image_subset_iff] at h, rcases exists_pos_lt_subset_ball hR (to_euclidean.is_closed_image.2 hs) h with ⟨r, hr, hsr⟩, exact ⟨r, hr, image_subset_iff.1 hsr⟩ end lemma nhds_basis_closed_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (closed_ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap x], exact metric.nhds_basis_closed_ball.comap _ end lemma closed_ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : closed_ball x r ∈ 𝓝 x := nhds_basis_closed_ball.mem_of_mem hr lemma nhds_basis_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap x], exact metric.nhds_basis_ball.comap _ end lemma ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : ball x r ∈ 𝓝 x := nhds_basis_ball.mem_of_mem hr end euclidean variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] {G : Type*} [normed_add_comm_group G] [normed_space ℝ G] [finite_dimensional ℝ G] {f g : F → G} {n : ℕ∞} lemma cont_diff.euclidean_dist (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) (h : ∀ x, f x ≠ g x) : cont_diff ℝ n (λ x, euclidean.dist (f x) (g x)) := begin simp only [euclidean.dist], apply @cont_diff.dist ℝ, exacts [(@to_euclidean G _ _ _ _ _ _ _).cont_diff.comp hf, (@to_euclidean G _ _ _ _ _ _ _).cont_diff.comp hg, λ x, to_euclidean.injective.ne (h x)] end
acb48d27b051246d56df39bd11f1b44d0709483b
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Meta/Tactic/Simp/SimpLemmas.lean
fe0c69d5c95046c1160522b927a19f3dafdff4dd
[ "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
5,344
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.LevelDefEq import Lean.Meta.DiscrTree namespace Lean.Meta inductive SimpLemmaKind where | eq | iff | pos | neg deriving Inhabited, BEq structure SimpLemma where keys : Array DiscrTree.Key val : Expr priority : Nat post : Bool perm : Bool -- true is lhs and rhs are identical modulo permutation of variables name? : Option Name := none -- for debugging and tracing purposes kind : SimpLemmaKind deriving Inhabited instance : ToFormat SimpLemma where format s := let perm := if s.perm then ":perm" else "" let name := match s.name? with | some n => fmt n | none => "<unknown>" let prio := f!":{s.priority}" name ++ prio ++ perm instance : ToMessageData SimpLemma where toMessageData s := fmt s instance : BEq SimpLemma where beq e₁ e₂ := e₁.val == e₂.val structure SimpLemmas where pre : DiscrTree SimpLemma := DiscrTree.empty post : DiscrTree SimpLemma := DiscrTree.empty deriving Inhabited def addSimpLemmaEntry (d : SimpLemmas) (e : SimpLemma) : SimpLemmas := if e.post then { d with post := d.post.insertCore e.keys e } else { d with pre := d.pre.insertCore e.keys e } builtin_initialize simpExtension : SimpleScopedEnvExtension SimpLemma SimpLemmas ← registerSimpleScopedEnvExtension { name := `simpExt initial := {} addEntry := addSimpLemmaEntry } private partial def isPerm : Expr → Expr → MetaM Bool | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂ | Expr.mdata _ s _, t => isPerm s t | s, Expr.mdata _ t _ => isPerm s t | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ => isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => i₁ == i₂ <&&> isPerm b₁ b₂ | s, t => s == t def mkSimpLemmaCore (e : Expr) (val : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do let type ← inferType e unless (← isProp type) do throwError! "invalid 'simp', proposition expected{indentExpr type}" withNewMCtxDepth do let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type let (keys, perm, kind) ← match type.eq? with | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs, SimpLemmaKind.eq) | none => match type.iff? with | some (lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs, SimpLemmaKind.iff) | none => match type.not? with | some lhs => pure (← DiscrTree.mkPath lhs, false, SimpLemmaKind.neg) | none => pure (← DiscrTree.mkPath type, false, SimpLemmaKind.pos) return { keys := keys, perm := perm, kind := kind, post := post, val := val, name? := name?, priority := prio } def addSimpLemma (declName : Name) (post : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let cinfo ← getConstInfo declName /- The `simp` tactic uses fresh universe metavariables when using a global simp lemma. See `SimpLemma.getValue` -/ let lemma ← mkSimpLemmaCore (mkConst declName (cinfo.lparams.map mkLevelParam)) (mkConst declName) post prio declName simpExtension.add lemma attrKind pure () builtin_initialize registerBuiltinAttribute { name := `simp descr := "simplification lemma" add := fun declName stx attrKind => do let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost let prio ← getAttrParamOptPrio stx[2] discard <| addSimpLemma declName post attrKind prio |>.run {} {} } def getSimpLemmas : MetaM SimpLemmas := return simpExtension.getState (← getEnv) /- Auxiliary method for creating a local simp lemma. -/ def mkSimpLemma (e : Expr) (post : Bool := true) (prio : Nat := evalPrio! default) (name? : Option Name := none) : MetaM SimpLemma := do mkSimpLemmaCore e e post prio name? /- Auxiliary method for adding a local simp lemma to a `SimpLemmas` datastructure. -/ def SimpLemmas.add (s : SimpLemmas) (e : Expr) (post : Bool := true) (prio : Nat := evalPrio! default) (name? : Option Name := none) : MetaM SimpLemmas := do let lemma ← mkSimpLemma e post prio name? return addSimpLemmaEntry s lemma def SimpLemma.getValue (lemma : SimpLemma) : MetaM Expr := do match lemma.val with | Expr.const declName [] _ => let info ← getConstInfo declName if info.lparams.isEmpty then return lemma.val else return lemma.val.updateConst! (← info.lparams.mapM (fun _ => mkFreshLevelMVar)) | _ => return lemma.val end Lean.Meta
3b02cdc825bd795a5c3b2e99d1fc9a3030ba1597
2f8bf12144551bc7d8087a6320990c4621741f3d
/library/init/lean/compiler/ir/freevars.lean
7b2467934a5acc4a7d95fa8396c2920b894afa13
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean4
eb63a12960e69823749edceb4f23fd33fa2253ce
fa16920a6a7700cabc567aa629ce4ae2478a2f40
refs/heads/master
1,589,935,810,594
1,557,177,860,000
1,557,177,860,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,297
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.compiler.ir.basic namespace Lean namespace IR namespace MaxIndex /- Compute the maximum index `M` used in a declaration. We `M` to initialize the fresh index generator used to create fresh variable and join point names. Recall that we variable and join points share the same namespace in our implementation. -/ abbrev Collector := Index → Index @[inline] private def skip : Collector := id @[inline] private def collect (x : Index) : Collector := λ y, if x > y then x else y @[inline] private def collectVar (x : VarId) : Collector := collect x.idx @[inline] private def collectJP (j : JoinPointId) : Collector := collect j.idx @[inline] private def seq (k₁ k₂ : Collector) : Collector := k₂ ∘ k₁ instance : HasAndthen Collector := ⟨seq⟩ private def collectArg : Arg → Collector | (Arg.var x) := collectVar x | irrelevant := skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := λ m, as.foldl (λ m a, f a m) m private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def collectParam (p : Param) : Collector := collectVar p.x private def collectParams (ps : Array Param) : Collector := collectArray ps collectParam private def collectExpr : Expr → Collector | (Expr.ctor _ ys) := collectArgs ys | (Expr.reset x) := collectVar x | (Expr.reuse x _ _ ys) := collectVar x; collectArgs ys | (Expr.proj _ x) := collectVar x | (Expr.uproj _ x) := collectVar x | (Expr.sproj _ _ x) := collectVar x | (Expr.fap _ ys) := collectArgs ys | (Expr.pap _ ys) := collectArgs ys | (Expr.ap x ys) := collectVar x; collectArgs ys | (Expr.box _ x) := collectVar x | (Expr.unbox x) := collectVar x | (Expr.lit v) := skip | (Expr.isShared x) := collectVar x | (Expr.isTaggedPtr x) := collectVar x private def collectAlts (f : FnBody → Collector) (alts : Array Alt) : Collector := collectArray alts $ λ alt, f alt.body partial def collectFnBody : FnBody → Collector | (FnBody.vdecl x _ v b) := collectExpr v; collectFnBody b | (FnBody.jdecl j ys _ v b) := collectFnBody v; collectParams ys; collectFnBody b | (FnBody.set x _ y b) := collectVar x; collectVar y; collectFnBody b | (FnBody.uset x _ y b) := collectVar x; collectVar y; collectFnBody b | (FnBody.sset x _ _ y _ b) := collectVar x; collectVar y; collectFnBody b | (FnBody.release x _ b) := collectVar x; collectFnBody b | (FnBody.inc x _ _ b) := collectVar x; collectFnBody b | (FnBody.dec x _ _ b) := collectVar x; collectFnBody b | (FnBody.mdata _ b) := collectFnBody b | (FnBody.case _ x alts) := collectVar x; collectAlts collectFnBody alts | (FnBody.jmp j ys) := collectJP j; collectArgs ys | (FnBody.ret x) := collectArg x | FnBody.unreachable := skip partial def collectDecl : Decl → Collector | (Decl.fdecl _ xs _ b) := collectParams xs; collectFnBody b | (Decl.extern _ xs _) := collectParams xs end MaxIndex def FnBody.maxIndex (b : FnBody) : Index := MaxIndex.collectFnBody b 0 def Decl.maxIndex (d : Decl) : Index := MaxIndex.collectDecl d 0 namespace FreeIndices /- We say a variable (join point) index (aka name) is free in a function body if there isn't a `FnBody.vdecl` (`Fnbody.jdecl`) binding it. -/ abbrev Collector := IndexSet → IndexSet → IndexSet @[inline] private def skip : Collector := λ bv fv, fv @[inline] private def collectIndex (x : Index) : Collector := λ bv fv, if bv.contains x then fv else fv.insert x @[inline] private def collectVar (x : VarId) : Collector := collectIndex x.idx @[inline] private def collectJP (x : JoinPointId) : Collector := collectIndex x.idx @[inline] private def withIndex (x : Index) : Collector → Collector := λ k bv fv, k (bv.insert x) fv @[inline] private def withVar (x : VarId) : Collector → Collector := withIndex x.idx @[inline] private def withJP (x : JoinPointId) : Collector → Collector := withIndex x.idx def insertParams (s : IndexSet) (ys : Array Param) : IndexSet := ys.foldl (λ s p, s.insert p.x.idx) s @[inline] private def withParams (ys : Array Param) : Collector → Collector := λ k bv fv, k (insertParams bv ys) fv @[inline] private def seq : Collector → Collector → Collector := λ k₁ k₂ bv fv, k₂ bv (k₁ bv fv) instance : HasAndthen Collector := ⟨seq⟩ private def collectArg : Arg → Collector | (Arg.var x) := collectVar x | irrelevant := skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := λ bv fv, as.foldl (λ fv a, f a bv fv) fv private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def collectExpr : Expr → Collector | (Expr.ctor _ ys) := collectArgs ys | (Expr.reset x) := collectVar x | (Expr.reuse x _ _ ys) := collectVar x; collectArgs ys | (Expr.proj _ x) := collectVar x | (Expr.uproj _ x) := collectVar x | (Expr.sproj _ _ x) := collectVar x | (Expr.fap _ ys) := collectArgs ys | (Expr.pap _ ys) := collectArgs ys | (Expr.ap x ys) := collectVar x; collectArgs ys | (Expr.box _ x) := collectVar x | (Expr.unbox x) := collectVar x | (Expr.lit v) := skip | (Expr.isShared x) := collectVar x | (Expr.isTaggedPtr x) := collectVar x private def collectAlts (f : FnBody → Collector) (alts : Array Alt) : Collector := collectArray alts $ λ alt, f alt.body partial def collectFnBody : FnBody → Collector | (FnBody.vdecl x _ v b) := collectExpr v; withVar x (collectFnBody b) | (FnBody.jdecl j ys _ v b) := withParams ys (collectFnBody v); withJP j (collectFnBody b) | (FnBody.set x _ y b) := collectVar x; collectVar y; collectFnBody b | (FnBody.uset x _ y b) := collectVar x; collectVar y; collectFnBody b | (FnBody.sset x _ _ y _ b) := collectVar x; collectVar y; collectFnBody b | (FnBody.release x _ b) := collectVar x; collectFnBody b | (FnBody.inc x _ _ b) := collectVar x; collectFnBody b | (FnBody.dec x _ _ b) := collectVar x; collectFnBody b | (FnBody.mdata _ b) := collectFnBody b | (FnBody.case _ x alts) := collectVar x; collectAlts collectFnBody alts | (FnBody.jmp j ys) := collectJP j; collectArgs ys | (FnBody.ret x) := collectArg x | FnBody.unreachable := skip end FreeIndices def FnBody.collectFreeIndices (b : FnBody) (vs : IndexSet) : IndexSet := FreeIndices.collectFnBody b {} vs def FnBody.freeIndices (b : FnBody) : IndexSet := b.collectFreeIndices {} namespace HasIndex /- In principle, we can check whether a function body `b` contains an index `i` using `b.freeIndices.contains i`, but it is more efficient to avoid the construction of the set of freeIndices and just search whether `i` occurs in `b` or not. -/ def visitVar (w : Index) (x : VarId) : Bool := w == x.idx def visitJP (w : Index) (x : JoinPointId) : Bool := w == x.idx def visitArg (w : Index) : Arg → Bool | (Arg.var x) := visitVar w x | _ := false def visitArgs (w : Index) (xs : Array Arg) : Bool := xs.any (visitArg w) def visitParams (w : Index) (ps : Array Param) : Bool := ps.any (λ p, w == p.x.idx) def visitExpr (w : Index) : Expr → Bool | (Expr.ctor _ ys) := visitArgs w ys | (Expr.reset x) := visitVar w x | (Expr.reuse x _ _ ys) := visitVar w x || visitArgs w ys | (Expr.proj _ x) := visitVar w x | (Expr.uproj _ x) := visitVar w x | (Expr.sproj _ _ x) := visitVar w x | (Expr.fap _ ys) := visitArgs w ys | (Expr.pap _ ys) := visitArgs w ys | (Expr.ap x ys) := visitVar w x || visitArgs w ys | (Expr.box _ x) := visitVar w x | (Expr.unbox x) := visitVar w x | (Expr.lit v) := false | (Expr.isShared x) := visitVar w x | (Expr.isTaggedPtr x) := visitVar w x partial def visitFnBody (w : Index) : FnBody → Bool | (FnBody.vdecl x _ v b) := visitExpr w v || (!visitVar w x && visitFnBody b) | (FnBody.jdecl j ys _ v b) := (!visitParams w ys && visitFnBody v) || (!visitJP w j && visitFnBody b) | (FnBody.set x _ y b) := visitVar w x || visitVar w y || visitFnBody b | (FnBody.uset x _ y b) := visitVar w x || visitVar w y || visitFnBody b | (FnBody.sset x _ _ y _ b) := visitVar w x || visitVar w y || visitFnBody b | (FnBody.release x _ b) := visitVar w x || visitFnBody b | (FnBody.inc x _ _ b) := visitVar w x || visitFnBody b | (FnBody.dec x _ _ b) := visitVar w x || visitFnBody b | (FnBody.mdata _ b) := visitFnBody b | (FnBody.jmp j ys) := visitJP w j || visitArgs w ys | (FnBody.ret x) := visitArg w x | (FnBody.case _ x alts) := visitVar w x || alts.any (λ alt, visitFnBody alt.body) | (FnBody.unreachable) := false end HasIndex def Arg.hasFreeVar (arg : Arg) (x : VarId) : Bool := HasIndex.visitArg x.idx arg def Expr.hasFreeVar (e : Expr) (x : VarId) : Bool := HasIndex.visitExpr x.idx e def FnBody.hasFreeVar (b : FnBody) (x : VarId) : Bool := HasIndex.visitFnBody x.idx b end IR end Lean
6a95392202b873d1efd52b33902a122b9c3df1d6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/filter/countable_Inter.lean
9dbcb17230763bd211a8e9634cb3afb32f30d07c
[ "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
11,293
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import order.filter.basic import data.set.countable /-! # Filters with countable intersection property > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `countable_Inter_filter` to be the class of filters with the following property: for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. Two main examples are the `residual` filter defined in `topology.G_delta` and the `measure.ae` filter defined in `measure_theory.measure_space`. We reformulate the definition in terms of indexed intersection and in terms of `filter.eventually` and provide instances for some basic constructions (`⊥`, `⊤`, `filter.principal`, `filter.map`, `filter.comap`, `has_inf.inf`). We also provide a custom constructor `filter.of_countable_Inter` that deduces two axioms of a `filter` from the countable intersection property. ## Tags filter, countable -/ open set filter open_locale filter variables {ι : Sort*} {α β : Type*} /-- A filter `l` has the countable intersection property if for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. -/ class countable_Inter_filter (l : filter α) : Prop := (countable_sInter_mem' : ∀ {S : set (set α)} (hSc : S.countable) (hS : ∀ s ∈ S, s ∈ l), ⋂₀ S ∈ l) variables {l : filter α} [countable_Inter_filter l] lemma countable_sInter_mem {S : set (set α)} (hSc : S.countable) : ⋂₀ S ∈ l ↔ ∀ s ∈ S, s ∈ l := ⟨λ hS s hs, mem_of_superset hS (sInter_subset_of_mem hs), countable_Inter_filter.countable_sInter_mem' hSc⟩ lemma countable_Inter_mem [countable ι] {s : ι → set α} : (⋂ i, s i) ∈ l ↔ ∀ i, s i ∈ l := sInter_range s ▸ (countable_sInter_mem (countable_range _)).trans forall_range_iff lemma countable_bInter_mem {ι : Type*} {S : set ι} (hS : S.countable) {s : Π i ∈ S, set α} : (⋂ i ∈ S, s i ‹_›) ∈ l ↔ ∀ i ∈ S, s i ‹_› ∈ l := begin rw [bInter_eq_Inter], haveI := hS.to_encodable, exact countable_Inter_mem.trans subtype.forall end lemma eventually_countable_forall [countable ι] {p : α → ι → Prop} : (∀ᶠ x in l, ∀ i, p x i) ↔ ∀ i, ∀ᶠ x in l, p x i := by simpa only [filter.eventually, set_of_forall] using @countable_Inter_mem _ _ l _ _ (λ i, {x | p x i}) lemma eventually_countable_ball {ι : Type*} {S : set ι} (hS : S.countable) {p : Π (x : α) (i ∈ S), Prop} : (∀ᶠ x in l, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᶠ x in l, p x i ‹_› := by simpa only [filter.eventually, set_of_forall] using @countable_bInter_mem _ l _ _ _ hS (λ i hi, {x | p x i hi}) lemma eventually_le.countable_Union [countable ι] {s t : ι → set α} (h : ∀ i, s i ≤ᶠ[l] t i) : (⋃ i, s i) ≤ᶠ[l] ⋃ i, t i := (eventually_countable_forall.2 h).mono $ λ x hst hs, mem_Union.2 $ (mem_Union.1 hs).imp hst lemma eventually_eq.countable_Union [countable ι] {s t : ι → set α} (h : ∀ i, s i =ᶠ[l] t i) : (⋃ i, s i) =ᶠ[l] ⋃ i, t i := (eventually_le.countable_Union (λ i, (h i).le)).antisymm (eventually_le.countable_Union (λ i, (h i).symm.le)) lemma eventually_le.countable_bUnion {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› ≤ᶠ[l] t i ‹_›) : (⋃ i ∈ S, s i ‹_›) ≤ᶠ[l] ⋃ i ∈ S, t i ‹_› := begin simp only [bUnion_eq_Union], haveI := hS.to_encodable, exact eventually_le.countable_Union (λ i, h i i.2) end lemma eventually_eq.countable_bUnion {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› =ᶠ[l] t i ‹_›) : (⋃ i ∈ S, s i ‹_›) =ᶠ[l] ⋃ i ∈ S, t i ‹_› := (eventually_le.countable_bUnion hS (λ i hi, (h i hi).le)).antisymm (eventually_le.countable_bUnion hS (λ i hi, (h i hi).symm.le)) lemma eventually_le.countable_Inter [countable ι] {s t : ι → set α} (h : ∀ i, s i ≤ᶠ[l] t i) : (⋂ i, s i) ≤ᶠ[l] ⋂ i, t i := (eventually_countable_forall.2 h).mono $ λ x hst hs, mem_Inter.2 $ λ i, hst _ (mem_Inter.1 hs i) lemma eventually_eq.countable_Inter [countable ι] {s t : ι → set α} (h : ∀ i, s i =ᶠ[l] t i) : (⋂ i, s i) =ᶠ[l] ⋂ i, t i := (eventually_le.countable_Inter (λ i, (h i).le)).antisymm (eventually_le.countable_Inter (λ i, (h i).symm.le)) lemma eventually_le.countable_bInter {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› ≤ᶠ[l] t i ‹_›) : (⋂ i ∈ S, s i ‹_›) ≤ᶠ[l] ⋂ i ∈ S, t i ‹_› := begin simp only [bInter_eq_Inter], haveI := hS.to_encodable, exact eventually_le.countable_Inter (λ i, h i i.2) end lemma eventually_eq.countable_bInter {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› =ᶠ[l] t i ‹_›) : (⋂ i ∈ S, s i ‹_›) =ᶠ[l] ⋂ i ∈ S, t i ‹_› := (eventually_le.countable_bInter hS (λ i hi, (h i hi).le)).antisymm (eventually_le.countable_bInter hS (λ i hi, (h i hi).symm.le)) /-- Construct a filter with countable intersection property. This constructor deduces `filter.univ_sets` and `filter.inter_sets` from the countable intersection property. -/ def filter.of_countable_Inter (l : set (set α)) (hp : ∀ S : set (set α), S.countable → S ⊆ l → (⋂₀ S) ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) : filter α := { sets := l, univ_sets := @sInter_empty α ▸ hp _ countable_empty (empty_subset _), sets_of_superset := h_mono, inter_sets := λ s t hs ht, sInter_pair s t ▸ hp _ ((countable_singleton _).insert _) (insert_subset.2 ⟨hs, singleton_subset_iff.2 ht⟩) } instance filter.countable_Inter_of_countable_Inter (l : set (set α)) (hp : ∀ S : set (set α), S.countable → S ⊆ l → (⋂₀ S) ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) : countable_Inter_filter (filter.of_countable_Inter l hp h_mono) := ⟨hp⟩ @[simp] lemma filter.mem_of_countable_Inter {l : set (set α)} (hp : ∀ S : set (set α), S.countable → S ⊆ l → (⋂₀ S) ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) {s : set α} : s ∈ filter.of_countable_Inter l hp h_mono ↔ s ∈ l := iff.rfl instance countable_Inter_filter_principal (s : set α) : countable_Inter_filter (𝓟 s) := ⟨λ S hSc hS, subset_sInter hS⟩ instance countable_Inter_filter_bot : countable_Inter_filter (⊥ : filter α) := by { rw ← principal_empty, apply countable_Inter_filter_principal } instance countable_Inter_filter_top : countable_Inter_filter (⊤ : filter α) := by { rw ← principal_univ, apply countable_Inter_filter_principal } instance (l : filter β) [countable_Inter_filter l] (f : α → β) : countable_Inter_filter (comap f l) := begin refine ⟨λ S hSc hS, _⟩, choose! t htl ht using hS, have : (⋂ s ∈ S, t s) ∈ l, from (countable_bInter_mem hSc).2 htl, refine ⟨_, this, _⟩, simpa [preimage_Inter] using (Inter₂_mono ht) end instance (l : filter α) [countable_Inter_filter l] (f : α → β) : countable_Inter_filter (map f l) := begin constructor, intros S hSc hS, simp only [mem_map, sInter_eq_bInter, preimage_Inter₂] at hS ⊢, exact (countable_bInter_mem hSc).2 hS end /-- Infimum of two `countable_Inter_filter`s is a `countable_Inter_filter`. This is useful, e.g., to automatically get an instance for `residual α ⊓ 𝓟 s`. -/ instance countable_Inter_filter_inf (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊓ l₂) := begin refine ⟨λ S hSc hS, _⟩, choose s hs t ht hst using hS, replace hs : (⋂ i ∈ S, s i ‹_›) ∈ l₁ := (countable_bInter_mem hSc).2 hs, replace ht : (⋂ i ∈ S, t i ‹_›) ∈ l₂ := (countable_bInter_mem hSc).2 ht, refine mem_of_superset (inter_mem_inf hs ht) (subset_sInter $ λ i hi, _), rw hst i hi, apply inter_subset_inter ; exact Inter_subset_of_subset i (Inter_subset _ _) end /-- Supremum of two `countable_Inter_filter`s is a `countable_Inter_filter`. -/ instance countable_Inter_filter_sup (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊔ l₂) := begin refine ⟨λ S hSc hS, ⟨_, _⟩⟩; refine (countable_sInter_mem hSc).2 (λ s hs, _), exacts [(hS s hs).1, (hS s hs).2] end namespace filter variable (g : set (set α)) /-- `filter.countable_generate_sets g` is the (sets of the) greatest `countable_Inter_filter` containing `g`.-/ inductive countable_generate_sets : set α → Prop | basic {s : set α} : s ∈ g → countable_generate_sets s | univ : countable_generate_sets univ | superset {s t : set α} : countable_generate_sets s → s ⊆ t → countable_generate_sets t | Inter {S : set (set α)} : S.countable → (∀ s ∈ S, countable_generate_sets s) → countable_generate_sets ⋂₀ S /-- `filter.countable_generate g` is the greatest `countable_Inter_filter` containing `g`.-/ @[derive countable_Inter_filter] def countable_generate : filter α := of_countable_Inter (countable_generate_sets g) (λ S, countable_generate_sets.Inter) (λ s t, countable_generate_sets.superset) variable {g} /-- A set is in the `countable_Inter_filter` generated by `g` if and only if it contains a countable intersection of elements of `g`. -/ lemma mem_countable_generate_iff {s : set α} : s ∈ countable_generate g ↔ ∃ (S : set (set α)), S ⊆ g ∧ S.countable ∧ ⋂₀ S ⊆ s := begin split; intro h, { induction h with s hs s t hs st ih S Sct hS ih, { exact ⟨{s}, by simp[hs]⟩ }, { exact ⟨∅, by simp⟩ }, { refine exists_imp_exists (λ S, _) ih, tauto }, choose T Tg Tct hT using ih, refine ⟨⋃ s (H : s ∈ S), T s H, by simpa, Sct.bUnion Tct, _⟩, apply subset_sInter, intros s H, refine subset_trans (sInter_subset_sInter (subset_Union₂ s H)) (hT s H), }, rcases h with ⟨S, Sg, Sct, hS⟩, refine mem_of_superset ((countable_sInter_mem Sct).mpr _) hS, intros s H, exact countable_generate_sets.basic (Sg H), end lemma le_countable_generate_iff_of_countable_Inter_filter {f : filter α} [countable_Inter_filter f] : f ≤ countable_generate g ↔ g ⊆ f.sets := begin split; intro h, { exact subset_trans (λ s, countable_generate_sets.basic) h }, intros s hs, induction hs with s hs s t hs st ih S Sct hS ih, { exact h hs }, { exact univ_mem }, { exact mem_of_superset ih st, }, exact (countable_sInter_mem Sct).mpr ih, end variable (g) /-- `countable_generate g` is the greatest `countable_Inter_filter` containing `g`.-/ lemma countable_generate_is_greatest : is_greatest {f : filter α | countable_Inter_filter f ∧ g ⊆ f.sets} (countable_generate g) := begin refine ⟨⟨infer_instance, λ s, countable_generate_sets.basic⟩, _⟩, rintros f ⟨fct, hf⟩, rwa @le_countable_generate_iff_of_countable_Inter_filter _ _ _ fct, end end filter
2bb5887b6e4066d18238c3fd2a46f96b7c58fbf2
842b7df4a999c5c50bbd215b8617dd705e43c2e1
/nat_num_game/src/Advanced_Multiplication_World/adv_mul_wrld1.lean
18263b859367f5db4d400beaf835a4ee913796b9
[]
no_license
Samyak-Surti/LeanCode
1c245631f74b00057d20483c8ac75916e8643b14
944eac3e5f43e2614ed246083b97fbdf24181d83
refs/heads/master
1,669,023,730,828
1,595,534,784,000
1,595,534,784,000
282,037,186
0
0
null
null
null
null
UTF-8
Lean
false
false
316
lean
theorem mul_pos (a b : ℕ) : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := begin intros x y, cases a with n, rw nat.zero_mul, exact x, cases b with m, rw nat.succ_mul, rw nat.mul_zero, rw nat.zero_add, exact y, rw nat.succ_mul, rw nat.add_succ, apply nat.succ_ne_zero, end
c01051888625feb5844205f3ceffb26706f9ea80
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/discrete_valuation_ring.lean
1d6cc27d1c22dd5fb43b483f3249ac975b2fa390
[ "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
17,105
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import ring_theory.principal_ideal_domain import order.conditionally_complete_lattice import ring_theory.ideal.local_ring import ring_theory.multiplicity import ring_theory.valuation.basic import linear_algebra.adic_completion /-! # Discrete valuation rings This file defines discrete valuation rings (DVRs) and develops a basic interface for them. ## Important definitions There are various definitions of a DVR in the literature; we define a DVR to be a local PID which is not a field (the first definition in Wikipedia) and prove that this is equivalent to being a PID with a unique non-zero prime ideal (the definition in Serre's book "Local Fields"). Let R be an integral domain, assumed to be a principal ideal ring and a local ring. * `discrete_valuation_ring R` : a predicate expressing that R is a DVR ### Definitions * `add_val R : add_valuation R part_enat` : the additive valuation on a DVR. ## Implementation notes It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible. We do not hence define `uniformizer` at all, because we can use `irreducible` instead. ## Tags discrete valuation ring -/ open_locale classical universe u open ideal local_ring /-- An integral domain is a *discrete valuation ring* (DVR) if it's a local PID which is not a field. -/ class discrete_valuation_ring (R : Type u) [comm_ring R] [is_domain R] extends is_principal_ideal_ring R, local_ring R : Prop := (not_a_field' : maximal_ideal R ≠ ⊥) namespace discrete_valuation_ring variables (R : Type u) [comm_ring R] [is_domain R] [discrete_valuation_ring R] lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field' variable {R} open principal_ideal_ring /-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the maximal ideal of R -/ theorem irreducible_iff_uniformizer (ϖ : R) : irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} := ⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm, begin intro h, have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R, from h.symm ▸ submodule.mem_span_singleton_self ϖ, refine ⟨h2, _⟩, intros a b hab, by_contra' h, obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h, rw [h, mem_span_singleton'] at ha hb, rcases ha with ⟨a, rfl⟩, rcases hb with ⟨b, rfl⟩, rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab, have h3 := eq_zero_of_mul_eq_self_right _ hab.symm, { apply not_a_field R, simp [h, h3] }, { exact λ hh, h2 (is_unit_of_dvd_one ϖ ⟨_, hh.symm⟩) } end⟩ lemma _root_.irreducible.maximal_ideal_eq {ϖ : R} (h : irreducible ϖ) : maximal_ideal R = ideal.span {ϖ} := (irreducible_iff_uniformizer _).mp h variable (R) /-- Uniformisers exist in a DVR -/ theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ := by {simp_rw [irreducible_iff_uniformizer], exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal} /-- Uniformisers exist in a DVR -/ theorem exists_prime : ∃ ϖ : R, prime ϖ := (exists_irreducible R).imp (λ _, principal_ideal_ring.irreducible_iff_prime.1) /-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/ theorem iff_pid_with_one_nonzero_prime (R : Type u) [comm_ring R] [is_domain R] : discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P := begin split, { intro RDVR, rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩, split, assumption, resetI, use local_ring.maximal_ideal R, split, split, { assumption }, { apply_instance } , { rintro Q ⟨hQ1, hQ2⟩, obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1, have hq : q ≠ 0, { rintro rfl, apply hQ1, simp }, erw span_singleton_prime hq at hQ2, replace hQ2 := hQ2.irreducible, rw irreducible_iff_uniformizer at hQ2, exact hQ2.symm } }, { rintro ⟨RPID, Punique⟩, haveI : local_ring R := local_ring.of_unique_nonzero_prime Punique, refine {not_a_field' := _}, rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩, have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1), intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM } end lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) : associated a b := begin rw irreducible_iff_uniformizer at ha hb, rw [←span_singleton_eq_span_singleton, ←ha, hb], end end discrete_valuation_ring namespace discrete_valuation_ring variable (R : Type*) /-- Alternative characterisation of discrete valuation rings. -/ def has_unit_mul_pow_irreducible_factorization [comm_ring R] : Prop := ∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x namespace has_unit_mul_pow_irreducible_factorization variables {R} [comm_ring R] (hR : has_unit_mul_pow_irreducible_factorization R) include hR lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin rcases hR with ⟨ϖ, hϖ, hR⟩, suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ, { apply associated.trans (this hp) (this hq).symm, }, clear hp hq p q, intros p hp, obtain ⟨n, hn⟩ := hR hp.ne_zero, have : irreducible (ϖ ^ n) := hn.symm.irreducible hp, rcases lt_trichotomy n 1 with (H|rfl|H), { obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial }, simpa only [not_irreducible_one, pow_zero] using this, }, { simpa only [pow_one] using hn.symm, }, { obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H, rw pow_succ at this, rcases this.is_unit_or_is_unit rfl with H0|H0, { exact (hϖ.not_unit H0).elim, }, { rw [add_comm, pow_succ] at H0, exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } } end variables [is_domain R] /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a unique factorization domain. See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/ theorem to_unique_factorization_monoid : unique_factorization_monoid R := let p := classical.some hR in let spec := classical.some_spec hR in unique_factorization_monoid.of_exists_prime_factors $ λ x hx, begin use multiset.repeat p (classical.some (spec.2 hx)), split, { intros q hq, have hpq := multiset.eq_of_mem_repeat hq, rw hpq, refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩, intros a b h, by_cases ha : a = 0, { rw ha, simp only [true_or, dvd_zero], }, obtain ⟨m, u, rfl⟩ := spec.2 ha, rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (units.is_unit _)] at h, rw is_unit.dvd_mul_right (units.is_unit _), by_cases hm : m = 0, { simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h }, left, obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm, rw pow_succ, apply dvd_mul_of_dvd_left dvd_rfl _ }, { rw [multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), } end omit hR lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : has_unit_mul_pow_irreducible_factorization R := begin obtain ⟨p, hp⟩ := h₁, refine ⟨p, hp, _⟩, intros x hx, cases wf_dvd_monoid.exists_factors x hx with fx hfx, refine ⟨fx.card, _⟩, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, symmetry, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ q hq rfl, rw associates.mk_eq_mk_iff_associated, apply h₂ (hfx.1 _ hq) hp, end end has_unit_mul_pow_irreducible_factorization lemma aux_pid_of_ufd_of_unique_irreducible (R : Type u) [comm_ring R] [is_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : is_principal_ideal_ring R := begin constructor, intro I, by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], }, obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0, obtain ⟨p, hp, H⟩ := has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂, have ex : ∃ n : ℕ, p ^ n ∈ I, { obtain ⟨n, u, rfl⟩ := H hx0, refine ⟨n, _⟩, simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hxI, }, constructor, use p ^ (nat.find ex), show I = ideal.span _, apply le_antisymm, { intros r hr, by_cases hr0 : r = 0, { simp only [hr0, submodule.zero_mem], }, obtain ⟨n, u, rfl⟩ := H hr0, simp only [mem_span_singleton, units.is_unit, is_unit.dvd_mul_right], apply pow_dvd_pow, apply nat.find_min', simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hr, }, { erw submodule.span_singleton_le_iff_mem, exact nat.find_spec ex, }, end /-- A unique factorization domain with at least one irreducible element in which all irreducible elements are associated is a discrete valuation ring. -/ lemma of_ufd_of_unique_irreducible {R : Type u} [comm_ring R] [is_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : discrete_valuation_ring R := begin rw iff_pid_with_one_nonzero_prime, haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂, obtain ⟨p, hp⟩ := h₁, refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩, { rw submodule.ne_bot_iff, refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, }, { rwa [ideal.span_singleton_prime hp.ne_zero, ← unique_factorization_monoid.irreducible_iff_prime], }, { intro I, rw ← submodule.is_principal.span_singleton_generator I, rintro ⟨I0, hI⟩, apply span_singleton_eq_span_singleton.mpr, apply h₂ _ hp, erw [ne.def, span_singleton_eq_bot] at I0, rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0], apply_instance, }, end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a discrete valuation ring. -/ lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [comm_ring R] [is_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) : discrete_valuation_ring R := begin letI : unique_factorization_monoid R := hR.to_unique_factorization_monoid, apply of_ufd_of_unique_irreducible _ hR.unique_irreducible, unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, }, end section variables [comm_ring R] [is_domain R] [discrete_valuation_ring R] variable {R} lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ), associated x (ϖ ^ n) := begin have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid, cases wf_dvd_monoid.exists_factors x hx with fx hfx, unfreezingI { use fx.card }, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ _ _ rfl, rw associates.mk_eq_mk_iff_associated, refine associated_of_irreducible _ _ hirr, apply hfx.1, assumption end lemma eq_unit_mul_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ) (u : Rˣ), x = u * ϖ ^ n := begin obtain ⟨n, hn⟩ := associated_pow_irreducible hx hirr, obtain ⟨u, rfl⟩ := hn.symm, use [n, u], apply mul_comm, end open submodule.is_principal lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) : ∃ n : ℕ, s = ideal.span {ϖ ^ n} := begin have gen_ne_zero : generator s ≠ 0, { rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption }, rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩, use n, have : span _ = _ := span_singleton_generator s, rw [← this, ← hnu, span_singleton_eq_span_singleton], use u end lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q) (u v : Rˣ) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) : m = n := begin have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod, { rw [multiset.prod_repeat, multiset.prod_repeat, associated], refine ⟨u * v⁻¹, _⟩, simp only [units.coe_mul], rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], }, have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key), { simpa only [multiset.card_repeat] }, all_goals { intros x hx, unfreezingI { obtain rfl := multiset.eq_of_mem_repeat hx, assumption } }, end lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : Rˣ) (m n : ℕ) (h : ↑u * ϖ ^ m = v * ϖ ^ n) : u = v := begin obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h, rw ← sub_eq_zero at h, rw [← sub_mul, mul_eq_zero] at h, cases h, { rw sub_eq_zero at h, exact_mod_cast h }, { apply (hirr.ne_zero (pow_eq_zero h)).elim, } end /-! ## The additive valuation on a DVR -/ open multiplicity /-- The `part_enat`-valued additive valuation on a DVR -/ noncomputable def add_val (R : Type u) [comm_ring R] [is_domain R] [discrete_valuation_ring R] : add_valuation R part_enat := add_valuation (classical.some_spec (exists_prime R)) lemma add_val_def (r : R) (u : Rˣ) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) (hr : r = u * ϖ ^ n) : add_val R r = n := by rw [add_val, add_valuation_apply, hr, eq_of_associated_left (associated_of_irreducible R hϖ (classical.some_spec (exists_prime R)).irreducible), eq_of_associated_right (associated.symm ⟨u, mul_comm _ _⟩), multiplicity_pow_self_of_prime (principal_ideal_ring.irreducible_iff_prime.1 hϖ)] lemma add_val_def' (u : Rˣ) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) : add_val R ((u : R) * ϖ ^ n) = n := add_val_def _ u hϖ n rfl @[simp] lemma add_val_zero : add_val R 0 = ⊤ := (add_val R).map_zero @[simp] lemma add_val_one : add_val R 1 = 0 := (add_val R).map_one @[simp] lemma add_val_uniformizer {ϖ : R} (hϖ : irreducible ϖ) : add_val R ϖ = 1 := by simpa only [one_mul, eq_self_iff_true, units.coe_one, pow_one, forall_true_left, nat.cast_one] using add_val_def ϖ 1 hϖ 1 @[simp] lemma add_val_mul {a b : R} : add_val R (a * b) = add_val R a + add_val R b := (add_val R).map_mul _ _ lemma add_val_pow (a : R) (n : ℕ) : add_val R (a ^ n) = n • add_val R a := (add_val R).map_pow _ _ lemma _root_.irreducible.add_val_pow {ϖ : R} (h : irreducible ϖ) (n : ℕ) : add_val R (ϖ ^ n) = n := by rw [add_val_pow, add_val_uniformizer h, nsmul_one] lemma add_val_eq_top_iff {a : R} : add_val R a = ⊤ ↔ a = 0 := begin have hi := (classical.some_spec (exists_prime R)).irreducible, split, { contrapose, intro h, obtain ⟨n, ha⟩ := associated_pow_irreducible h hi, obtain ⟨u, rfl⟩ := ha.symm, rw [mul_comm, add_val_def' u hi n], exact part_enat.coe_ne_top _ }, { rintro rfl, exact add_val_zero } end lemma add_val_le_iff_dvd {a b : R} : add_val R a ≤ add_val R b ↔ a ∣ b := begin have hp := classical.some_spec (exists_prime R), split; intro h, { by_cases ha0 : a = 0, { rw [ha0, add_val_zero, top_le_iff, add_val_eq_top_iff] at h, rw h, apply dvd_zero }, obtain ⟨n, ha⟩ := associated_pow_irreducible ha0 hp.irreducible, rw [add_val, add_valuation_apply, add_valuation_apply, multiplicity_le_multiplicity_iff] at h, exact ha.dvd.trans (h n ha.symm.dvd), }, { rw [add_val, add_valuation_apply, add_valuation_apply], exact multiplicity_le_multiplicity_of_dvd_right h } end lemma add_val_add {a b : R} : min (add_val R a) (add_val R b) ≤ add_val R (a + b) := (add_val R).map_add _ _ end instance (R : Type*) [comm_ring R] [is_domain R] [discrete_valuation_ring R] : is_Hausdorff (maximal_ideal R) R := { haus' := λ x hx, begin obtain ⟨ϖ, hϖ⟩ := exists_irreducible R, simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.zero, hϖ.maximal_ideal_eq, ideal.span_singleton_pow, ideal.mem_span_singleton, ← add_val_le_iff_dvd, hϖ.add_val_pow] at hx, rwa [← add_val_eq_top_iff, part_enat.eq_top_iff_forall_le], end } end discrete_valuation_ring
4781dca9982fe31dcf990bddc75ef0b77e8342e8
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/pi_instances.lean
7e3a46f3a404f43022b29f2ee0239b54404f9971
[ "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
1,810
lean
/- Copyright (c) 2018 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Automation for creating instances of mathematical structures for pi types -/ import tactic.interactive order.basic namespace tactic open interactive interactive.types lean.parser expr open functor has_seq list nat tactic.interactive meta def derive_field : tactic unit := do b ← target >>= is_prop, field ← get_current_field, if b then do field ← get_current_field, vs ← introv [] <|> pure [], hs ← intros <|> pure [], resetI, x ← get_unused_name, try (() <$ ext1 [rcases_patt.one x] <|> () <$ intro x), x' ← try_core (get_local x), applyc field, hs.mmap (λ h, try $ () <$ (to_expr ``(congr_fun %%h %%(x'.iget)) >>= apply) <|> () <$ apply (h x'.iget) <|> () <$ (to_expr ``(set.mem_image_of_mem _ %%h) >>= apply) <|> () <$ (solve_by_elim) ), return () else focus1 $ do field ← get_current_field, e ← mk_const field, expl_arity ← get_expl_arity e, xs ← (iota expl_arity).mmap $ λ _, intro1, x ← intro1, applyc field, xs.mmap' (λ h, try $ () <$ (apply (h x) <|> apply h) <|> refine ``(set.image ($ %%x) %%h)) <|> fail "args", return () /-- `pi_instance` constructs an instance of `my_class (Π i : I, f i)` where we know `Π i, my_class (f i)`. If an order relation is required, it defaults to `pi.partial_order`. Any field of the instance that `pi_instance` cannot construct is left untouched and generated as a new goal. -/ meta def pi_instance : tactic unit := refine_struct ``( { ..pi.partial_order, .. } ); propagate_tags (try (derive_field ; done)) run_cmd add_interactive [`pi_instance] end tactic
f8d0932dfc96890a860eb61e6cbf79833315ac79
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/not_in_use/accelerationEval.lean
8a5a7d28ce0878d388db16bc386f78512c59cd69
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
1,094
lean
import ..imperative_DSL.environment import .geometryEval import .timeEval open lang.classicalAcceleration def classicalAccelerationEval : lang.classicalAcceleration.expr → environment.env → classicalAcceleration | (expr.lit v) i := v | (lang.classicalAcceleration.expr.var v) i := i.a v | (expr.div v t) i := match v with | (lang.classicalVelocity.expr.lit e) := match t with | (lang.classicalTime.expr.lit e2) := classicalAcceleration.mk 0 e e2 | (lang.classicalTime.expr.var v2) := classicalAcceleration.mk 0 (e) (i.t v2) end | (lang.classicalVelocity.expr.var v) := match t with | (lang.classicalTime.expr.lit e2) := classicalAcceleration.mk 0 (i.v v) (e2) | (lang.classicalTime.expr.var v2) := classicalAcceleration.mk 0 (i.v v) (i.t v2) end | (lang.classicalVelocity.expr.div g t) := let G := classicalGeometryEval g i in let T := classicalTimeEval t i in classicalAcceleration.mk 0 (classicalVelocity.mk 0 G T) T end
dc271f0226898503ec4c12593cb78481ec55d89f
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Init/Data/Array/Basic.lean
6ee1012d1e01251621eb6664b1650faac691c2fa
[ "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
27,408
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Util universes u v w namespace Array variable {α : Type u} @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { data := List.replicate n v } theorem sizeMkArrayEq (n : Nat) (v : α) : (mkArray n v).size = n := List.lengthReplicateEq .. instance : EmptyCollection (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) where default := Array.empty def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def back? (a : Array α) : Option α := a.get? (a.size - 1) -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ theorem sizeSetEq (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := List.lengthSetEq .. theorem sizePushEq (a : Array α) (v : α) : (push a v).size = a.size + 1 := List.lengthConcatEq .. /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i let v₂ := a.get j let a' := a.set i v₂ a'.set (sizeSetEq a i v₂ ▸ j) v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i let a := a.set i v (e, a) @[inline] def swapAt! (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else have Inhabited α from ⟨v⟩ panic! ("index " ++ toString i ++ " out of bounds") @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { data := a.data.dropLast } def shrink (a : Array α) (n : Nat) : Array α := let rec loop | 0, a => a | n+1, a => loop n a.pop loop (a.size - n) a @[inline] def modifyM [Monad m] [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := do if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩ let v := a.get idx let a' := a.set idx arbitrary let v ← f v pure <| a'.set (sizeSetEq a .. ▸ idx) v else pure a @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run <| a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/ @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b -- Move? private theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b | 0, _, h => h | a+1, b, h => have a < b from Nat.ltTrans (Nat.ltSuccSelf _) h zeroLtOfLt this /- Reference implementation for `forIn` -/ @[implementedBy Array.forInUnsafe] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! : 0 < 1) have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b instance : ForIn m (Array α) α where forIn := Array.forIn /- See comment at forInUnsafe -/ @[inline] unsafe def foldlMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.leRefl _) /- See comment at forInUnsafe -/ @[inline] unsafe def foldrMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i-1) stop (← f (as.uget (i-1) lcProof) b) if start ≤ as.size then if stop < start then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else if stop < as.size then fold (USize.ofNat as.size) (USize.ofNat stop) init else pure init /- Reference implementation for `foldrM` -/ @[implementedBy foldrMUnsafe] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec fold (i : Nat) (h : i ≤ as.size) (b : β) : m β := do if i == stop then pure b else match i, h with | 0, _ => pure b | i+1, h => have i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h fold i (Nat.leOfLt this) (← f (as.get ⟨i, this⟩) b) if h : start ≤ as.size then if stop < start then fold start h init else pure init else if stop < as.size then fold as.size (Nat.leRefl _) init else pure init /- See comment at forInUnsafe -/ @[inline] unsafe def mapMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := let sz := USize.ofNat as.size let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do if i < sz then let v := r.uget i lcProof let r := r.uset i arbitrary lcProof let vNew ← f (unsafeCast v) map (i+1) (r.uset i (unsafeCast vNew) lcProof) else pure (unsafeCast r) unsafeCast <| map 0 (unsafeCast as) /- Reference implementation for `mapM` -/ @[implementedBy mapMUnsafe] def mapM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do let b ← f a; pure (bs.push b)) (mkEmpty as.size) @[inline] def mapIdxM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : Fin as.size → α → m β) : m (Array β) := let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array β) : m (Array β) := do match i, inv with | 0, _ => pure bs | i+1, inv => have j < as.size by rw [← inv, Nat.addAssoc, Nat.addComm 1 j, Nat.addLeftComm]; apply Nat.leAddRight let idx : Fin as.size := ⟨j, this⟩ have i + (j + 1) = as.size by rw [← inv, Nat.addComm j 1, Nat.addAssoc] map i (j+1) this (bs.push (← f idx (as.get idx))) map as.size 0 rfl (mkEmpty as.size) @[inline] def findSomeM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := do for a in as do match (← f a) with | some b => return b | _ => pure ⟨⟩ return none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := do for a in as do if (← p a) then return a return none @[inline] def findIdxM? [Monad m] (as : Array α) (p : α → m Bool) : m (Option Nat) := do let mut i := 0 for a in as do if (← p a) then return some i i := i + 1 return none @[inline] unsafe def anyMUnsafe {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do if i == stop then pure false else if (← p (as.uget i lcProof)) then pure true else any (i+1) stop if start < stop then if stop ≤ as.size then any (USize.ofNat start) (USize.ofNat stop) else pure false else pure false @[implementedBy anyMUnsafe] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let any (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) : m Bool := do if hlt : j < stop then match i with | 0 => pure false | i'+1 => if (← p (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) then pure true else loop i' (j+1) else pure false loop (stop - start) start if h : stop ≤ as.size then any stop h else any as.size (Nat.leRefl _) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := return !(← as.anyM fun v => return !(← p v)) @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, h => pure none | i+1, h => do have i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h let r ← f (as.get ⟨i, this⟩) match r with | some v => pure r | none => have i ≤ as.size from Nat.leOfLt this find i this find as.size (Nat.leRefl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := 0) (stop := as.size) : m PUnit := as.foldlM (fun _ => f) ⟨⟩ start stop @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := as.size) (stop := 0) : m PUnit := as.foldrM (fun a _ => f a) ⟨⟩ start stop @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Array α) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Array α) (start := as.size) (stop := 0) : β := Id.run <| as.foldrM f init start stop @[inline] def map {α : Type u} {β : Type v} (f : α → β) (as : Array α) : Array β := Id.run <| as.mapM f @[inline] def mapIdx {α : Type u} {β : Type v} (as : Array α) (f : Fin as.size → α → β) : Array β := Id.run <| as.mapIdxM f @[inline] def find? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findM? p @[inline] def findSome? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeM? f @[inline] def findSome! {α : Type u} {β : Type v} [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeRevM? f @[inline] def findRev? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p @[inline] def findIdx? {α : Type u} (as : Array α) (p : α → Bool) : Option Nat := let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat := if hlt : j < as.size then match i, inv with | 0, inv => by apply False.elim rw [Nat.zeroAdd] at inv rw [inv] at hlt exact absurd hlt (Nat.ltIrrefl _) | i+1, inv => if p (as.get ⟨j, hlt⟩) then some j else have i + (j+1) = as.size by rw [← inv, Nat.addComm j 1, Nat.addAssoc] loop i (j+1) this else none loop as.size 0 rfl def getIdx? [BEq α] (a : Array α) (v : α) : Option Nat := a.findIdx? fun a => a == v @[inline] def any (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.anyM p start stop @[inline] def all (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.allM p start stop def contains [BEq α] (as : Array α) (a : α) : Bool := as.any fun b => a == b def elem [BEq α] (a : α) (as : Array α) : Bool := as.contains a -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverse (as : Array α) : Array α := let n := as.size let mid := n / 2 let rec rev (as : Array α) (i : Nat) := if i < mid then rev (as.swap! i (n - i - 1)) (i+1) else as rev as 0 @[inline] def getEvenElems (as : Array α) : Array α := (·.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a => if even then (false, r.push a) else (true, r) @[export lean_array_to_list] def toList (as : Array α) : List α := as.foldr List.cons [] instance {α : Type u} [Repr α] : Repr (Array α) where reprPrec a _ := if a.size == 0 then "#[]" else Std.Format.bracketFill "#[" (@Std.Format.joinSep _ ⟨repr⟩ (toList a) ("," ++ Std.Format.line)) "]" instance [ToString α] : ToString (Array α) where toString a := "#" ++ toString a.toList protected def append (as : Array α) (bs : Array α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : Append (Array α) := ⟨Array.append⟩ @[inline] def concatMapM [Monad m] (f : α → m (Array β)) (as : Array α) : m (Array β) := as.foldlM (init := empty) fun bs a => do return bs ++ (← f a) @[inline] def concatMap (f : α → Array β) (as : Array α) : Array β := as.foldl (init := empty) fun bs a => bs ++ f a end Array @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | [], r => r | a::as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | [] => 0 | _::as => as.redLength + 1 @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) export Array (mkArray) syntax "#[" sepBy(term, ", ") "]" : term macro_rules | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ]) namespace Array -- TODO(Leo): cleanup @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [BEq α] : BEq (Array α) := ⟨fun a b => isEqv a b BEq.beq⟩ @[inline] def filter (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Array α := as.foldl (init := #[]) (start := start) (stop := stop) fun r a => if p a then r.push a else r @[inline] def filterM [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m (Array α) := as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do if (← p a) then r.push a else r @[specialize] def filterMapM [Monad m] (f : α → m (Option β)) (as : Array α) (start := 0) (stop := as.size) : m (Array β) := as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do match (← f a) with | some b => pure (bs.push b) | none => pure bs @[inline] def filterMap (f : α → Option β) (as : Array α) (start := 0) (stop := as.size) : Array β := Id.run <| as.filterMapM f (start := start) (stop := stop) @[specialize] def getMax? (as : Array α) (lt : α → α → Bool) : Option α := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩ some <| as.foldl (init := a0) (start := 1) fun best a => if lt best a then a else best else none @[inline] def partition (p : α → Bool) (as : Array α) : Array α × Array α := do let mut bs := #[] let mut cs := #[] for a in as do if p a then bs := bs.push a else cs := cs.push a return (bs, cs) theorem ext (a b : Array α) (h₁ : a.size = b.size) (h₂ : (i : Nat) → (hi₁ : i < a.size) → (hi₂ : i < b.size) → a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) : a = b := by let rec extAux (a b : List α) (h₁ : a.length = b.length) (h₂ : (i : Nat) → (hi₁ : i < a.length) → (hi₂ : i < b.length) → a.get i hi₁ = b.get i hi₂) : a = b := by induction a generalizing b with | nil => cases b with | nil => rfl | cons b bs => rw [List.lengthConsEq] at h₁; injection h₁ | cons a as ih => cases b with | nil => rw [List.lengthConsEq] at h₁; injection h₁ | cons b bs => have hz₁ : 0 < (a::as).length by rw [List.lengthConsEq]; apply Nat.zeroLtSucc have hz₂ : 0 < (b::bs).length by rw [List.lengthConsEq]; apply Nat.zeroLtSucc have headEq : a = b from h₂ 0 hz₁ hz₂ have h₁' : as.length = bs.length by rw [List.lengthConsEq, List.lengthConsEq] at h₁; injection h₁; assumption have h₂' : (i : Nat) → (hi₁ : i < as.length) → (hi₂ : i < bs.length) → as.get i hi₁ = bs.get i hi₂ by intro i hi₁ hi₂ have hi₁' : i+1 < (a::as).length by rw [List.lengthConsEq]; apply Nat.succLtSucc; assumption have hi₂' : i+1 < (b::bs).length by rw [List.lengthConsEq]; apply Nat.succLtSucc; assumption have (a::as).get (i+1) hi₁' = (b::bs).get (i+1) hi₂' from h₂ (i+1) hi₁' hi₂' apply this have tailEq : as = bs from ih bs h₁' h₂' rw [headEq, tailEq] cases a; cases b apply congrArg apply extAux assumption assumption theorem extLit {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : (i : Nat) → (hi : i < n) → a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array -- CLEANUP the following code namespace Array partial def indexOfAux [BEq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux a v (i+1) else none def indexOf? [BEq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a theorem sizeSwapEq (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := by show ((a.set i (a.get j)).set (sizeSetEq a i _ ▸ j) (a.get i)).size = a.size rw [sizeSetEq, sizeSetEq] theorem sizePopEq (a : Array α) : a.pop.size = a.size - 1 := List.lengthDropLast .. section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } where default := ⟨a.pop, sizePopEq a⟩ partial def eraseIdxSzAux (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux a (i+1) (r.swap idx idx1) ((sizeSwapEq r idx idx1).trans heq) else ⟨r.pop, (sizePopEq r).trans (heq ▸ rfl)⟩ end def eraseIdx' (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def erase [BEq α] (as : Array α) (a : α) : Array α := match as.indexOf? a with | none => as | some i => as.feraseIdx i partial def insertAtAux (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux i as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size def toListLitAux (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc) def toArrayLit (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray <| toListLitAux a n hsz n (hsz ▸ Nat.leRefl _) [] theorem toArrayLitEq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove ∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List α) (hi : 0 ≤ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List α) (hi : i+1 ≤ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have ∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ [] -/ partial def isPrefixOfAux [BEq α] (as bs : Array α) (hle : as.size ≤ bs.size) : Nat → Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.ltOfLtOfLe h hle⟩; if a == b then isPrefixOfAux as bs hle (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf [BEq α] (as bs : Array α) : Bool := if h : as.size ≤ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux [BEq α] (as : Array α) (a : α) : forall (i : Nat), i < as.size → Bool | 0, h => true | i+1, h => have i < as.size from Nat.ltTrans (Nat.ltSuccSelf _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux as a i this private partial def allDiffAux [BEq α] (as : Array α) : Nat → Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux as (i+1) else true def allDiff [BEq α] (as : Array α) : Bool := allDiffAux as 0 @[specialize] partial def zipWithAux (f : α → β → γ) (as : Array α) (bs : Array β) : Nat → Array γ → Array γ | i, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; if h : i < bs.size then let b := bs.get ⟨i, h⟩; zipWithAux f as bs (i+1) <| cs.push <| f a b else cs else cs @[inline] def zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : Array γ := zipWithAux f as bs 0 #[] def zip (as : Array α) (bs : Array β) : Array (α × β) := zipWith as bs Prod.mk end Array