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
26b84fda8e517193ed45f454d5895c09def96ab1
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/abstract_expr3.lean
f5e132f5866bdef61a841f25df6a49bb32d7681a
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
658
lean
universes l1 l2 constants (X : Type.{l1}) (P : X → Type.{l2}) (P_ss : ∀ x, subsingleton (P x)) constants (x1 x2 : X) (px1a px1b : P x1) (px2a px2b : P x2) attribute P_ss [instance] constants (f : Π (x1 x2 : X), P x1 → P x2 → Prop) #abstract_expr 0 f #abstract_expr 0 f x1 #abstract_expr 0 f x1 x2 #abstract_expr 0 f x1 x2 px1a #abstract_expr 0 f x1 x2 px1b #abstract_expr 0 f x1 x2 px1a px2a #abstract_expr 0 f x1 x2 px1a px2b #abstract_expr 1 f x1 x2, f x2 x1 #abstract_expr 1 f x1 x2, f x1 x2 px1a #abstract_expr 1 f x1 x2 px1a, f x1 x2 px1b #abstract_expr 1 f x1 x2 px1a px2a, f x1 x2 px1b #abstract_expr 1 f x1 x2 px1a px2a, f x1 x2 px1b px2b
4e57f7a383b7cca4080bc8e480cc8aabd77ff4d7
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/order/complete_lattice.lean
5bdb1f7e0644be36abc9d836e3ed3c1cb765f6db
[ "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
34,145
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 Theory of complete lattices. -/ import order.bounded_lattice data.set.basic tactic.pi_instances set_option old_structure_cmd true open set namespace lattice universes u v w w₂ variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} /-- class for the `Sup` operator -/ class has_Sup (α : Type u) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type u) := (Inf : set α → α) /-- Supremum of a set -/ def Sup [has_Sup α] : set α → α := has_Sup.Sup /-- Infimum of a set -/ def Inf [has_Inf α] : set α → α := has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] (s : ι → α) : α := Inf (range s) def has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ def has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type u) extends complete_lattice α, decidable_linear_order α section variables [complete_lattice α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha) theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha) @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume : Sup s ≤ a, assume b, assume : b ∈ s, le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›, Sup_le⟩ @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume : a ≤ Inf s, assume b, assume : b ∈ s, le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›), le_Inf⟩ -- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`? theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s := by have := le_Sup h; finish --Inf_le_of_le h (le_Sup h) -- TODO: it is weird that we have to add union_def theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := le_antisymm (by finish) (sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _)) /- old proof: le_antisymm (Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup)) (sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _)) -/ theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := le_antisymm (le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _)) (by finish) /- old proof: le_antisymm (le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _)) (le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le)) -/ theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := by finish /- le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t)) -/ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := le_antisymm (by finish) (by finish) -- le_antisymm (Sup_le (assume _, false.elim)) bot_le @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := le_antisymm (by finish) (by finish) --le_antisymm le_top (le_Inf (assume _, false.elim)) @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤ --le_antisymm le_top (le_Sup ⟨⟩) @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := le_antisymm (Inf_le ⟨⟩) bot_le -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := have Sup {b | b = a} = a, from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl), calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union ... = a ⊔ Sup s : by rw [this] @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := have Inf {b | b = a} = a, from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _), calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union ... = a ⊓ Inf s : by rw [this] @[simp] theorem Sup_singleton {a : α} : Sup {a} = a := by finish [singleton_def] --eq.trans Sup_insert $ by simp @[simp] theorem Inf_singleton {a : α} : Inf {a} = a := by finish [singleton_def] --eq.trans Inf_insert $ by simp @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := iff.intro (assume h a ha, bot_unique $ h ▸ le_Sup ha) (assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha) end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := iff.intro (assume : Inf s < b, classical.by_contradiction $ assume : ¬ (∃a∈s, a < b), have b ≤ Inf s, from le_Inf $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩, lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›)) (assume ⟨a, ha, h⟩, lt_of_le_of_lt (Inf_le ha) h) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := iff.intro (assume : b < Sup s, classical.by_contradiction $ assume : ¬ (∃a∈s, b < a), have Sup s ≤ b, from Sup_le $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩, lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›)) (assume ⟨a, ha, h⟩, lt_of_lt_of_le h $ le_Sup ha) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := iff.intro (assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb) (assume h, bot_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha)) lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) := iff.trans lt_Sup_iff $ iff.intro (assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩) (assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩) lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) := iff.trans Inf_lt_iff $ iff.intro (assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩) (assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩) end complete_linear_order /- supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := ⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩ -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type u} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin unfold supr, apply congr_arg, ext, simp, split, exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩, exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩ end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ /- I wanted to see if this would help for infi_comm; it doesn't. @[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂) : (: ⨅ i j, s i j :) ≤ (: s i j :) := begin transitivity, apply (infi_le (λ i, ⨅ j, s i j) i), apply infi_le end -/ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ @[congr] theorem infi_congr_Prop {α : Type u} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := begin unfold infi, apply congr_arg, ext, simp, split, exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩, exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩ end @[simp] theorem infi_const {a : α} : ∀[nonempty ι], (⨅ b:ι, a) = a | ⟨i⟩ := le_antisymm (Inf_le ⟨i, rfl⟩) (by finish) @[simp] theorem supr_const {a : α} : ∀[nonempty ι], (⨆ b:ι, a) = a | ⟨i⟩ := le_antisymm (by finish) (le_Sup ⟨i, rfl⟩) @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := bot_unique $ supr_le $ assume i, le_refl _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := iff.intro (assume eq i, top_unique $ eq ▸ infi_le _ _) (assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i) @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := iff.intro (assume eq i, bot_unique $ eq ▸ le_supr _ _) (assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i) @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := by rw [supr_eq_dif, dif_eq_if] lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := by by_cases p; simp [h] lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := by rw [infi_eq_dif, dif_eq_if] -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := le_antisymm (supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i) (supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j) @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) attribute [ematch] le_refl theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) (inf_le_right_of_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := le_antisymm (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right)) lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf i]; simp [inf_comm] lemma binfi_inf {ι : Sort*} {p : ι → Prop} {f : Πi, p i → α} {a : α} {i : ι} (hi : p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left) (infi_le_of_le i $ infi_le_of_le hi $ inf_le_right)) theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := le_antisymm (supr_le $ assume i, sup_le (le_sup_left_of_le $ le_supr _ _) (le_sup_right_of_le $ le_supr _ _)) (sup_le (supr_le $ assume i, le_supr_of_le i le_sup_left) (supr_le $ assume i, le_supr_of_le i le_sup_right)) /- supr and infi under Prop -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := le_antisymm (supr_le $ assume s, match s with | or.inl i := le_sup_left_of_le $ le_supr _ i | or.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩)) theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := le_antisymm (le_infi $ assume b, le_infi $ assume h, Inf_le h) (le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h) theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_range {α : Type u} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type u} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := le_antisymm (le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _)) (le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i) theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi ... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm] ... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm] ... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr ... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm] ... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm] ... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left] /- supr and infi under set constructions -/ /- should work using the simplifier! -/ @[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := le_antisymm le_top (le_infi $ assume x, le_infi false.elim) @[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le @[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x, from congr_arg infi $ funext $ assume x, infi_const @[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x, from congr_arg supr $ funext $ assume x, supr_const @[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or ... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left @[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := by rw [(union_eq_self_of_subset_left h).symm, supr_union]; exact le_sup_left @[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl @[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left @[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left @[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := show (⨅ x ∈ insert b (∅ : set β), f x) = f b, by simp @[simp] theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by { rw [show {a, b} = (insert b {a} : set β), from rfl, infi_insert, inf_comm], simp } @[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := show (⨆ x ∈ insert b (∅ : set β), f x) = f b, by simp @[simp] theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by { rw [show {a, b} = (insert b {a} : set β), from rfl, supr_insert, sup_comm], simp } lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := le_antisymm (le_infi $ assume b, le_infi $ assume hbt, infi_le_of_le (f b) $ infi_le (λ_, g (f b)) (mem_image_of_mem f hbt)) (le_infi $ assume c, le_infi $ assume ⟨b, hbt, eq⟩, eq ▸ infi_le_of_le b $ infi_le (λ_, g (f b)) hbt) lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := le_antisymm (supr_le $ assume c, supr_le $ assume ⟨b, hbt, eq⟩, eq ▸ le_supr_of_le b $ le_supr (λ_, g (f b)) hbt) (supr_le $ assume b, supr_le $ assume hbt, le_supr_of_le (f b) $ le_supr (λ_, g (f b)) (mem_image_of_mem f hbt)) /- supr and infi under Type -/ @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i) @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le @[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := le_antisymm (le_inf (infi_le _ _) (infi_le _ _)) (le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end) theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := le_antisymm (supr_le $ assume s, match s with | sum.inl i := le_sup_left_of_le $ le_supr _ i | sum.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩)) end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by rw [← Sup_range, Sup_eq_top]; from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff)) lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, b > f i) := by rw [← Inf_range, Inf_eq_bot]; from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff)) end complete_linear_order /- Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, ..lattice.bounded_lattice_Prop } lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (assume ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (assume ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := by { pi_instance; { intros, intro, apply_field, intros, simp at H, rcases H with ⟨ x, H₀, H₁ ⟩, subst b, apply a_1 _ H₀ i, } } lemma Inf_apply {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅f∈s, (f : Πa, β a) a) := by rw [← Inf_image]; refl lemma infi_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by erw [← Inf_range, Inf_apply, infi_range] lemma Sup_apply {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f∈s, (f : Πa, β a) a) := by rw [← Sup_image]; refl lemma supr_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := by erw [← Sup_range, Sup_apply, supr_range] section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h end complete_lattice section ord_continuous open lattice variables [complete_lattice α] [complete_lattice β] /-- A function `f` between complete lattices is order-continuous if it preserves all suprema. -/ def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i) lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ := have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _, have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl, begin rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h, rw [h, supr_insert, supr_singleton, sup_comm] end lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f := assume a₁ a₂ h, calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left ... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm ... = _ : by rw [sup_of_le_right h] end ord_continuous end lattice namespace order_dual open lattice variable (α : Type*) instance [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.lattice.bounded_lattice α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.lattice.complete_lattice α, .. order_dual.decidable_linear_order α } end order_dual namespace prod open lattice variables (α : Type*) (β : Type*) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.lattice.bounded_lattice α β, .. prod.lattice.has_Sup α β, .. prod.lattice.has_Inf α β } end prod
773b7c95e4af16565b8cc40153d0e17d34a51fdc
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/group/prod.lean
a1c5223e4bf6fa8be185f9341e12b668abdbc532
[ "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
12,415
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import algebra.group.hom import data.equiv.mul_add import data.prod /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. -/ variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace prod @[to_additive] instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ @[simp, to_additive] lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive] lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive] lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl @[to_additive] instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ @[simp, to_additive] lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl @[simp, to_additive] lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl @[to_additive] lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl @[simp, to_additive] lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 := mk.inj_iff @[to_additive] lemma fst_mul_snd [mul_one_class M] [mul_one_class N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive] lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive] lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl @[simp, to_additive] lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl @[to_additive] instance [has_div M] [has_div N] : has_div (M × N) := ⟨λ p q, ⟨p.1 / q.1, p.2 / q.2⟩⟩ @[simp] lemma fst_sub [add_group A] [add_group B] (a b : A × B) : (a - b).1 = a.1 - b.1 := rfl @[simp] lemma snd_sub [add_group A] [add_group B] (a b : A × B) : (a - b).2 = a.2 - b.2 := rfl @[simp] lemma mk_sub_mk [add_group A] [add_group B] (x₁ x₂ : A) (y₁ y₂ : B) : (x₁, y₁) - (x₂, y₂) = (x₁ - x₂, y₁ - y₂) := rfl instance [mul_zero_class M] [mul_zero_class N] : mul_zero_class (M × N) := { zero_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, .. prod.has_zero, .. prod.has_mul } @[to_additive] instance [semigroup M] [semigroup N] : semigroup (M × N) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } @[to_additive] instance [mul_one_class M] [mul_one_class N] : mul_one_class (M × N) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.has_mul, .. prod.has_one } @[to_additive] instance [monoid M] [monoid N] : monoid (M × N) := { .. prod.semigroup, .. prod.mul_one_class } @[to_additive] instance [group G] [group H] : group (G × H) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, div_eq_mul_inv := λ a b, mk.inj_iff.mpr ⟨div_eq_mul_inv _ _, div_eq_mul_inv _ _⟩, .. prod.monoid, .. prod.has_inv, .. prod.has_div } @[to_additive] instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } @[to_additive] instance [left_cancel_semigroup G] [left_cancel_semigroup H] : left_cancel_semigroup (G × H) := { mul_left_cancel := λ a b c h, prod.ext (mul_left_cancel (prod.ext_iff.1 h).1) (mul_left_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [right_cancel_semigroup G] [right_cancel_semigroup H] : right_cancel_semigroup (G × H) := { mul_right_cancel := λ a b c h, prod.ext (mul_right_cancel (prod.ext_iff.1 h).1) (mul_right_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [left_cancel_monoid M] [left_cancel_monoid N] : left_cancel_monoid (M × N) := { .. prod.left_cancel_semigroup, .. prod.monoid } @[to_additive] instance [right_cancel_monoid M] [right_cancel_monoid N] : right_cancel_monoid (M × N) := { .. prod.right_cancel_semigroup, .. prod.monoid } @[to_additive] instance [cancel_monoid M] [cancel_monoid N] : cancel_monoid (M × N) := { .. prod.right_cancel_monoid, .. prod.left_cancel_monoid } @[to_additive] instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) := { .. prod.comm_semigroup, .. prod.monoid } @[to_additive] instance [cancel_comm_monoid M] [cancel_comm_monoid N] : cancel_comm_monoid (M × N) := { .. prod.left_cancel_monoid, .. prod.right_cancel_monoid, .. prod.comm_monoid } instance [monoid_with_zero M] [monoid_with_zero N] : monoid_with_zero (M × N) := { .. prod.monoid, .. prod.mul_zero_class } instance [comm_monoid_with_zero M] [comm_monoid_with_zero N] : comm_monoid_with_zero (M × N) := { .. prod.comm_monoid, .. prod.mul_zero_class } @[to_additive] instance [comm_group G] [comm_group H] : comm_group (G × H) := { .. prod.comm_semigroup, .. prod.group } end prod namespace monoid_hom variables (M N) [mul_one_class M] [mul_one_class N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`."] def inl : M →* M × N := ⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`."] def inr : N →* M × N := ⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl @[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl @[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl @[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl section prod variable [mul_one_class P] /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)` -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →* N) (g : M →* P) : M →* N × P := { to_fun := λ x, (f x, g x), map_one' := prod.ext f.map_one g.map_one, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[simp, to_additive prod_apply] lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] [mul_one_class P] (f : M →* M') (g : N →* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [comm_monoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[simp, to_additive] lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id $ M × N) lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end monoid_hom namespace mul_equiv section variables {M N} [mul_one_class M] [mul_one_class N] /-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/ @[to_additive prod_comm "The equivalence between `M × N` and `N × M` given by swapping the components is additive."] def prod_comm : M × N ≃* N × M := { map_mul' := λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, rfl, ..equiv.prod_comm M N } @[simp, to_additive coe_prod_comm] lemma coe_prod_comm : ⇑(prod_comm : M × N ≃* N × M) = prod.swap := rfl @[simp, to_additive coe_prod_comm_symm] lemma coe_prod_comm_symm : ⇑((prod_comm : M × N ≃* N × M).symm) = prod.swap := rfl end section variables {M N} [monoid M] [monoid N] /-- The monoid equivalence between units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive prod_add_units "The additive monoid equivalence between additive units of a product of two additive monoids, and the product of the additive units of each additive monoid."] def prod_units : units (M × N) ≃* units M × units N := { to_fun := (units.map (monoid_hom.fst M N)).prod (units.map (monoid_hom.snd M N)), inv_fun := λ u, ⟨(u.1, u.2), (↑u.1⁻¹, ↑u.2⁻¹), by simp, by simp⟩, left_inv := λ u, by simp, right_inv := λ ⟨u₁, u₂⟩, by simp [units.map], map_mul' := monoid_hom.map_mul _ } end end mul_equiv
b979301589a62e680823ce09757df9938861b1e5
63abd62053d479eae5abf4951554e1064a4c45b4
/archive/miu_language/basic.lean
a15371be95fb3125356a0f7d061407ef070cba15
[ "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
6,032
lean
/- Copyright (c) 2020 Gihan Marasingha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gihan Marasingha -/ import tactic.linarith /-! # An MIU Decision Procedure in Lean The [MIU formal system](https://en.wikipedia.org/wiki/MU_puzzle) was introduced by Douglas Hofstadter in the first chapter of his 1979 book, [Gödel, Escher, Bach](https://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach). The system is defined by four rules of inference, one axiom, and an alphabet of three symbols: `M`, `I`, and `U`. Hofstadter's central question is: can the string `"MU"` be derived? It transpires that there is a simple decision procedure for this system. A string is derivable if and only if it starts with `M`, contains no other `M`s, and the number of `I`s in the string is congruent to 1 or 2 modulo 3. The principal aim of this project is to give a Lean proof that the derivability of a string is a decidable predicate. ## The MIU System In Hofstadter's description, an _atom_ is any one of `M`, `I` or `U`. A _string_ is a finite sequence of zero or more symbols. To simplify notation, we write a sequence `[I,U,U,M]`, for example, as `IUUM`. The four rules of inference are: 1. xI → xIU, 2. Mx → Mxx, 3. xIIIy → xUy, 4. xUUy → xy, where the notation α → β is to be interpreted as 'if α is derivable, then β is derivable'. Additionally, he has an axiom: * `MI` is derivable. In Lean, it is natural to treat the rules of inference and the axiom on an equal footing via an inductive data type `derivable` designed so that `derviable x` represents the notion that the string `x` can be derived from the axiom by the rules of inference. The axiom is represented as a nonrecursive constructor for `derivable`. This mirrors the translation of Peano's axiom '0 is a natural number' into the nonrecursive constructor `zero` of the inductive type `nat`. ## References * [Jeremy Avigad, Leonardo de Moura and Soonho Kong, _Theorem Proving in Lean_][avigad_moura_kong-2017] * [Douglas R Hofstadter, _Gödel, Escher, Bach_][Hofstadter-1979] ## Tags miu, derivable strings -/ namespace miu /-! ### Declarations and instance derivations for `miu_atom` and `miustr` -/ /-- The atoms of MIU can be represented as an enumerated type in Lean. -/ @[derive decidable_eq] inductive miu_atom : Type | M : miu_atom | I : miu_atom | U : miu_atom /-! The annotation `@[derive decidable_eq]` above assigns the attribute `derive` to `miu_atom`, through which Lean automatically derives that `miu_atom` is an instance of `decidable_eq`. The use of `derive` is crucial in this project and will lead to the automatic derivation of decidability. -/ open miu_atom /-- We show that the type `miu_atom` is inhabited, giving `M` (for no particular reason) as the default element. -/ instance miu_atom_inhabited : inhabited miu_atom := inhabited.mk M /-- `miu_atom.repr` is the 'natural' function from `miu_atom` to `string`. -/ def miu_atom.repr : miu_atom → string | M := "M" | I := "I" | U := "U" /-- Using `miu_atom.repr`, we prove that ``miu_atom` is an instance of `has_repr`. -/ instance : has_repr miu_atom := ⟨λ u, u.repr⟩ /-- For simplicity, an `miustr` is just a list of elements of type `miu_atom`. -/ @[derive [has_append, has_mem miu_atom]] def miustr := list miu_atom /-- For display purposes, an `miustr` can be represented as a `string`. -/ def miustr.mrepr : miustr → string | [] := "" | (c::cs) := c.repr ++ (miustr.mrepr cs) instance miurepr : has_repr miustr := ⟨λ u, u.mrepr⟩ /-- In the other direction, we set up a coercion from `string` to `miustr`. -/ def lchar_to_miustr : (list char) → miustr | [] := [] | (c::cs) := let ms := lchar_to_miustr cs in match c with | 'M' := M::ms | 'I' := I::ms | 'U' := U::ms | _ := [] end instance string_coe_miustr : has_coe string miustr := ⟨λ st, lchar_to_miustr st.data ⟩ /-! ### Derivability -/ /-- The inductive type `derivable` has five constructors. The nonrecursive constructor `mk` corresponds to Hofstadter's axiom that `"MI"` is derivable. Each of the constructors `r1`, `r2`, `r3`, `r4` corresponds to the one of Hofstadter's rules of inference. -/ inductive derivable : miustr → Prop | mk : derivable "MI" | r1 {x} : derivable (x ++ [I]) → derivable (x ++ [I, U]) | r2 {x} : derivable (M :: x) → derivable (M :: x ++ x) | r3 {x y} : derivable (x ++ [I, I, I] ++ y) → derivable (x ++ U :: y) | r4 {x y} : derivable (x ++ [U, U] ++ y) → derivable (x ++ y) /-! ### Rule usage examples -/ example (h : derivable "UMI") : derivable "UMIU" := begin change ("UMIU" : miustr) with [U,M] ++ [I,U], exact derivable.r1 h, -- Rule 1 end example (h : derivable "MIIU") : derivable "MIIUIIU" := begin change ("MIIUIIU" : miustr) with M :: [I,I,U] ++ [I,I,U], exact derivable.r2 h, -- Rule 2 end example (h : derivable "UIUMIIIMMM") : derivable "UIUMUMMM" := begin change ("UIUMUMMM" : miustr) with [U,I,U,M] ++ U :: [M,M,M], exact derivable.r3 h, -- Rule 3 end example (h : derivable "MIMIMUUIIM") : derivable "MIMIMIIM" := begin change ("MIMIMIIM" : miustr) with [M,I,M,I,M] ++ [I,I,M], exact derivable.r4 h, -- Rule 4 end /-! ### Derivability examples -/ private lemma MIU_der : derivable "MIU":= begin change ("MIU" :miustr) with [M] ++ [I,U], apply derivable.r1, -- reduce to deriving "MI", constructor, -- which is the base of the inductive construction. end example : derivable "MIUIU" := begin change ("MIUIU" : miustr) with M :: [I,U] ++ [I,U], exact derivable.r2 MIU_der, -- `"MIUIU"` can be derived as `"MIU"` can. end example : derivable "MUI" := begin have h₂ : derivable "MII", { change ("MII" : miustr) with M :: [I] ++ [I], exact derivable.r2 derivable.mk, }, have h₃ : derivable "MIIII", { change ("MIIII" : miustr) with M :: [I,I] ++ [I,I], exact derivable.r2 h₂, }, change ("MUI" : miustr) with [M] ++ U :: [I], exact derivable.r3 h₃, -- We prove our main goal using rule 3 end end miu
565b7b75dc4c7aad8130b007eb5939bbd21881e7
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/util.lean
f7762c8f9aa3618abe08efa26912c464a96982b1
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
1,446
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.string.basic universes u /- This function has a native implementation that tracks time. -/ def timeit {α : Type u} (s : string) (f : thunk α) : α := f () /- This function has a native implementation that displays the given string in the regular output stream. -/ def trace {α : Type u} (s : string) (f : thunk α) : α := f () /- This function has a native implementation that shows the VM call stack. -/ def trace_call_stack {α : Type u} (f : thunk α) : α := f () /- This function has a native implementation that displays in the given position all trace messages used in f. The arguments line and col are filled by the elaborator. -/ def scope_trace {α : Type u} {line col: nat} (f : thunk α) : α := f () /-- This function has a native implementation where the thunk is interrupted if it takes more than 'max' "heartbeats" to compute it. The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'f ()'. This is a deterministic way of interrupting long running tasks. -/ meta def try_for {α : Type u} (max : nat) (f : thunk α) : option α := some (f ()) meta constant undefined_core {α : Sort u} (message : string) : α meta def undefined {α : Sort u} : α := undefined_core "undefined"
2e0fe9c1b7ccbc424a3d0314df599e786081241e
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/tests/lean/run/super_examples.lean
9e59b3b4d34a91977eb156488fb704f1741ae990
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
3,028
lean
import tools.super open tactic constant nat_has_dvd : has_dvd nat attribute [instance] nat_has_dvd noncomputable def prime (n : ℕ) := ∀d, dvd d n → d = 1 ∨ d = n axiom dvd_refl (m : ℕ) : dvd m m axiom dvd_mul (m n k : ℕ) : dvd m n → dvd m (n*k) axiom nat_mul_cancel_one (m n : ℕ) : m = m * n → n = 1 example {m n : ℕ} : prime (m * n) → m = 1 ∨ n = 1 := begin with_lemmas dvd_refl dvd_mul nat_mul_cancel_one, super end example : nat.zero ≠ nat.succ nat.zero := by super example (x y : ℕ) : nat.succ x = nat.succ y → x = y := by super example (i) (a b c : i) : [a,b,c] = [b,c,a] -> a = b ∧ b = c := by super definition is_positive (n : ℕ) := n > 0 example (n : ℕ) : n > 0 ↔ is_positive n := by super example (m n : ℕ) : 0 + m = 0 + n → m = n := by super with nat.zero_add local attribute [simp] nat.zero_add nat.succ_add @[simp] lemma nat_add_succ (m n : ℕ) : m + nat.succ n = nat.succ (m + n) := rfl @[simp] lemma nat_zero_has_zero : nat.zero = 0 := rfl example : ∀x y : ℕ, x + y = y + x := begin intros, induction x, super, super end example (i) [inhabited i] : nonempty i := by super example (i) [nonempty i] : ¬(inhabited i → false) := by super example : nonempty ℕ := by super example : ¬(inhabited ℕ → false) := by super example {a b} : ¬(b ∨ ¬a) ∨ (a → b) := by super example {a} : a ∨ ¬a := by super example {a} : (a ∧ a) ∨ (¬a ∧ ¬a) := by super example (i) (c : i) (p : i → Prop) (f : i → i) : p c → (∀x, p x → p (f x)) → p (f (f (f c))) := by super example (i) (p : i → Prop) : ∀x, p x → ∃x, p x := by super example (i) [nonempty i] (p : i → i → Prop) : (∀x y, p x y) → ∃x, ∀z, p x z := by super example (i) [nonempty i] (p : i → Prop) : (∀x, p x) → ¬¬∀x, p x := by super -- Requires non-empty domain. example {i} [nonempty i] (p : i → Prop) : (∀x y, p x ∨ p y) → ∃x y, p x ∧ p y := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p b → p a := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p a → p b := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p b = p a := by super example (i) (c : i) (p : i → Prop) (f g : i → i) : p c → (∀x, p x → p (f x)) → (∀x, p x → f x = g x) → f (f c) = g (g c) := by super example (i) (p q : i → i → Prop) (a b c d : i) : (∀x y z, p x y ∧ p y z → p x z) → (∀x y z, q x y ∧ q y z → q x z) → (∀x y, q x y → q y x) → (∀x y, p x y ∨ q x y) → p a b ∨ q c d := by super -- This example from Davis-Putnam actually requires a non-empty domain example (i) [nonempty i] (f g : i → i → Prop) : ∃x y, ∀z, (f x y → f y z ∧ f z z) ∧ (f x y ∧ g x y → g x z ∧ g z z) := by super example (person) [nonempty person] (drinks : person → Prop) : ∃canary, drinks canary → ∀other, drinks other := by super example {p q : ℕ → Prop} {r} : (∀x y, p x ∧ q y ∧ r) -> ∀x, (p x ∧ r ∧ q x) := by super
bd7e23511990bd327e02ab57756518d980031576
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/imo/imo1975_q1.lean
47170ea79e550f0981958de07cd761d4fdbcef6c
[ "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
2,090
lean
/- Copyright (c) 2022 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import data.real.basic import data.nat.interval import algebra.order.rearrangement import algebra.big_operators.ring /-! # IMO 1975 Q1 Let `x₁, x₂, ... , xₙ` and `y₁, y₂, ... , yₙ` be two sequences of real numbers, such that `x₁ ≥ x₂ ≥ ... ≥ xₙ` and `y₁ ≥ y₂ ≥ ... ≥ yₙ`. Prove that if `z₁, z₂, ... , zₙ` is any permutation of `y₁, y₂, ... , yₙ`, then `∑ (xᵢ - yᵢ)^2 ≤ ∑ (xᵢ - zᵢ)^2` # Solution Firstly, we expand the squares withing both sums and distribute into separate finite sums. Then, noting that `∑ yᵢ ^ 2 = ∑ zᵢ ^ 2`, it remains to prove that `∑ xᵢ * zᵢ ≤ ∑ xᵢ * yᵢ`, which is true by the Rearrangement Inequality -/ open_locale big_operators /- Let `n` be a natural number, `x` and `y` be as in the problem statement and `σ` be the permutation of natural numbers such that `z = y ∘ σ` -/ variables (n : ℕ) (σ : equiv.perm ℕ) (hσ : {x | σ x ≠ x} ⊆ finset.Icc 1 n) (x y : ℕ → ℝ) variables (hx : antitone_on x (finset.Icc 1 n)) variables (hy : antitone_on y (finset.Icc 1 n)) include hx hy hσ theorem IMO_1975_Q1 : ∑ i in finset.Icc 1 n, (x i - y i) ^ 2 ≤ ∑ i in finset.Icc 1 n, (x i - y (σ i)) ^ 2 := begin simp only [sub_sq, finset.sum_add_distrib, finset.sum_sub_distrib], -- a finite sum is invariant if we permute the order of summation have hσy : ∑ (i : ℕ) in finset.Icc 1 n, y i ^ 2 = ∑ (i : ℕ) in finset.Icc 1 n, y (σ i) ^ 2, { rw ← equiv.perm.sum_comp σ (finset.Icc 1 n) _ hσ }, -- let's cancel terms appearing on both sides norm_num [hσy, mul_assoc, ← finset.mul_sum], -- what's left to prove is a version of the rearrangement inequality apply monovary_on.sum_mul_comp_perm_le_sum_mul _ hσ, -- finally we need to show that `x` and `y` 'vary' together on `[1, n]` and this is due to both of -- them being `decreasing` exact antitone_on.monovary_on hx hy end
32d2be3395356fc92619c8b62bcff4130984c6ec
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/field_theory/tower.lean
1141cb3c76f573603c3e70b436cd49229da3da0f
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,087
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 ring_theory.algebra_tower import linear_algebra.matrix.finite_dimensional import linear_algebra.matrix.to_lin /-! # Tower of field extensions In this file we prove the tower law for arbitrary extensions and finite extensions. Suppose `L` is a field extension of `K` and `K` is a field extension of `F`. Then `[L:F] = [L:K] [K:F]` where `[E₁:E₂]` means the `E₂`-dimension of `E₁`. In fact we generalize it to vector spaces, where `L` is not necessarily a field, but just a vector space over `K`. ## Implementation notes We prove two versions, since there are two notions of dimensions: `module.rank` which gives the dimension of an arbitrary vector space as a cardinal, and `finite_dimensional.finrank` which gives the dimension of a finitely-dimensional vector space as a natural number. ## Tags tower law -/ universes u v w u₁ v₁ w₁ open_locale classical big_operators section field open cardinal variables (F : Type u) (K : Type v) (A : Type w) variables [field F] [field K] [add_comm_group A] variables [algebra F K] [module K A] [module F A] [is_scalar_tower F K A] /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim' : (cardinal.lift.{w} (module.rank F K) * cardinal.lift.{v} (module.rank K A)) = cardinal.lift.{v} (module.rank F A) := let b := basis.of_vector_space F K, c := basis.of_vector_space K A in by rw [← (module.rank F K).lift_id, ← b.mk_eq_dim, ← (module.rank K A).lift_id, ← c.mk_eq_dim, ← lift_umax.{w v}, ← (b.smul c).mk_eq_dim, mk_prod, lift_mul, lift_lift, lift_lift, lift_lift, lift_lift, lift_umax] /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim (F : Type u) (K A : Type v) [field F] [field K] [add_comm_group A] [algebra F K] [module K A] [module F A] [is_scalar_tower F K A] : module.rank F K * module.rank K A = module.rank F A := by convert dim_mul_dim' F K A; rw lift_id namespace finite_dimensional open is_noetherian theorem trans [finite_dimensional F K] [finite_dimensional K A] : finite_dimensional F A := let b := basis.of_vector_space F K, c := basis.of_vector_space K A in of_fintype_basis $ b.smul c lemma right [hf : finite_dimensional F A] : finite_dimensional K A := let ⟨⟨b, hb⟩⟩ := iff_fg.1 hf in iff_fg.2 ⟨⟨b, submodule.restrict_scalars_injective F _ _ $ by { rw [submodule.restrict_scalars_top, eq_top_iff, ← hb, submodule.span_le], exact submodule.subset_span }⟩⟩ /-- Tower law: if `A` is a `K`-algebra and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem finrank_mul_finrank [finite_dimensional F K] : finrank F K * finrank K A = finrank F A := begin by_cases hA : finite_dimensional K A, { resetI, let b := basis.of_vector_space F K, let c := basis.of_vector_space K A, rw [finrank_eq_card_basis b, finrank_eq_card_basis c, finrank_eq_card_basis (b.smul c), fintype.card_prod] }, { rw [finrank_of_infinite_dimensional hA, mul_zero, finrank_of_infinite_dimensional], exact mt (@right F K A _ _ _ _ _ _ _) hA } end instance linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [module F V] [add_comm_group W] [module F W] [finite_dimensional F V] [finite_dimensional F W] : finite_dimensional F (V →ₗ[F] W) := let b := basis.of_vector_space F V, c := basis.of_vector_space F W in (matrix.to_lin b c).finite_dimensional lemma finrank_linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [module F V] [add_comm_group W] [module F W] [finite_dimensional F V] [finite_dimensional F W] : finrank F (V →ₗ[F] W) = finrank F V * finrank F W := let b := basis.of_vector_space F V, c := basis.of_vector_space F W in by rw [linear_equiv.finrank_eq (linear_map.to_matrix b c), matrix.finrank_matrix, finrank_eq_card_basis b, finrank_eq_card_basis c, mul_comm] -- TODO: generalize by removing [finite_dimensional F K] -- V = ⊕F, -- (V →ₗ[F] K) = ((⊕F) →ₗ[F] K) = (⊕ (F →ₗ[F] K)) = ⊕K instance linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [module F V] [finite_dimensional F V] : finite_dimensional K (V →ₗ[F] K) := right F _ _ lemma finrank_linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [module F V] [finite_dimensional F V] : finrank K (V →ₗ[F] K) = finrank F V := (nat.mul_right_inj $ show 0 < finrank F K, from finrank_pos).1 $ calc finrank F K * finrank K (V →ₗ[F] K) = finrank F (V →ₗ[F] K) : finrank_mul_finrank _ _ _ ... = finrank F V * finrank F K : finrank_linear_map F V K ... = finrank F K * finrank F V : mul_comm _ _ end finite_dimensional end field
24b398fc3abd028ba37a410defa0c3af01f8fb97
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world10/level14.lean
188f415200962e1087ff7cfd725839d825cc7eb3
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
521
lean
import game.world10.level13 -- hide namespace mynat -- hide /- # Inequality world. ## Level 14: `add_le_add_left` I know these are easy and we've done several already, but this is one of the axioms for an ordered commutative monoid! We'll get something new in the next level. -/ /- Lemma If $a\le b$ then for all $t$, $t+a\le t+b$. -/ theorem add_le_add_left (a b : mynat) (h : a ≤ b) (t : mynat) : t + a ≤ t + b := begin [less_leaky] cases h with c hc, use c, rw hc, ring, end end mynat -- hide
0dcbbeb2cd0e450137e803cc5adf805b73d59895
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/set/pointwise/interval.lean
d62629b46dcdd3f0c2f82f7d48f1fa68ab751f11
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
20,828
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, Patrick Massot -/ import data.set.intervals.unordered_interval import data.set.intervals.monoid import data.set.pointwise.basic import algebra.order.field.basic import algebra.order.group.min_max /-! # (Pre)images of intervals In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`, then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove lemmas about preimages and images of all intervals. We also prove a few lemmas about images under `x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`. -/ open_locale interval pointwise variables {α : Type*} namespace set section ordered_add_comm_group variables [ordered_add_comm_group α] (a b c : α) /-! ### Preimages under `x ↦ a + x` -/ @[simp] lemma preimage_const_add_Ici : (λ x, a + x) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add'.symm @[simp] lemma preimage_const_add_Ioi : (λ x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add'.symm @[simp] lemma preimage_const_add_Iic : (λ x, a + x) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le'.symm @[simp] lemma preimage_const_add_Iio : (λ x, a + x) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt'.symm @[simp] lemma preimage_const_add_Icc : (λ x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_const_add_Ico : (λ x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_const_add_Ioc : (λ x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_const_add_Ioo : (λ x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ x + a` -/ @[simp] lemma preimage_add_const_Ici : (λ x, x + a) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add.symm @[simp] lemma preimage_add_const_Ioi : (λ x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add.symm @[simp] lemma preimage_add_const_Iic : (λ x, x + a) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le.symm @[simp] lemma preimage_add_const_Iio : (λ x, x + a) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt.symm @[simp] lemma preimage_add_const_Icc : (λ x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_add_const_Ico : (λ x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_add_const_Ioc : (λ x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_add_const_Ioo : (λ x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ -x` -/ @[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ λ x, le_neg @[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ λ x, neg_le @[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ λ x, lt_neg @[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ λ x, neg_lt @[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Preimages under `x ↦ x - a` -/ @[simp] lemma preimage_sub_const_Ici : (λ x, x - a) ⁻¹' (Ici b) = Ici (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioi : (λ x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iic : (λ x, x - a) ⁻¹' (Iic b) = Iic (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iio : (λ x, x - a) ⁻¹' (Iio b) = Iio (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Icc : (λ x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ico : (λ x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioc : (λ x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioo : (λ x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) := by simp [sub_eq_add_neg] /-! ### Preimages under `x ↦ a - x` -/ @[simp] lemma preimage_const_sub_Ici : (λ x, a - x) ⁻¹' (Ici b) = Iic (a - b) := ext $ λ x, le_sub_comm @[simp] lemma preimage_const_sub_Iic : (λ x, a - x) ⁻¹' (Iic b) = Ici (a - b) := ext $ λ x, sub_le_comm @[simp] lemma preimage_const_sub_Ioi : (λ x, a - x) ⁻¹' (Ioi b) = Iio (a - b) := ext $ λ x, lt_sub_comm @[simp] lemma preimage_const_sub_Iio : (λ x, a - x) ⁻¹' (Iio b) = Ioi (a - b) := ext $ λ x, sub_lt_comm @[simp] lemma preimage_const_sub_Icc : (λ x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_const_sub_Ico : (λ x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioc : (λ x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioo : (λ x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Images under `x ↦ a + x` -/ @[simp] lemma image_const_add_Iic : (λ x, a + x) '' Iic b = Iic (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iio : (λ x, a + x) '' Iio b = Iio (a + b) := by simp [add_comm] /-! ### Images under `x ↦ x + a` -/ @[simp] lemma image_add_const_Iic : (λ x, x + a) '' Iic b = Iic (b + a) := by simp @[simp] lemma image_add_const_Iio : (λ x, x + a) '' Iio b = Iio (b + a) := by simp /-! ### Images under `x ↦ -x` -/ lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp /-! ### Images under `x ↦ a - x` -/ @[simp] lemma image_const_sub_Ici : (λ x, a - x) '' Ici b = Iic (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iic : (λ x, a - x) '' Iic b = Ici (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x), add_comm] @[simp] lemma image_const_sub_Ioi : (λ x, a - x) '' Ioi b = Iio (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iio : (λ x, a - x) '' Iio b = Ioi (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x), add_comm] @[simp] lemma image_const_sub_Icc : (λ x, a - x) '' Icc b c = Icc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x), add_comm] @[simp] lemma image_const_sub_Ico : (λ x, a - x) '' Ico b c = Ioc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x), add_comm] @[simp] lemma image_const_sub_Ioc : (λ x, a - x) '' Ioc b c = Ico (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x), add_comm] @[simp] lemma image_const_sub_Ioo : (λ x, a - x) '' Ioo b c = Ioo (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x), add_comm] /-! ### Images under `x ↦ x - a` -/ @[simp] lemma image_sub_const_Ici : (λ x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iic : (λ x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioi : (λ x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iio : (λ x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Icc : (λ x, x - a) '' Icc b c = Icc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ico : (λ x, x - a) '' Ico b c = Ico (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioc : (λ x, x - a) '' Ioc b c = Ioc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioo : (λ x, x - a) '' Ioo b c = Ioo (b - a) (c - a) := by simp [sub_eq_neg_add] /-! ### Bijections -/ lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) := image_add_const_Iic a b ▸ ((add_left_injective _).inj_on _).bij_on_image lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) := image_add_const_Iio a b ▸ ((add_left_injective _).inj_on _).bij_on_image end ordered_add_comm_group section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] (a b c d : α) @[simp] lemma preimage_const_add_uIcc : (λ x, a + x) ⁻¹' [b, c] = [b - a, c - a] := by simp only [←Icc_min_max, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right] @[simp] lemma preimage_add_const_uIcc : (λ x, x + a) ⁻¹' [b, c] = [b - a, c - a] := by simpa only [add_comm] using preimage_const_add_uIcc a b c @[simp] lemma preimage_neg_uIcc : - [a, b] = [-a, -b] := by simp only [←Icc_min_max, preimage_neg_Icc, min_neg_neg, max_neg_neg] @[simp] lemma preimage_sub_const_uIcc : (λ x, x - a) ⁻¹' [b, c] = [b + a, c + a] := by simp [sub_eq_add_neg] @[simp] lemma preimage_const_sub_uIcc : (λ x, a - x) ⁻¹' [b, c] = [a - b, a - c] := by { simp_rw [←Icc_min_max, preimage_const_sub_Icc], simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg], } @[simp] lemma image_const_add_uIcc : (λ x, a + x) '' [b, c] = [a + b, a + c] := by simp [add_comm] @[simp] lemma image_add_const_uIcc : (λ x, x + a) '' [b, c] = [b + a, c + a] := by simp @[simp] lemma image_const_sub_uIcc : (λ x, a - x) '' [b, c] = [a - b, a - c] := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_sub_const_uIcc : (λ x, x - a) '' [b, c] = [b - a, c - a] := by simp [sub_eq_add_neg, add_comm] lemma image_neg_uIcc : has_neg.neg '' [a, b] = [-a, -b] := by simp variables {a b c d} /-- If `[c, d]` is a subinterval of `[a, b]`, then the distance between `c` and `d` is less than or equal to that of `a` and `b` -/ lemma abs_sub_le_of_uIcc_subset_uIcc (h : [c, d] ⊆ [a, b]) : |d - c| ≤ |b - a| := begin rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs], rw [uIcc_subset_uIcc_iff_le] at h, exact sub_le_sub h.2 h.1, end /-- If `c ∈ [a, b]`, then the distance between `a` and `c` is less than or equal to that of `a` and `b` -/ lemma abs_sub_left_of_mem_uIcc (h : c ∈ [a, b]) : |c - a| ≤ |b - a| := abs_sub_le_of_uIcc_subset_uIcc $ uIcc_subset_uIcc_left h /-- If `x ∈ [a, b]`, then the distance between `c` and `b` is less than or equal to that of `a` and `b` -/ lemma abs_sub_right_of_mem_uIcc (h : c ∈ [a, b]) : |b - c| ≤ |b - a| := abs_sub_le_of_uIcc_subset_uIcc $ uIcc_subset_uIcc_right h end linear_ordered_add_comm_group /-! ### Multiplication and inverse in a field -/ section linear_ordered_field variables [linear_ordered_field α] {a : α} @[simp] lemma preimage_mul_const_Iio (a : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff h).symm @[simp] lemma preimage_mul_const_Ioi (a : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff h).symm @[simp] lemma preimage_mul_const_Iic (a : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff h).symm @[simp] lemma preimage_mul_const_Ici (a : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff h).symm @[simp] lemma preimage_mul_const_Ioo (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_mul_const_Ioc (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_mul_const_Ico (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_mul_const_Icc (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_mul_const_Iio_of_neg (a : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Iio a) = Ioi (a / c) := ext $ λ x, (div_lt_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioi_of_neg (a : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioi a) = Iio (a / c) := ext $ λ x, (lt_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Iic_of_neg (a : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Iic a) = Ici (a / c) := ext $ λ x, (div_le_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ici_of_neg (a : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Ici a) = Iic (a / c) := ext $ λ x, (le_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioo_of_neg (a b : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simp [← Ioi_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ioc_of_neg (a b : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ico_of_neg (a b : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm] @[simp] lemma preimage_mul_const_Icc_of_neg (a b : α) {c : α} (h : c < 0) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simp [← Ici_inter_Iic, h, inter_comm] @[simp] lemma preimage_const_mul_Iio (a : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff' h).symm @[simp] lemma preimage_const_mul_Ioi (a : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff' h).symm @[simp] lemma preimage_const_mul_Iic (a : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff' h).symm @[simp] lemma preimage_const_mul_Ici (a : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff' h).symm @[simp] lemma preimage_const_mul_Ioo (a b : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_const_mul_Ioc (a b : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_const_mul_Ico (a b : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_const_mul_Icc (a b : α) {c : α} (h : 0 < c) : ((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_const_mul_Iio_of_neg (a : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Iio a) = Ioi (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h @[simp] lemma preimage_const_mul_Ioi_of_neg (a : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Ioi a) = Iio (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h @[simp] lemma preimage_const_mul_Iic_of_neg (a : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Iic a) = Ici (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h @[simp] lemma preimage_const_mul_Ici_of_neg (a : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Ici a) = Iic (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h @[simp] lemma preimage_const_mul_Ioo_of_neg (a b : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h @[simp] lemma preimage_const_mul_Ioc_of_neg (a b : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h @[simp] lemma preimage_const_mul_Ico_of_neg (a b : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h @[simp] lemma preimage_const_mul_Icc_of_neg (a b : α) {c : α} (h : c < 0) : ((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h @[simp] lemma preimage_mul_const_uIcc (ha : a ≠ 0) (b c : α) : (λ x, x * a) ⁻¹' [b, c] = [b / a, c / a] := (lt_or_gt_of_ne ha).elim (λ h, by simp [←Icc_min_max, h, h.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos]) (λ (ha : 0 < a), by simp [←Icc_min_max, ha, ha.le, min_div_div_right, max_div_div_right]) @[simp] lemma preimage_const_mul_uIcc (ha : a ≠ 0) (b c : α) : (λ x, a * x) ⁻¹' [b, c] = [b / a, c / a] := by simp only [← preimage_mul_const_uIcc ha, mul_comm] @[simp] lemma preimage_div_const_uIcc (ha : a ≠ 0) (b c : α) : (λ x, x / a) ⁻¹' [b, c] = [b * a, c * a] := by simp only [div_eq_mul_inv, preimage_mul_const_uIcc (inv_ne_zero ha), inv_inv] @[simp] lemma image_mul_const_uIcc (a b c : α) : (λ x, x * a) '' [b, c] = [b * a, c * a] := if ha : a = 0 then by simp [ha] else calc (λ x, x * a) '' [b, c] = (λ x, x * a⁻¹) ⁻¹' [b, c] : (units.mk0 a ha).mul_right.image_eq_preimage _ ... = (λ x, x / a) ⁻¹' [b, c] : by simp only [div_eq_mul_inv] ... = [b * a, c * a] : preimage_div_const_uIcc ha _ _ @[simp] lemma image_const_mul_uIcc (a b c : α) : (λ x, a * x) '' [b, c] = [a * b, a * c] := by simpa only [mul_comm] using image_mul_const_uIcc a b c @[simp] lemma image_div_const_uIcc (a b c : α) : (λ x, x / a) '' [b, c] = [b / a, c / a] := by simp only [div_eq_mul_inv, image_mul_const_uIcc] lemma image_mul_right_Icc' (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_right_Icc {a b c : α} (hab : a ≤ b) (hc : 0 ≤ c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b ‹0 < c› end lemma image_mul_left_Icc' {a : α} (h : 0 < a) (b c : α) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : α} (ha : 0 ≤ a) (hbc : b ≤ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } lemma image_mul_right_Ioo (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) '' Ioo a b = Ioo (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_left_Ioo {a : α} (h : 0 < a) (b c : α) : ((*) a) '' Ioo b c = Ioo (a * b) (a * c) := by { convert image_mul_right_Ioo b c h using 1; simp only [mul_comm _ a] } /-- The (pre)image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/ lemma inv_Ioo_0_left {a : α} (ha : 0 < a) : (Ioo 0 a)⁻¹ = Ioi a⁻¹ := begin ext x, exact ⟨λ h, inv_inv x ▸ (inv_lt_inv ha h.1).2 h.2, λ h, ⟨inv_pos.2 $ (inv_pos.2 ha).trans h, inv_inv a ▸ (inv_lt_inv ((inv_pos.2 ha).trans h) (inv_pos.2 ha)).2 h⟩⟩, end lemma inv_Ioi {a : α} (ha : 0 < a) : (Ioi a)⁻¹ = Ioo 0 a⁻¹ := by rw [inv_eq_iff_inv_eq, inv_Ioo_0_left (inv_pos.2 ha), inv_inv] lemma image_const_mul_Ioi_zero {k : Type*} [linear_ordered_field k] {x : k} (hx : 0 < x) : (λ y, x * y) '' Ioi (0 : k) = Ioi 0 := by erw [(units.mk0 x hx.ne').mul_left.image_eq_preimage, preimage_const_mul_Ioi 0 (inv_pos.mpr hx), zero_div] /-! ### Images under `x ↦ a * x + b` -/ @[simp] lemma image_affine_Icc' {a : α} (h : 0 < a) (b c d : α) : (λ x, a * x + b) '' Icc c d = Icc (a * c + b) (a * d + b) := begin suffices : (λ x, x + b) '' ((λ x, a * x) '' Icc c d) = Icc (a * c + b) (a * d + b), { rwa set.image_image at this, }, rw [image_mul_left_Icc' h, image_add_const_Icc], end end linear_ordered_field end set
5379fc10971bf9bdc95868ad2d3f7e1a632cee89
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/using_smt3.lean
0ae11c07d146898003496ba1e0bee1afe053983d
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
556
lean
open tactic lemma ex1 : let x := 1 in ∀ y, x = y → y = 1 := by using_smt $ smt_tactic.intros >> get_local `x >>= (fun a, trace a) open tactic_result meta def fail_if_success {α : Type} (t : smt_tactic α) : smt_tactic unit := λ ss ts, match t ss ts with | success _ _ := failed ts | exception _ _ _ := success ((), ss) ts end def my_smt_config : smt_config := { pre_cfg := { zeta := tt } } lemma ex2 : let x := 1 in ∀ y, x = y → y = 1 := by using_smt_with my_smt_config $ smt_tactic.intros >> fail_if_success (get_local `x) >> return ()
f05a093de1739d041ffc76f92f578630ef91d66c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/ordered_auto.lean
a1a6190bd4b83a7a6fce5c179f381ababb9cd16e
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,478
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.basic import Mathlib.algebra.ring.basic import Mathlib.analysis.asymptotics import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # Ordered normed spaces In this file, we define classes for fields and groups that are both normed and ordered. These are mostly useful to avoid diamonds during type class inference. -/ /-- A `normed_linear_ordered_group` is an additive group that is both a `normed_group` and a `linear_ordered_add_comm_group`. This class is necessary to avoid diamonds. -/ class normed_linear_ordered_group (α : Type u_1) extends has_norm α, linear_ordered_add_comm_group α, metric_space α where dist_eq : ∀ (x y : α), dist x y = norm (x - y) protected instance normed_linear_ordered_group.to_normed_group (α : Type u_1) [normed_linear_ordered_group α] : normed_group α := normed_group.mk normed_linear_ordered_group.dist_eq /-- A `normed_linear_ordered_field` is a field that is both a `normed_field` and a `linear_ordered_field`. This class is necessary to avoid diamonds. -/ class normed_linear_ordered_field (α : Type u_1) extends linear_ordered_field α, metric_space α, has_norm α where dist_eq : ∀ (x y : α), dist x y = norm (x - y) norm_mul' : ∀ (a b : α), norm (a * b) = norm a * norm b protected instance normed_linear_ordered_field.to_normed_field (α : Type u_1) [normed_linear_ordered_field α] : normed_field α := normed_field.mk normed_linear_ordered_field.dist_eq normed_linear_ordered_field.norm_mul' protected instance normed_linear_ordered_field.to_normed_linear_ordered_group (α : Type u_1) [normed_linear_ordered_field α] : normed_linear_ordered_group α := normed_linear_ordered_group.mk normed_linear_ordered_field.dist_eq theorem tendsto_pow_div_pow_at_top_of_lt {α : Type u_1} [normed_linear_ordered_field α] [order_topology α] {p : ℕ} {q : ℕ} (hpq : p < q) : filter.tendsto (fun (x : α) => x ^ p / x ^ q) filter.at_top (nhds 0) := sorry theorem is_o_pow_pow_at_top_of_lt {α : Type} [normed_linear_ordered_field α] [order_topology α] {p : ℕ} {q : ℕ} (hpq : p < q) : asymptotics.is_o (fun (x : α) => x ^ p) (fun (x : α) => x ^ q) filter.at_top := sorry end Mathlib
2022694cde4ee8fe63379f137b8d89215b3243b9
fd3506535396cef3d1bdcf4ae5b87c8ed9ff2c2e
/migrated/extra.lean
d7528fa34eebdd40b039b49c206b80ba54db5349
[]
no_license
williamdemeo/leanproved
77933dbcb8bfbae61a753ae31fa669b3ed8cda9d
d8c2e2ca0002b252fce049c4ff9be0e9e83a6374
refs/heads/master
1,598,674,802,432
1,437,528,488,000
1,437,528,488,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,334
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ -- These belong in the library somewhere. import algebra.group data -- Thought this might be useful in converting different forms of Prop theorem and_imp_curry (a b c : Prop) : (a ∧ b → c) = (a → b → c) := propext (iff.intro (λ Pl a b, Pl (and.intro a b)) (λ Pr Pand, Pr (and.left Pand) (and.right Pand))) theorem and_discharge_left {a b : Prop} : a → (a ∧ b) = b := assume Pa, propext (iff.intro (assume Pab, and.elim_right Pab) (assume Pb, and.intro Pa Pb)) definition swap {A B C : Type} (f : A → B → C) : B → A → C := λ x y, f y x definition not_imp_not_of_imp {a b : Prop} : (a → b) → ¬b → ¬a := assume Pimp Pnb Pa, absurd (Pimp Pa) Pnb section decidable_quantifiers lemma forall_of_not_exists_not {A : Type} {p : A → Prop} [h : decidable_pred p] : ¬(∃ x, ¬p x) → ∀ x, p x := assume Pne, take x, decidable.rec_on (h x) (λ P : p x, P) (λ nP : ¬p x, absurd (exists.intro x nP) Pne) end decidable_quantifiers namespace nat -- not sure why these are missing lemma not_lt_of_le {a b : nat} : a ≤ b → ¬ b < a := assume aleb, not.intro (assume blta, lt.irrefl a (lt_of_le_of_lt aleb blta)) end nat namespace set section open function variables {A B C: Type} variable {S : set A} lemma image_subset (S H : set A) : ∀ f : A → B, S ⊆ H → f '[S] ⊆ f '[H] := assume f, assume SsubH, begin esimp [image, subset, set_of, mem], intro x, intro Hex, cases Hex with y Img, exact (exists.intro y (and.intro (SsubH (and.left Img)) (and.right Img))) end end section open function variable {A : Type} lemma subset.trans (a b c : set A) : a ⊆ b → b ⊆ c → a ⊆ c := begin esimp [subset, mem], intro f, intro g, intro x, intro ax, exact g (f ax) end end end set namespace function section open set eq.ops variables {A B C : Type} lemma injective_eq_inj_on_univ {f : A → B} : injective f = inj_on f univ := begin esimp [injective, inj_on, univ, mem], apply propext, -- ⊢ (∀ (a₁ a₂ : A), f a₁ = f a₂ → a₁ = a₂) ↔ ∀ ⦃x1 x2 : A⦄, true → true → f x1 = f x2 → x1 = x2 repeat (apply forall_congr; intros), rewrite *true_imp end lemma univ_maps_to_univ {f : A → B} : maps_to f univ univ := take a, assume P, trivial theorem injective_compose {g : B → C} {f : A → B} (Hg : injective g) (Hf : injective f) : injective (g ∘ f) := eq.symm !injective_eq_inj_on_univ ▸ inj_on_compose univ_maps_to_univ (injective_eq_inj_on_univ ▸ Hg) (injective_eq_inj_on_univ ▸ Hf) lemma surjective_eq_surj_on_univ {f : A → B} : surjective f = surj_on f univ univ := begin esimp [surjective, surj_on, univ, image, subset, set_of, mem], apply propext, apply forall_congr, intro b, -- ⊢ (∃ (a : A), f a = b) ↔ true → (∃ (x : A), true ∧ f x = b) rewrite true_imp, apply exists_congr, intro a, rewrite true_and end theorem surjective_compose {g : B → C} {f : A → B} (Hg : surjective g) (Hf : surjective f) : surjective (g ∘ f) := eq.symm surjective_eq_surj_on_univ ▸ surj_on_compose (surjective_eq_surj_on_univ ▸ Hg) (surjective_eq_surj_on_univ ▸ Hf) -- classical definition of bijective, not requiring an inv definition bijective (f : A → B) := injective f ∧ surjective f lemma bijective_eq_bij_on_univ {f : A → B} : bijective f = bij_on f univ univ := assert P : maps_to f univ univ, from univ_maps_to_univ, by rewrite [↑bijective, ↑bij_on, injective_eq_inj_on_univ, surjective_eq_surj_on_univ, and_discharge_left P] theorem bijective_compose {g : B → C} {f : A → B} (Hg : bijective g) (Hf : bijective f) : bijective (g ∘ f) := eq.symm bijective_eq_bij_on_univ ▸ bij_on_compose (bijective_eq_bij_on_univ ▸ Hg) (bijective_eq_bij_on_univ ▸ Hf) theorem id_is_inj : injective (@id A) := take a1 a2, by rewrite ↑id; intro H; exact H theorem id_is_surj : surjective (@id A) := take a, exists.intro a rfl theorem id_is_bij : bijective (@id A) := and.intro id_is_inj id_is_surj lemma left_id (f : A → B) : id ∘ f = f := rfl lemma right_id (f : A → B) : f ∘ id = f := rfl lemma left_inv_of_right_inv_of_inj {A : Type} [h : decidable_eq A] {B : Type} {f : A → B} {g : B → A} : injective f → f∘g = id → g∘f = id := assume Pinj Pright, assert Pid : f∘(g∘f) = f, from calc f∘g∘f = (f∘g)∘f : compose.assoc ... = id∘f : Pright ... = f : left_id, funext (take x, decidable.rec_on (h ((g∘f) x) x) (λ Peq, Peq) (λ Pne, assert Pfneq : (f∘g∘f) x ≠ f x, from not_imp_not_of_imp (Pinj ((g∘f) x) x) Pne, by rewrite Pid at Pfneq; exact absurd rfl Pfneq)) end end function namespace algebra section group variable {A : Type} variable [s : group A] include s lemma comm_one (a : A) : a*1 = 1*a := calc a*1 = a : mul_one ... = 1*a : one_mul lemma comm_mul_eq_one (a b : A) : a*b = 1 = (b*a = 1) := propext (iff.intro (assume Pl : a*b = 1, assert Pinv : a⁻¹=b, from inv_eq_of_mul_eq_one Pl, by rewrite [eq.symm Pinv, mul.left_inv]) (assume Pr : b*a = 1, assert Pinv : b⁻¹=a, from inv_eq_of_mul_eq_one Pr, by rewrite [eq.symm Pinv, mul.left_inv])) end group end algebra namespace finset -- more development of theory of finset section image open function variables {A B : Type} variables [deceqA : decidable_eq A] [deceqB : decidable_eq B] include deceqA include deceqB lemma Union_insert (f : A → finset B) {a : A} {s : finset A} : Union (insert a s) f = f a ∪ Union s f := match decidable_mem a s with | decidable.inl Pin := begin rewrite [Union_insert_of_mem f Pin], apply ext, intro x, apply iff.intro, exact mem_union_r, rewrite [mem_union_eq], intro Por, exact or.elim Por (assume Pl, begin rewrite mem_Union_eq, exact (exists.intro a (and.intro Pin Pl)) end) (assume Pr, Pr) end | decidable.inr Pnin := Union_insert_of_not_mem f Pnin end lemma image_eq_Union_index_image (s : finset A) (f : A → finset B) : Union s f = Union (image f s) id := finset.induction_on s (begin rewrite Union_empty end) (take s1 a Pa IH, by rewrite [image_insert, *Union_insert, IH]) end image -- theory of equivalent classes developed especially for counting purposes section eqv open function open eq.ops variable {A : Type} variable [deceqA : decidable_eq A] include deceqA definition is_eqv_class (f : A → finset A) := ∀ a b, a ∈ f b = (f a = f b) definition is_restricted_cover (s : finset A) (f : A → finset A) := s = Union s f structure partition : Type := (set : finset A) (part : A → finset A) (eqv : is_eqv_class part) (complete : set = Union set part) definition eqv_classes (f : partition) : finset (finset A) := image (partition.part f) (partition.set f) lemma eqv_class_disjoint (f : partition) (a1 a2 : finset A) (Pa1 : a1 ∈ eqv_classes f) (Pa2 : a2 ∈ eqv_classes f) : a1 ≠ a2 → a1 ∩ a2 = ∅ := assume Pne, assert Pe1 : _, from exists_of_mem_image Pa1, obtain g1 Pg1, from Pe1, assert Pe2 : _, from exists_of_mem_image Pa2, obtain g2 Pg2, from Pe2, begin apply inter_eq_empty_of_disjoint, apply disjoint.intro, rewrite [eq.symm (and.right Pg1), eq.symm (and.right Pg2)], intro x, rewrite [*(partition.eqv f)], intro Pxg1, rewrite [Pxg1, and.right Pg1, and.right Pg2], intro Pe, exact absurd Pe Pne end lemma class_equation (f : @partition A _) : card (partition.set f) = nat.Sum (eqv_classes f) card := let s := (partition.set f), p := (partition.part f), img := image p s in calc card s = card (Union s p) : partition.complete f ... = card (Union img id) : image_eq_Union_index_image s p ... = card (Union (eqv_classes f) id) : rfl ... = nat.Sum (eqv_classes f) card : card_Union_of_disjoint _ id (eqv_class_disjoint f) lemma eqv_class_refl {f : A → finset A} (Peqv : is_eqv_class f) : ∀ a, a ∈ f a := take a, by rewrite [Peqv a a] -- make it a little easier to prove union from restriction lemma restriction_imp_union {s : finset A} (f : A → finset A) (Peqv : is_eqv_class f) : (∀ a, a ∈ s → f a ⊆ s) → s = Union s f := assume Psub, ext (take a, iff.intro (assume Pains, begin rewrite [(Union_insert_of_mem f Pains)⁻¹, Union_insert], apply mem_union_l, exact eqv_class_refl Peqv a end) (assume Painu, have Pclass : ∃ x, x ∈ s ∧ a ∈ f x, from iff.elim_left (mem_Union_iff s f _) Painu, obtain x Px, from Pclass, have Pfx : f x ⊆ s, from Psub x (and.left Px), mem_of_subset_of_mem Pfx (and.right Px))) local attribute partition.part [coercion] end eqv end finset namespace list -- useful for inverting function on a finite domain section kth open nat variable {A : Type} definition kth : ∀ k (l : list A), k < length l → A | k [] := begin rewrite length_nil, intro Pltz, exact absurd Pltz !not_lt_zero end | 0 (a::l) := λ P, a | (k+1) (a::l):= by rewrite length_cons; intro Plt; exact kth k l (lt_of_succ_lt_succ Plt) lemma kth_zero_of_cons {a} (l : list A) (P : 0 < length (a::l)) : kth 0 (a::l) P = a := rfl lemma kth_succ_of_cons {a} k (l : list A) (P : k+1 < length (a::l)) : kth (succ k) (a::l) P = kth k l (lt_of_succ_lt_succ P) := rfl variable [deceqA : decidable_eq A] include deceqA -- find_mem can be used to generate a proof of Found if a ∈ l. -- "kth (find a l) l Found" can be used to retrieve what is found. While that may seem -- silly since we already have what we are looking for in "a", -- "let elts := elems A, k := find b (map f elts) in kth k elts Found" -- would allow us to use it as a map to reverse a finite function. lemma find_le_length : ∀ {a} {l : list A}, find a l ≤ length l | a [] := !le.refl | a (b::l) := decidable.rec_on (deceqA a b) (assume Peq, by rewrite [find_cons_of_eq l Peq]; exact !zero_lt_succ) (assume Pne, begin rewrite [find_cons_of_ne l Pne, length_cons], apply succ_lt_succ, apply find_le_length end) lemma find_not_mem : ∀ {a} {l : list A}, find a l = length l → a ∉ l | a [] := assume Peq, !not_mem_nil | a (b::l) := decidable.rec_on (deceqA a b) (assume Peq, by rewrite [find_cons_of_eq l Peq, length_cons]; contradiction) (assume Pne, begin rewrite [find_cons_of_ne l Pne, length_cons, mem_cons_iff], intro Plen, apply (not_or Pne), exact find_not_mem (succ_inj Plen) end) lemma find_mem {a} {l : list A} : a ∈ l → find a l < length l := assume Pin, begin apply lt_of_le_and_ne, apply find_le_length, apply not.intro, intro Peq, exact absurd Pin (find_not_mem Peq) end end kth variables {A B : Type} -- missing in list/basic lemma not_mem_cons_of_ne_and_not_mem {x y : A} {l : list A} : x ≠ y ∧ x ∉ l → x ∉ y::l := assume P, not.intro (assume Pxin, absurd (eq_or_mem_of_mem_cons Pxin) (not_or (and.left P) (and.right P))) lemma ne_and_not_mem_of_not_mem_cons {x y : A} {l : list A} : x ∉ y::l → x ≠ y ∧ x ∉ l := assume P, and.intro (not_eq_of_not_mem P) (not_mem_of_not_mem P) -- missing in list/comb /-lemma for_all_of_all {p : A → Prop} : ∀ {l}, all l p → (∀a, a ∈ l → p a) | [] H := take a Painnil, by contradiction | (a::l) H := begin rewrite all_cons_eq at H, end-/ -- new for list/comb dependent map theory definition dinj (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2 definition dmap (p : A → Prop) [h : decidable_pred p] (f : Π a, p a → B) : list A → list B | [] := [] | (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l) -- properties of dmap section dmap variable {p : A → Prop} variable [h : decidable_pred p] include h variable {f : Π a, p a → B} lemma dmap_nil : dmap p f [] = [] := rfl lemma dmap_cons_of_pos {a : A} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l := λ l, dif_pos P lemma dmap_cons_of_neg {a : A} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l := λ l, dif_neg P lemma mem_of_dmap : ∀ {l : list A} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l | [] := take a Pa Pinnil, by contradiction | (a::l) := take b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin) (assume Pbeqa, begin rewrite [eq.symm Pbeqa, dmap_cons_of_pos Pb], exact !mem_cons end) (assume Pbinl, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa], apply mem_cons_of_mem, exact mem_of_dmap Pb Pbinl end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], exact mem_of_dmap Pb Pbinl end)) lemma map_of_dmap_inv_pos {g : B → A} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) : ∀ {l : list A}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l | [] := assume Pl, by rewrite [dmap_nil, map_nil] | (a::l) := assume Pal, assert Pa : p a, from Pal a !mem_cons, assert Pl : ∀ a, a ∈ l → p a, from take x Pxin, Pal x (mem_cons_of_mem a Pxin), by rewrite [dmap_cons_of_pos Pa, map_cons, Pinv, map_of_dmap_inv_pos Pl] lemma dinj_mem_of_mem_of_dmap (Pdi : dinj p f) : ∀ {l : list A} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l | [] := take a Pa Pinnil, by contradiction | (b::l) := take a Pa Pmap, decidable.rec_on (h b) (λ Pb, begin rewrite (dmap_cons_of_pos Pb) at Pmap, rewrite mem_cons_iff at Pmap, rewrite mem_cons_iff, apply (or_of_or_of_imp_of_imp Pmap), apply Pdi, apply dinj_mem_of_mem_of_dmap Pa end) (λ nPb, begin rewrite (dmap_cons_of_neg nPb) at Pmap, apply mem_cons_of_mem, exact dinj_mem_of_mem_of_dmap Pa Pmap end) lemma dinj_not_mem_of_dmap (Pdi : dinj p f) {l : list A} {a} (Pa : p a) : a ∉ l → (f a Pa) ∉ dmap p f l := not_imp_not_of_imp (dinj_mem_of_mem_of_dmap Pdi Pa) lemma dmap_nodup_of_dinj (Pdi : dinj p f): ∀ {l : list A}, nodup l → nodup (dmap p f l) | [] := take P, nodup.ndnil | (a::l) := take Pnodup, decidable.rec_on (h a) (λ Pa, begin rewrite [dmap_cons_of_pos Pa], apply nodup_cons, apply (dinj_not_mem_of_dmap Pdi Pa), exact not_mem_of_nodup_cons Pnodup, exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup) end) (λ nPa, begin rewrite [dmap_cons_of_neg nPa], exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup) end) end dmap end list namespace list section nodup open function variables {A B : Type} --lemma inj_map_nodup (f : A → B) (inj : injective f) : ∀ (l : list A), nodup l → nodup (map f l) := sorry end nodup end list namespace finset open eq.ops nat -- general version of pigeon hole for finsets. we can specialize it to fintype univ. -- note the classical property of inj is split between inj_on and maps_to, which we -- replace with image subset instead lemma card_le_of_inj {A : Type} [deceqA : decidable_eq A] {B : Type} [deceqB : decidable_eq B] (a : finset A) (b : finset B) : (∃ f : A → B, set.inj_on f (ts a) ∧ (image f a ⊆ b)) → card a ≤ card b := assume Pex, obtain f Pinj, from Pex, assert Psub : _, from and.right Pinj, assert Ple : card (image f a) ≤ card b, from card_le_card_of_subset Psub, by rewrite [(card_image_eq_of_inj_on (and.left Pinj))⁻¹]; exact Ple end finset namespace fintype open eq.ops nat function list finset section card definition card [reducible] (A : Type) [finA : fintype A] := finset.card (@finset.univ A _) lemma card_eq_card_image_of_inj {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {B : Type} [finB : fintype B] [deceqB : decidable_eq B] {f : A → B} : injective f → finset.card (image f univ) = card A := assume Pinj, card_image_eq_of_inj_on (to_set_univ⁻¹ ▸ injective_eq_inj_on_univ ▸ Pinj) -- general version of pigeon hole principle. we will specialize it to less_than type later lemma card_le_of_inj (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (B : Type) [finB : fintype B] [deceqB : decidable_eq B] : (∃ f : A → B, injective f) → card A ≤ card B := assume Pex, obtain f Pinj, from Pex, assert Pinj_on_univ : _, from injective_eq_inj_on_univ ▸ Pinj, assert Pinj_ts : _, from to_set_univ⁻¹ ▸ Pinj_on_univ, assert Psub : (image f univ) ⊆ univ, from !subset_univ, finset.card_le_of_inj univ univ (exists.intro f (and.intro Pinj_ts Psub)) -- used to prove that inj ∧ eq card => surj lemma univ_of_card_eq_univ {A : Type} [finA : fintype A] [deceqA : decidable_eq A] {s : finset A} : finset.card s = card A → s = univ := assume Pcardeq, ext (take a, assert D : decidable (a ∈ s), from decidable_mem a s, begin apply iff.intro, intro ain, apply mem_univ, intro ain, cases D with Pin Pnin, exact Pin, assert Pplus1 : finset.card (insert a s) = finset.card s + 1, exact card_insert_of_not_mem Pnin, rewrite Pcardeq at Pplus1, assert Ple : finset.card (insert a s) ≤ card A, apply card_le_card_of_subset, apply subset_univ, rewrite Pplus1 at Ple, exact absurd (lt_of_succ_lt_succ Ple) !lt.irrefl end) end card -- this theory is developed so it would be easier to establish permutations on finite -- types. In general we could hypothesize a finset of card n but since all Sn groups are -- isomorphic there is no reason not to use a concrete list of nats. Especially since -- we now conflate the object with the index we may be able to make the construction of -- the inverse simpler, but that remains to be seen. structure less_than (n : nat) := (val : nat) (lt : val < n) definition less_than.has_decidable_eq [instance] (n : nat) : decidable_eq (less_than n) := take i j, less_than.destruct i (λ ival iltn, less_than.destruct j (λ jval jltn, decidable.rec_on (nat.has_decidable_eq ival jval) (assume Pe, decidable.inl (dcongr_arg2 less_than.mk Pe !proof_irrel)) (assume Pne, decidable.inr (not.intro (assume Pmkeq, less_than.no_confusion Pmkeq (assume Pe, absurd Pe Pne)))))) namespace less_than open decidable -- new tactic makes the proof above more succinct example (n : nat) : ∀ (i j : less_than n), decidable (i = j) | (mk ival ilt) (mk jval jlt) := match nat.has_decidable_eq ival jval with | inl veq := inl (by substvars) | inr vne := inr (by intro h; injection h; contradiction) end end less_than lemma lt_dinj (n : nat) : dinj (λ i, i < n) less_than.mk := take a1 a2 Pa1 Pa2 Pmkeq, less_than.no_confusion Pmkeq (λ Pe Pqe, Pe) lemma lt_inv (n i : nat) (Plt : i < n) : less_than.val (less_than.mk i Plt) = i := rfl definition upto [reducible] (n : nat) : list (less_than n) := dmap (λ i, i < n) less_than.mk (list.upto n) lemma upto_nodup (n : nat) : nodup (upto n) := dmap_nodup_of_dinj (lt_dinj n) (list.nodup_upto n) check @less_than.mk lemma upto_complete (n : nat) : ∀ (i : less_than n), i ∈ upto n := take i, less_than.destruct i ( take ival Piltn, assert Pin : ival ∈ list.upto n, from mem_upto_of_lt Piltn, mem_of_dmap Piltn Pin) lemma upto_nil : upto 0 = [] := by rewrite [↑upto, list.upto_nil, dmap_nil] lemma upto_map_eq_upto (n : nat) : map less_than.val (upto n) = list.upto n := map_of_dmap_inv_pos (lt_inv n) (@lt_of_mem_upto n) lemma upto_length (n : nat) : length (upto n) = n := calc length (upto n) = length (list.upto n) : (upto_map_eq_upto n ▸ len_map less_than.val (upto n))⁻¹ ... = n : list.length_upto n definition fin_lt_type [instance] (n : nat) : fintype (less_than n) := fintype.mk (upto n) (upto_nodup n) (upto_complete n) local attribute less_than.val [coercion] -- alternative definitions of upto not needed for anything definition lt_collect (n : nat) (l : list (less_than n)) (i : nat) := if H : (i < n) then cons (less_than.mk i H) l else l definition upto₁ (n : nat) : list (less_than n) := foldl (lt_collect n) [] (list.upto n) definition lt_cons (n : nat) (i : nat) (l : list (less_than n)) : list (less_than n) := if H : (i < n) then cons (less_than.mk i H) l else l definition upto₂ (n : nat) : list (less_than n) := foldr (lt_cons n) [] (list.upto n) section pigeon_hole variable {n : nat} lemma card_univ_lt_type : card (less_than n) = n := upto_length n variable {m : nat} theorem pigeon_hole : m < n → ¬ (∃ f : less_than n → less_than m, injective f) := assume Pmltn, not.intro (assume Pex, absurd Pmltn (not_lt_of_le (calc n = card (less_than n) : card_univ_lt_type ... ≤ card (less_than m) : card_le_of_inj (less_than n) (less_than m) Pex ... = m : card_univ_lt_type))) end pigeon_hole end fintype
6bc018ddd0819f54c90bfeeacc17dd995e13af17
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/Structure.lean
e03bc92fed2b408884319fb5de9b6a603204c7ea
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,549
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 Helper functions for retrieving structure information. -/ import Lean.Environment import Lean.ProjFns namespace Lean structure StructureFieldInfo where fieldName : Name projFn : Name subobject? : Option Name -- It is `some parentStructName` if it is a subobject, and `parentStructName` is the name of the parent structure deriving Inhabited, Repr def StructureFieldInfo.lt (i₁ i₂ : StructureFieldInfo) : Bool := Name.quickLt i₁.fieldName i₂.fieldName structure StructureInfo where structName : Name fieldNames : Array Name := #[] -- sorted by field position in the structure fieldInfo : Array StructureFieldInfo := #[] -- sorted by `fieldName` deriving Inhabited def StructureInfo.lt (i₁ i₂ : StructureInfo) : Bool := Name.quickLt i₁.structName i₂.structName /-- Auxiliary state for structures defined in the current module. -/ private structure StructureState where map : Std.PersistentHashMap Name StructureInfo := {} deriving Inhabited builtin_initialize structureExt : SimplePersistentEnvExtension StructureInfo StructureState ← registerSimplePersistentEnvExtension { name := `structExt addImportedFn := fun _ => {} addEntryFn := fun s e => { s with map := s.map.insert e.structName e } toArrayFn := fun es => es.toArray.qsort StructureInfo.lt } structure StructureDescr where structName : Name fields : Array StructureFieldInfo -- Should use the order the field appear in the constructor. deriving Inhabited def registerStructure (env : Environment) (e : StructureDescr) : Environment := structureExt.addEntry env { structName := e.structName fieldNames := e.fields.map fun e => e.fieldName fieldInfo := e.fields.qsort StructureFieldInfo.lt } def getStructureInfo? (env : Environment) (structName : Name) : Option StructureInfo := match env.getModuleIdxFor? structName with | some modIdx => structureExt.getModuleEntries env modIdx |>.binSearch { structName } StructureInfo.lt | none => structureExt.getState env |>.map.find? structName def getStructureCtor (env : Environment) (constName : Name) : ConstructorVal := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctorName], .. }) => match env.find? ctorName with | some (ConstantInfo.ctorInfo val) => val | _ => panic! "ill-formed environment" | _ => panic! "structure expected" /-- Get direct field names for the given structure. -/ def getStructureFields (env : Environment) (structName : Name) : Array Name := if let some info := getStructureInfo? env structName then info.fieldNames else panic! "structure expected" def getFieldInfo? (env : Environment) (structName : Name) (fieldName : Name) : Option StructureFieldInfo := if let some info := getStructureInfo? env structName then info.fieldInfo.binSearch { fieldName := fieldName, projFn := arbitrary, subobject? := none } StructureFieldInfo.lt else none /-- If `fieldName` represents the relation to a parent structure `S`, return `S` -/ def isSubobjectField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some fieldInfo := getFieldInfo? env structName fieldName then fieldInfo.subobject? else none /-- Return immediate parent structures -/ def getParentStructures (env : Environment) (structName : Name) : Array Name := let fieldNames := getStructureFields env structName; fieldNames.foldl (init := #[]) fun acc fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => acc.push parentStructName | none => acc /-- Return all parent structures -/ partial def getAllParentStructures (env : Environment) (structName : Name) : Array Name := visit structName |>.run #[] |>.2 where visit (structName : Name) : StateT (Array Name) Id Unit := do for p in getParentStructures env structName do modify fun s => s.push p visit p /-- `findField? env S fname`. If `fname` is defined in a parent `S'` of `S`, return `S'` -/ partial def findField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if (getStructureFields env structName).contains fieldName then some structName else getParentStructures env structName |>.findSome? fun parentStructName => findField? env parentStructName fieldName private partial def getStructureFieldsFlattenedAux (env : Environment) (structName : Name) (fullNames : Array Name) (includeSubobjectFields : Bool) : Array Name := (getStructureFields env structName).foldl (init := fullNames) fun fullNames fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => let fullNames := if includeSubobjectFields then fullNames.push fieldName else fullNames getStructureFieldsFlattenedAux env parentStructName fullNames includeSubobjectFields | none => fullNames.push fieldName def getStructureFieldsFlattened (env : Environment) (structName : Name) (includeSubobjectFields := true) : Array Name := getStructureFieldsFlattenedAux env structName #[] includeSubobjectFields /-- Return true if `constName` is the name of an inductive datatype created using the `structure` or `class` commands. We perform the check by testing whether auxiliary projection functions have been created. -/ def isStructure (env : Environment) (constName : Name) : Bool := getStructureInfo? env constName |>.isSome def getProjFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some fieldInfo := getFieldInfo? env structName fieldName then some fieldInfo.projFn else none partial def getPathToBaseStructureAux (env : Environment) (baseStructName : Name) (structName : Name) (path : List Name) : Option (List Name) := if baseStructName == structName then some path.reverse else let fieldNames := getStructureFields env structName; fieldNames.findSome? fun fieldName => match isSubobjectField? env structName fieldName with | none => none | some parentStructName => match getProjFnForField? env structName fieldName with | none => none | some projFn => getPathToBaseStructureAux env baseStructName parentStructName (projFn :: path) /-- If `baseStructName` is an ancestor structure for `structName`, then return a sequence of projection functions to go from `structName` to `baseStructName`. -/ def getPathToBaseStructure? (env : Environment) (baseStructName : Name) (structName : Name) : Option (List Name) := getPathToBaseStructureAux env baseStructName structName [] /-- Return true iff `constName` is the a non-recursive inductive datatype that has only one constructor. -/ def isStructureLike (env : Environment) (constName : Name) : Bool := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctor], .. }) => true | _ => false /-- Return number of fields for a structure-like type -/ def getStructureLikeNumFields (env : Environment) (constName : Name) : Nat := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctor], .. }) => match env.find? ctor with | some (ConstantInfo.ctorInfo { numFields := n, .. }) => n | _ => 0 | _ => 0 end Lean
d4d4f6eab8e402e7ce1e6e6a1d0a87de5cad6d35
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/order/proj_Icc.lean
a032314bb4a6d8d676c3ee9bf9dc8adee1dd3bf8
[ "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
2,403
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Patrick Massot -/ import data.set.intervals.proj_Icc import topology.algebra.order.basic /-! # Projection onto a closed interval In this file we prove that the projection `set.proj_Icc f a b h` is a quotient map, and use it to show that `Icc_extend h f` is continuous if and only if `f` is continuous. -/ open set filter open_locale filter topological_space variables {α β γ : Type*} [linear_order α] [topological_space γ] {a b c : α} {h : a ≤ b} lemma filter.tendsto.Icc_extend (f : γ → Icc a b → β) {z : γ} {l : filter α} {l' : filter β} (hf : tendsto ↿f (𝓝 z ×ᶠ l.map (proj_Icc a b h)) l') : tendsto ↿(Icc_extend h ∘ f) (𝓝 z ×ᶠ l) l' := show tendsto (↿f ∘ prod.map id (proj_Icc a b h)) (𝓝 z ×ᶠ l) l', from hf.comp $ tendsto_id.prod_map tendsto_map variables [topological_space α] [order_topology α] [topological_space β] @[continuity] lemma continuous_proj_Icc : continuous (proj_Icc a b h) := (continuous_const.max $ continuous_const.min continuous_id).subtype_mk _ lemma quotient_map_proj_Icc : quotient_map (proj_Icc a b h) := quotient_map_iff.2 ⟨proj_Icc_surjective h, λ s, ⟨λ hs, hs.preimage continuous_proj_Icc, λ hs, ⟨_, hs, by { ext, simp }⟩⟩⟩ @[simp] lemma continuous_Icc_extend_iff {f : Icc a b → β} : continuous (Icc_extend h f) ↔ continuous f := quotient_map_proj_Icc.continuous_iff.symm /-- See Note [continuity lemma statement]. -/ lemma continuous.Icc_extend {f : γ → Icc a b → β} {g : γ → α} (hf : continuous ↿f) (hg : continuous g) : continuous (λ a, Icc_extend h (f a) (g a)) := hf.comp $ continuous_id.prod_mk $ continuous_proj_Icc.comp hg /-- A useful special case of `continuous.Icc_extend`. -/ @[continuity] lemma continuous.Icc_extend' {f : Icc a b → β} (hf : continuous f) : continuous (Icc_extend h f) := hf.comp continuous_proj_Icc lemma continuous_at.Icc_extend {x : γ} (f : γ → Icc a b → β) {g : γ → α} (hf : continuous_at ↿f (x, proj_Icc a b h (g x))) (hg : continuous_at g x) : continuous_at (λ a, Icc_extend h (f a) (g a)) x := show continuous_at (↿f ∘ λ x, (x, proj_Icc a b h (g x))) x, from continuous_at.comp hf $ continuous_at_id.prod $ continuous_proj_Icc.continuous_at.comp hg
cbef957080a22dcc4fead8351cdd414b470974b6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/list/zip.lean
a47215800747839e5d8ac959cc7a52c3ec24734a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
14,748
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.basic /-! # zip & unzip This file provides results about `list.zip_with`, `list.zip` and `list.unzip` (definitions are in core Lean). `zip_with f l₁ l₂` applies `f : α → β → γ` pointwise to a list `l₁ : list α` and `l₂ : list β`. It applies, until one of the lists is exhausted. For example, `zip_with f [0, 1, 2] [6.28, 31] = [f 0 6.28, f 1 31]`. `zip` is `zip_with` applied to `prod.mk`. For example, `zip [a₁, a₂] [b₁, b₂, b₃] = [(a₁, b₁), (a₂, b₂)]`. `unzip` undoes `zip`. For example, `unzip [(a₁, b₁), (a₂, b₂)] = ([a₁, a₂], [b₁, b₂])`. -/ universe u open nat namespace list variables {α : Type u} {β γ δ : Type*} @[simp] theorem zip_with_cons_cons (f : α → β → γ) (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ := rfl @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_with_nil_left (f : α → β → γ) (l) : zip_with f [] l = [] := rfl @[simp] theorem zip_with_nil_right (f : α → β → γ) (l) : zip_with f l [] = [] := by cases l; refl @[simp] lemma zip_with_eq_nil_iff {f : α → β → γ} {l l'} : zip_with f l l' = [] ↔ l = [] ∨ l' = [] := by { cases l; cases l'; simp } @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := zip_with_nil_right _ l @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip_with (f : α → β → γ) : ∀ (l₁ : list α) (l₂ : list β), length (zip_with f l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, min_zero, zip_with_nil_right] | (a::l₁) (b::l₂) := by by simp [length, zip_cons_cons, length_zip_with l₁ l₂, min_add_add_right] @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) := length_zip_with _ lemma lt_length_left_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β} (h : i < (zip_with f l l').length) : i < l.length := by { rw [length_zip_with, lt_min_iff] at h, exact h.left } lemma lt_length_right_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β} (h : i < (zip_with f l l').length) : i < l'.length := by { rw [length_zip_with, lt_min_iff] at h, exact h.right } lemma lt_length_left_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) : i < l.length := lt_length_left_of_zip_with h lemma lt_length_right_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) : i < l'.length := lt_length_right_of_zip_with h theorem zip_append : ∀ {l₁ r₁ : list α} {l₂ r₂ : list β} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] r₁ l₂ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ r₁ [] r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) r₁ (b::l₂) r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] @[simp] lemma zip_with_map {μ} (f : γ → δ → μ) (g : α → γ) (h : β → δ) (as : list α) (bs : list β) : zip_with f (as.map g) (bs.map h) = zip_with (λ a b, f (g a) (h b)) as bs := begin induction as generalizing bs, { simp }, { cases bs; simp * } end lemma zip_with_map_left (f : α → β → γ) (g : δ → α) (l : list δ) (l' : list β) : zip_with f (l.map g) l' = zip_with (f ∘ g) l l' := by { convert (zip_with_map f g id l l'), exact eq.symm (list.map_id _) } lemma zip_with_map_right (f : α → β → γ) (l : list α) (g : δ → β) (l' : list δ) : zip_with f l (l'.map g) = zip_with (λ x, f x ∘ g) l l' := by { convert (list.zip_with_map f id g l l'), exact eq.symm (list.map_id _) } theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl lemma map_zip_with {δ : Type*} (f : α → β) (g : γ → δ → α) (l : list γ) (l' : list δ) : map f (zip_with g l l') = zip_with (λ x y, f (g x y)) l l' := begin induction l with hd tl hl generalizing l', { simp }, { cases l', { simp }, { simp [hl] } } end theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] theorem map_fst_zip : ∀ (l₁ : list α) (l₂ : list β), l₁.length ≤ l₂.length → map prod.fst (zip l₁ l₂) = l₁ | [] bs _ := rfl | (a :: as) (b :: bs) h := by { simp at h, simp! * } | (a :: as) [] h := by { simp at h, contradiction } theorem map_snd_zip : ∀ (l₁ : list α) (l₂ : list β), l₂.length ≤ l₁.length → map prod.snd (zip l₁ l₂) = l₂ | _ [] _ := by { rw zip_nil_right, refl } | [] (b :: bs) h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! * } @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] lemma zip_of_prod {l : list α} {l' : list β} {lp : list (α × β)} (hl : lp.map prod.fst = l) (hr : lp.map prod.snd = l') : lp = l.zip l' := by rw [←hl, ←hr, ←zip_unzip lp, ←unzip_left, ←unzip_right, zip_unzip, zip_unzip] lemma map_prod_left_eq_zip {l : list α} (f : α → β) : l.map (λ x, (x, f x)) = l.zip (l.map f) := by { rw ←zip_map', congr, exact map_id _ } lemma map_prod_right_eq_zip {l : list α} (f : α → β) : l.map (λ x, (f x, x)) = (l.map f).zip l := by { rw ←zip_map', congr, exact map_id _ } lemma zip_with_comm (f : α → α → β) (comm : ∀ (x y : α), f x y = f y x) (l l' : list α) : zip_with f l l' = zip_with f l' l := begin induction l with hd tl hl generalizing l', { simp }, { cases l', { simp }, { simp [comm, hl] } } end instance (f : α → α → β) [is_symm_op α β f] : is_symm_op (list α) (list β) (zip_with f) := ⟨zip_with_comm f is_symm_op.symm_op⟩ @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] lemma nth_zip_with (f : α → β → γ) (l₁ : list α) (l₂ : list β) (i : ℕ) : (zip_with f l₁ l₂).nth i = ((l₁.nth i).map f).bind (λ g, (l₂.nth i).map g) := begin induction l₁ generalizing l₂ i, { simp [zip_with, (<*>)] }, { cases l₂; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'], { cases ((l₁_hd :: l₁_tl).nth i); refl }, { cases i; simp only [option.map_some', nth, option.some_bind', *] } } end lemma nth_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (z : γ) (i : ℕ) : (zip_with f l₁ l₂).nth i = some z ↔ ∃ x y, l₁.nth i = some x ∧ l₂.nth i = some y ∧ f x y = z := begin induction l₁ generalizing l₂ i, { simp [zip_with] }, { cases l₂; simp only [zip_with, nth, exists_false, and_false, false_and], cases i; simp *, }, end lemma nth_zip_eq_some (l₁ : list α) (l₂ : list β) (z : α × β) (i : ℕ) : (zip l₁ l₂).nth i = some z ↔ l₁.nth i = some z.1 ∧ l₂.nth i = some z.2 := begin cases z, rw [zip, nth_zip_with_eq_some], split, { rintro ⟨x, y, h₀, h₁, h₂⟩, cc }, { rintro ⟨h₀, h₁⟩, exact ⟨_,_,h₀,h₁,rfl⟩ } end @[simp] lemma nth_le_zip_with {f : α → β → γ} {l : list α} {l' : list β} {i : ℕ} {h : i < (zip_with f l l').length} : (zip_with f l l').nth_le i h = f (l.nth_le i (lt_length_left_of_zip_with h)) (l'.nth_le i (lt_length_right_of_zip_with h)) := begin rw [←option.some_inj, ←nth_le_nth, nth_zip_with_eq_some], refine ⟨l.nth_le i (lt_length_left_of_zip_with h), l'.nth_le i (lt_length_right_of_zip_with h), nth_le_nth _, _⟩, simp only [←nth_le_nth, eq_self_iff_true, and_self] end @[simp] lemma nth_le_zip {l : list α} {l' : list β} {i : ℕ} {h : i < (zip l l').length} : (zip l l').nth_le i h = (l.nth_le i (lt_length_left_of_zip h), l'.nth_le i (lt_length_right_of_zip h)) := nth_le_zip_with lemma mem_zip_inits_tails {l : list α} {init tail : list α} : (init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l := begin induction l generalizing init tail; simp_rw [tails, inits, zip_cons_cons], { simp }, { split; rw [mem_cons_iff, zip_map_left, mem_map, prod.exists], { rintros (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩), { simp }, { simp [l_ih.mp h], }, }, { cases init, { simp }, { intro h, right, use [init_tl, tail], simp * at *, }, }, }, end lemma map_uncurry_zip_eq_zip_with (f : α → β → γ) (l : list α) (l' : list β) : map (function.uncurry f) (l.zip l') = zip_with f l l' := begin induction l with hd tl hl generalizing l', { simp }, { cases l' with hd' tl', { simp }, { simp [hl] } } end @[simp] lemma sum_zip_with_distrib_left {γ : Type*} [semiring γ] (f : α → β → γ) (n : γ) (l : list α) (l' : list β) : (l.zip_with (λ x y, n * f x y) l').sum = n * (l.zip_with f l').sum := begin induction l with hd tl hl generalizing f n l', { simp }, { cases l' with hd' tl', { simp, }, { simp [hl, mul_add] } } end section distrib /-! ### Operations that can be applied before or after a `zip_with` -/ variables (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ) lemma zip_with_distrib_take : (zip_with f l l').take n = zip_with f (l.take n) (l'.take n) := begin induction l with hd tl hl generalizing l' n, { simp }, { cases l', { simp }, { cases n, { simp }, { simp [hl] } } } end lemma zip_with_distrib_drop : (zip_with f l l').drop n = zip_with f (l.drop n) (l'.drop n) := begin induction l with hd tl hl generalizing l' n, { simp }, { cases l', { simp }, { cases n, { simp }, { simp [hl] } } } end lemma zip_with_distrib_tail : (zip_with f l l').tail = zip_with f l.tail l'.tail := by simp_rw [←drop_one, zip_with_distrib_drop] lemma zip_with_append (f : α → β → γ) (l la : list α) (l' lb : list β) (h : l.length = l'.length) : zip_with f (l ++ la) (l' ++ lb) = zip_with f l l' ++ zip_with f la lb := begin induction l with hd tl hl generalizing l', { have : l' = [] := eq_nil_of_length_eq_zero (by simpa using h.symm), simp [this], }, { cases l', { simpa using h }, { simp only [add_left_inj, length] at h, simp [hl _ h] } } end lemma zip_with_distrib_reverse (h : l.length = l'.length) : (zip_with f l l').reverse = zip_with f l.reverse l'.reverse := begin induction l with hd tl hl generalizing l', { simp }, { cases l' with hd' tl', { simp }, { simp only [add_left_inj, length] at h, have : tl.reverse.length = tl'.reverse.length := by simp [h], simp [hl _ h, zip_with_append _ _ _ _ _ this] } } end end distrib end list
2705d33d732b468951cf82570cdfd38291fd4f91
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/strong_epi_auto.lean
04685479f43cf3b81759489f241652dcd93da4ee
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,567
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.arrow import Mathlib.PostPort universes v u l namespace Mathlib /-! # Strong epimorphisms In this file, we define strong epimorphisms. A strong epimorphism is an epimorphism `f`, such that for every commutative square with `f` at the top and a monomorphism at the bottom, there is a diagonal morphism making the two triangles commute. This lift is necessarily unique (as shown in `comma.lean`). ## Main results Besides the definition, we show that * the composition of two strong epimorphisms is a strong epimorphism, * if `f ≫ g` is a strong epimorphism, then so is `g`, * if `f` is both a strong epimorphism and a monomorphism, then it is an isomorphism ## Future work There is also the dual notion of strong monomorphism. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ namespace category_theory /-- A strong epimorphism `f` is an epimorphism such that every commutative square with `f` at the top and a monomorphism at the bottom has a lift. -/ class strong_epi {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) where epi : epi f has_lift : ∀ {X Y : C} {u : P ⟶ X} {v : Q ⟶ Y} {z : X ⟶ Y} [_inst_2 : mono z] (h : u ≫ z = f ≫ v), arrow.has_lift (arrow.hom_mk' h) protected instance epi_of_strong_epi {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) [strong_epi f] : epi f := strong_epi.epi /-- The composition of two strong epimorphisms is a strong epimorphism. -/ theorem strong_epi_comp {C : Type u} [category C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) [strong_epi f] [strong_epi g] : strong_epi (f ≫ g) := sorry /-- If `f ≫ g` is a strong epimorphism, then so is g. -/ theorem strong_epi_of_strong_epi {C : Type u} [category C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) [strong_epi (f ≫ g)] : strong_epi g := sorry /-- An isomorphism is in particular a strong epimorphism. -/ protected instance strong_epi_of_is_iso {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) [is_iso f] : strong_epi f := sorry /-- A strong epimorphism that is a monomorphism is an isomorphism. -/ def is_iso_of_mono_of_strong_epi {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) [mono f] [strong_epi f] : is_iso f := is_iso.mk (arrow.lift (arrow.hom_mk' sorry)) end Mathlib
f0c93120536b589c644c65344cad15ca49ab773a
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/order/jordan_holder.lean
0523ca567bd94aa4d97b3b6ff41adc4b7c089468
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,826
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import order.lattice import data.list.sort import data.equiv.fin import data.equiv.functor /-! # Jordan-Hölder Theorem This file proves the Jordan Hölder theorem for a `jordan_holder_lattice`, a class also defined in this file. Examples of `jordan_holder_lattice` include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. Using this approach the theorem need not be proved seperately for both groups and modules, the proof in this file can be applied to both. ## Main definitions The main definitions in this file are `jordan_holder_lattice` and `composition_series`, and the relation `equivalent` on `composition_series` A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. A `composition_series X` is a finite nonempty series of elements of the lattice `X` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i, s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` ## Main theorems The main theorem is `composition_series.jordan_holder`, which says that if two composition series have the same least element and the same largest element, then they are `equivalent`. ## TODO Provide instances of `jordan_holder_lattice` for both submodules and subgroups, and potentially for modular lattices. It is not entirely clear how this should be done. Possibly there should be no global instances of `jordan_holder_lattice`, and the instances should only be defined locally in order to prove the Jordan-Hölder theorem for modules/groups and the API should be transferred because many of the theorems in this file will have stronger versions for modules. There will also need to be an API for mapping composition series across homomorphisms. It is also probably possible to provide an instance of `jordan_holder_lattice` for any `modular_lattice`, and in this case the Jordan-Hölder theorem will say that there is a well defined notion of length of a modular lattice. However an instance of `jordan_holder_lattice` for a modular lattice will not be able to contain the correct notion of isomorphism for modules, so a separate instance for modules will still be required and this will clash with the instance for modular lattices, and so at least one of these instances should not be a global instance. -/ universe u open set /-- A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. Examples include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. -/ class jordan_holder_lattice (X : Type u) [lattice X] := (is_maximal : X → X → Prop) (lt_of_is_maximal : ∀ {x y}, is_maximal x y → x < y) (sup_eq_of_is_maximal : ∀ {x y z}, is_maximal x z → is_maximal y z → x ≠ y → x ⊔ y = z) (is_maximal_inf_left_of_is_maximal_sup : ∀ {x y}, is_maximal x (x ⊔ y) → is_maximal y (x ⊔ y) → is_maximal (x ⊓ y) x) (iso : (X × X) → (X × X) → Prop) (iso_symm : ∀ {x y}, iso x y → iso y x) (iso_trans : ∀ {x y z}, iso x y → iso y z → iso x z) (second_iso : ∀ {x y}, is_maximal x (x ⊔ y) → iso (x, x ⊔ y) (x ⊓ y, y)) namespace jordan_holder_lattice variables {X : Type u} [lattice X] [jordan_holder_lattice X] lemma is_maximal_inf_right_of_is_maximal_sup {x y : X} (hxz : is_maximal x (x ⊔ y)) (hyz : is_maximal y (x ⊔ y)) : is_maximal (x ⊓ y) y := begin rw [inf_comm], rw [sup_comm] at hxz hyz, exact is_maximal_inf_left_of_is_maximal_sup hyz hxz end lemma is_maximal_of_eq_inf (x b : X) {a y : X} (ha : x ⊓ y = a) (hxy : x ≠ y) (hxb : is_maximal x b) (hyb : is_maximal y b) : is_maximal a y := begin have hb : x ⊔ y = b, from sup_eq_of_is_maximal hxb hyb hxy, substs a b, exact is_maximal_inf_right_of_is_maximal_sup hxb hyb end lemma second_iso_of_eq {x y a b : X} (hm : is_maximal x a) (ha : x ⊔ y = a) (hb : x ⊓ y = b) : iso (x, a) (b, y) := by substs a b; exact second_iso hm lemma is_maximal.iso_refl {x y : X} (h : is_maximal x y) : iso (x, y) (x, y) := second_iso_of_eq h (sup_eq_right.2 (le_of_lt (lt_of_is_maximal h))) (inf_eq_left.2 (le_of_lt (lt_of_is_maximal h))) end jordan_holder_lattice open jordan_holder_lattice attribute [symm] iso_symm attribute [trans] iso_trans /-- A `composition_series X` is a finite nonempty series of elements of a `jordan_holder_lattice` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. -/ structure composition_series (X : Type u) [lattice X] [jordan_holder_lattice X] : Type u := (length : ℕ) (series : fin (length + 1) → X) (step' : ∀ i : fin length, is_maximal (series i.cast_succ) (series i.succ)) namespace composition_series variables {X : Type u} [lattice X] [jordan_holder_lattice X] instance : has_coe_to_fun (composition_series X) := { F := _, coe := composition_series.series } instance [inhabited X] : inhabited (composition_series X) := ⟨{ length := 0, series := λ _, default X, step' := λ x, x.elim0 }⟩ variables {X} lemma step (s : composition_series X) : ∀ i : fin s.length, is_maximal (s i.cast_succ) (s i.succ) := s.step' @[simp] lemma coe_fn_mk (length : ℕ) (series step) : (@composition_series.mk X _ _ length series step : fin length.succ → X) = series := rfl theorem lt_succ (s : composition_series X) (i : fin s.length) : s i.cast_succ < s i.succ := lt_of_is_maximal (s.step _) protected theorem strict_mono (s : composition_series X) : strict_mono s := fin.strict_mono_iff_lt_succ.2 (λ i h, s.lt_succ ⟨i, nat.lt_of_succ_lt_succ h⟩) protected theorem injective (s : composition_series X) : function.injective s := s.strict_mono.injective @[simp] protected theorem inj (s : composition_series X) {i j : fin s.length.succ} : s i = s j ↔ i = j := s.injective.eq_iff instance : has_mem X (composition_series X) := ⟨λ x s, x ∈ set.range s⟩ lemma mem_def {x : X} {s : composition_series X} : x ∈ s ↔ x ∈ set.range s := iff.rfl lemma total {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) : x ≤ y ∨ y ≤ x := begin rcases set.mem_range.1 hx with ⟨i, rfl⟩, rcases set.mem_range.1 hy with ⟨j, rfl⟩, rw [s.strict_mono.le_iff_le, s.strict_mono.le_iff_le], exact le_total i j end /-- The ordered `list X` of elements of a `composition_series X`. -/ def to_list (s : composition_series X) : list X := list.of_fn s /-- Two `composition_series` are equal if they are the same length and have the same `i`th element for every `i` -/ lemma ext_fun {s₁ s₂ : composition_series X} (hl : s₁.length = s₂.length) (h : ∀ i, s₁ i = s₂ (fin.cast (congr_arg nat.succ hl) i)) : s₁ = s₂ := begin cases s₁, cases s₂, dsimp at *, subst hl, simpa [function.funext_iff] using h end @[simp] lemma length_to_list (s : composition_series X) : s.to_list.length = s.length + 1 := by rw [to_list, list.length_of_fn] lemma to_list_ne_nil (s : composition_series X) : s.to_list ≠ [] := by rw [← list.length_pos_iff_ne_nil, length_to_list]; exact nat.succ_pos _ lemma to_list_injective : function.injective (@composition_series.to_list X _ _) := λ s₁ s₂ (h : list.of_fn s₁ = list.of_fn s₂), have h₁ : s₁.length = s₂.length, from nat.succ_injective ((list.length_of_fn s₁).symm.trans $ (congr_arg list.length h).trans $ list.length_of_fn s₂), have h₂ : ∀ i : fin s₁.length.succ, (s₁ i) = s₂ (fin.cast (congr_arg nat.succ h₁) i), begin assume i, rw [← list.nth_le_of_fn s₁ i, ← list.nth_le_of_fn s₂], simp [h] end, begin cases s₁, cases s₂, dsimp at *, subst h₁, simp only [heq_iff_eq, eq_self_iff_true, true_and], simp only [fin.cast_refl] at h₂, exact funext h₂ end lemma chain'_to_list (s : composition_series X) : list.chain' is_maximal s.to_list := list.chain'_iff_nth_le.2 begin assume i hi, simp only [to_list, list.nth_le_of_fn'], rw [length_to_list] at hi, exact s.step ⟨i, hi⟩ end lemma to_list_sorted (s : composition_series X) : s.to_list.sorted (<) := list.pairwise_iff_nth_le.2 (λ i j hi hij, begin dsimp [to_list], rw [list.nth_le_of_fn', list.nth_le_of_fn'], exact s.strict_mono hij end) lemma to_list_nodup (s : composition_series X) : s.to_list.nodup := list.nodup_iff_nth_le_inj.2 (λ i j hi hj, begin delta to_list, rw [list.nth_le_of_fn', list.nth_le_of_fn', s.injective.eq_iff, fin.ext_iff, fin.coe_mk, fin.coe_mk], exact id end) @[simp] lemma mem_to_list {s : composition_series X} {x : X} : x ∈ s.to_list ↔ x ∈ s := by rw [to_list, list.mem_of_fn, mem_def] /-- Make a `composition_series X` from the ordered list of its elements. -/ def of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : composition_series X := { length := l.length - 1, series := λ i, l.nth_le i begin conv_rhs { rw ← nat.sub_add_cancel (list.length_pos_of_ne_nil hl) }, exact i.2 end, step' := λ ⟨i, hi⟩, list.chain'_iff_nth_le.1 hc i hi } lemma length_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : (of_list l hl hc).length = l.length - 1 := rfl lemma of_list_to_list (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := begin refine ext_fun _ _, { rw [length_of_list, length_to_list, nat.succ_sub_one] }, { rintros ⟨i, hi⟩, dsimp [of_list, to_list], rw [list.nth_le_of_fn'] } end @[simp] lemma of_list_to_list' (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := of_list_to_list s @[simp] lemma to_list_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : to_list (of_list l hl hc) = l := begin refine list.ext_le _ _, { rw [length_to_list, length_of_list, nat.sub_add_cancel (list.length_pos_of_ne_nil hl)] }, { assume i hi hi', dsimp [of_list, to_list], rw [list.nth_le_of_fn'], refl } end /-- Two `composition_series` are equal if they have the same elements. See also `ext_fun`. -/ @[ext] lemma ext {s₁ s₂ : composition_series X} (h : ∀ x, x ∈ s₁ ↔ x ∈ s₂) : s₁ = s₂ := to_list_injective $ list.eq_of_perm_of_sorted (by classical; exact list.perm_of_nodup_nodup_to_finset_eq s₁.to_list_nodup s₂.to_list_nodup (finset.ext $ by simp *)) s₁.to_list_sorted s₂.to_list_sorted /-- The largest element of a `composition_series` -/ def top (s : composition_series X) : X := s (fin.last _) lemma top_mem (s : composition_series X) : s.top ∈ s := mem_def.2 (set.mem_range.2 ⟨fin.last _, rfl⟩) @[simp] lemma le_top {s : composition_series X} (i : fin (s.length + 1)) : s i ≤ s.top := s.strict_mono.monotone (fin.le_last _) lemma le_top_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : x ≤ s.top := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ le_top _ /-- The smallest element of a `composition_series` -/ def bot (s : composition_series X) : X := s 0 lemma bot_mem (s : composition_series X) : s.bot ∈ s := mem_def.2 (set.mem_range.2 ⟨0, rfl⟩) @[simp] lemma bot_le {s : composition_series X} (i : fin (s.length + 1)) : s.bot ≤ s i := s.strict_mono.monotone (fin.zero_le _) lemma bot_le_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : s.bot ≤ x := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ bot_le _ lemma length_pos_of_mem_ne {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : 0 < s.length := let ⟨i, hi⟩ := hx, ⟨j, hj⟩ := hy in have hij : i ≠ j, from mt s.inj.2 $ λ h, hxy (hi ▸ hj ▸ h), hij.lt_or_lt.elim (λ hij, (lt_of_le_of_lt (zero_le i) (lt_of_lt_of_le hij (nat.le_of_lt_succ j.2)))) (λ hji, (lt_of_le_of_lt (zero_le j) (lt_of_lt_of_le hji (nat.le_of_lt_succ i.2)))) lemma forall_mem_eq_of_length_eq_zero {s : composition_series X} (hs : s.length = 0) {x y} (hx : x ∈ s) (hy : y ∈ s) : x = y := by_contradiction (λ hxy, pos_iff_ne_zero.1 (length_pos_of_mem_ne hx hy hxy) hs) /-- Remove the largest element from a `composition_series`. If the series `s` has length zero, then `s.erase_top = s` -/ @[simps] def erase_top (s : composition_series X) : composition_series X := { length := s.length - 1, series := λ i, s ⟨i, lt_of_lt_of_le i.2 (nat.succ_le_succ sub_le_self')⟩, step' := λ i, begin have := s.step ⟨i, lt_of_lt_of_le i.2 sub_le_self'⟩, cases i, exact this end } lemma top_erase_top (s : composition_series X) : s.erase_top.top = s ⟨s.length - 1, lt_of_le_of_lt sub_le_self' (nat.lt_succ_self _)⟩ := show s _ = s _, from congr_arg s begin ext, simp only [erase_top_length, fin.coe_last, fin.coe_cast_succ, fin.coe_of_nat_eq_mod, fin.coe_mk, coe_coe] end lemma erase_top_top_le (s : composition_series X) : s.erase_top.top ≤ s.top := by simp [erase_top, top, s.strict_mono.le_iff_le, fin.le_iff_coe_le_coe, sub_le_self'] @[simp] lemma bot_erase_top (s : composition_series X) : s.erase_top.bot = s.bot := rfl lemma mem_erase_top_of_ne_of_mem {s : composition_series X} {x : X} (hx : x ≠ s.top) (hxs : x ∈ s) : x ∈ s.erase_top := begin { rcases hxs with ⟨i, rfl⟩, have hi : (i : ℕ) < (s.length - 1).succ, { conv_rhs { rw [← nat.succ_sub (length_pos_of_mem_ne ⟨i, rfl⟩ s.top_mem hx), nat.succ_sub_one] }, exact lt_of_le_of_ne (nat.le_of_lt_succ i.2) (by simpa [top, s.inj, fin.ext_iff] using hx) }, refine ⟨i.cast_succ, _⟩, simp [fin.ext_iff, nat.mod_eq_of_lt hi] } end lemma mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) : x ∈ s.erase_top ↔ x ≠ s.top ∧ x ∈ s := begin simp only [mem_def], dsimp only [erase_top, coe_fn_mk], split, { rintros ⟨i, rfl⟩, have hi : (i : ℕ) < s.length, { conv_rhs { rw [← nat.succ_sub_one s.length, nat.succ_sub h] }, exact i.2 }, simp [top, fin.ext_iff, (ne_of_lt hi)] }, { intro h, exact mem_erase_top_of_ne_of_mem h.1 h.2 } end lemma lt_top_of_mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) (hx : x ∈ s.erase_top) : x < s.top := lt_of_le_of_ne (le_top_of_mem ((mem_erase_top h).1 hx).2) ((mem_erase_top h).1 hx).1 lemma is_maximal_erase_top_top {s : composition_series X} (h : 0 < s.length) : is_maximal s.erase_top.top s.top := have s.length - 1 + 1 = s.length, by conv_rhs { rw [← nat.succ_sub_one s.length] }; rw nat.succ_sub h, begin rw [top_erase_top, top], convert s.step ⟨s.length - 1, nat.sub_lt h zero_lt_one⟩; ext; simp [this] end lemma append_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := by { cases i, simp [fin.append, *] } lemma append_succ_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) (h : s₁ (fin.last _) = s₂ 0) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).succ = s₁ i.succ := begin cases i with i hi, simp only [fin.append, hi, fin.succ_mk, function.comp_app, fin.cast_succ_mk, fin.coe_mk, fin.cast_add_mk], split_ifs, { refl }, { have : i + 1 = s₁.length, from le_antisymm hi (le_of_not_gt h_1), calc s₂ ⟨i + 1 - s₁.length, by simp [this]⟩ = s₂ 0 : congr_arg s₂ (by simp [fin.ext_iff, this]) ... = s₁ (fin.last _) : h.symm ... = _ : congr_arg s₁ (by simp [fin.ext_iff, this]) } end lemma append_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := begin cases i, simp only [fin.append, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, nat.add_sub_cancel_left, dif_neg, fin.cast_succ_mk, not_false_iff, fin.coe_mk] end lemma append_succ_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).succ = s₂ i.succ := begin cases i with i hi, simp only [fin.append, add_assoc, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, nat.add_sub_cancel_left, fin.succ_mk, dif_neg, not_false_iff, fin.coe_mk] end /-- Append two composition series `s₁` and `s₂` such that the least element of `s₁` is the maximum element of `s₂`. -/ @[simps length] def append (s₁ s₂ : composition_series X) (h : s₁.top = s₂.bot) : composition_series X := { length := s₁.length + s₂.length, series := fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂, step' := λ i, begin refine fin.add_cases _ _ i, { intro i, rw [append_succ_cast_add_aux _ h, append_cast_add_aux], exact s₁.step i }, { intro i, rw [append_nat_add_aux, append_succ_nat_add_aux], exact s₂.step i } end } @[simp] lemma append_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := append_cast_add_aux i @[simp] lemma append_succ_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).succ = s₁ i.succ := append_succ_cast_add_aux i h @[simp] lemma append_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := append_nat_add_aux i @[simp] lemma append_succ_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).succ = s₂ i.succ := append_succ_nat_add_aux i /-- Add an element to the top of a `composition_series` -/ @[simps length] def snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : composition_series X := { length := s.length + 1, series := fin.snoc s x, step' := λ i, begin refine fin.last_cases _ _ i, { rwa [fin.snoc_cast_succ, fin.succ_last, fin.snoc_last, ← top] }, { intro i, rw [fin.snoc_cast_succ, ← fin.cast_succ_fin_succ, fin.snoc_cast_succ], exact s.step _ } end } @[simp] lemma top_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).top = x := fin.snoc_last _ _ @[simp] lemma snoc_last (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : snoc s x hsat (fin.last (s.length + 1)) = x := fin.snoc_last _ _ @[simp] lemma snoc_cast_succ (s : composition_series X) (x : X) (hsat : is_maximal s.top x) (i : fin (s.length + 1)) : snoc s x hsat (i.cast_succ) = s i := fin.snoc_cast_succ _ _ _ @[simp] lemma bot_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).bot = s.bot := by rw [bot, bot, ← fin.cast_succ_zero, snoc_cast_succ] lemma mem_snoc {s : composition_series X} {x y: X} {hsat : is_maximal s.top x} : y ∈ snoc s x hsat ↔ y ∈ s ∨ y = x := begin simp only [snoc, mem_def], split, { rintros ⟨i, rfl⟩, refine fin.last_cases _ (λ i, _) i, { right, simp }, { left, simp } }, { intro h, rcases h with ⟨i, rfl⟩ | rfl, { use i.cast_succ, simp }, { use (fin.last _), simp } } end lemma eq_snoc_erase_top {s : composition_series X} (h : 0 < s.length) : s = snoc (erase_top s) s.top (is_maximal_erase_top_top h) := begin ext x, simp [mem_snoc, mem_erase_top h], by_cases h : x = s.top; simp [*, s.top_mem] end @[simp] lemma snoc_erase_top_top {s : composition_series X} (h : is_maximal s.erase_top.top s.top) : s.erase_top.snoc s.top h = s := have h : 0 < s.length, from nat.pos_of_ne_zero begin assume hs, refine ne_of_gt (lt_of_is_maximal h) _, simp [top, fin.ext_iff, hs] end, (eq_snoc_erase_top h).symm /-- Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i) (s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` -/ def equivalent (s₁ s₂ : composition_series X) : Prop := ∃ f : fin s₁.length ≃ fin s₂.length, ∀ i : fin s₁.length, iso (s₁ i.cast_succ, s₁ i.succ) (s₂ (f i).cast_succ, s₂ (f i).succ) namespace equivalent @[refl] lemma refl (s : composition_series X) : equivalent s s := ⟨equiv.refl _, λ _, (s.step _).iso_refl⟩ @[symm] lemma symm {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : equivalent s₂ s₁ := ⟨h.some.symm, λ i, iso_symm (by simpa using h.some_spec (h.some.symm i))⟩ @[trans] lemma trans {s₁ s₂ s₃ : composition_series X} (h₁ : equivalent s₁ s₂) (h₂ : equivalent s₂ s₃) : equivalent s₁ s₃ := ⟨h₁.some.trans h₂.some, λ i, iso_trans (h₁.some_spec i) (h₂.some_spec (h₁.some i))⟩ lemma append {s₁ s₂ t₁ t₂ : composition_series X} (hs : s₁.top = s₂.bot) (ht : t₁.top = t₂.bot) (h₁ : equivalent s₁ t₁) (h₂ : equivalent s₂ t₂) : equivalent (append s₁ s₂ hs) (append t₁ t₂ ht) := let e : fin (s₁.length + s₂.length) ≃ fin (t₁.length + t₂.length) := calc fin (s₁.length + s₂.length) ≃ fin s₁.length ⊕ fin s₂.length : fin_sum_fin_equiv.symm ... ≃ fin t₁.length ⊕ fin t₂.length : equiv.sum_congr h₁.some h₂.some ... ≃ fin (t₁.length + t₂.length) : fin_sum_fin_equiv in ⟨e, begin assume i, refine fin.add_cases _ _ i, { assume i, simpa [top, bot] using h₁.some_spec i }, { assume i, simpa [top, bot] using h₂.some_spec i } end⟩ protected lemma snoc {s₁ s₂ : composition_series X} {x₁ x₂ : X} {hsat₁ : is_maximal s₁.top x₁} {hsat₂ : is_maximal s₂.top x₂} (hequiv : equivalent s₁ s₂) (htop : iso (s₁.top, x₁) (s₂.top, x₂)) : equivalent (s₁.snoc x₁ hsat₁) (s₂.snoc x₂ hsat₂) := let e : fin s₁.length.succ ≃ fin s₂.length.succ := calc fin (s₁.length + 1) ≃ option (fin s₁.length) : fin_succ_equiv_last ... ≃ option (fin s₂.length) : functor.map_equiv option hequiv.some ... ≃ fin (s₂.length + 1) : fin_succ_equiv_last.symm in ⟨e, λ i, begin refine fin.last_cases _ _ i, { simpa [top] using htop }, { assume i, simpa [fin.succ_cast_succ] using hequiv.some_spec i } end⟩ lemma length_eq {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : s₁.length = s₂.length := by simpa using fintype.card_congr h.some lemma snoc_snoc_swap {s : composition_series X} {x₁ x₂ y₁ y₂ : X} {hsat₁ : is_maximal s.top x₁} {hsat₂ : is_maximal s.top x₂} {hsaty₁ : is_maximal (snoc s x₁ hsat₁).top y₁} {hsaty₂ : is_maximal (snoc s x₂ hsat₂).top y₂} (hr₁ : iso (s.top, x₁) (x₂, y₂)) (hr₂ : iso (x₁, y₁) (s.top, x₂)) : equivalent (snoc (snoc s x₁ hsat₁) y₁ hsaty₁) (snoc (snoc s x₂ hsat₂) y₂ hsaty₂) := let e : fin (s.length + 1 + 1) ≃ fin (s.length + 1 + 1) := equiv.swap (fin.last _) (fin.cast_succ (fin.last _)) in have h1 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _).cast_succ, from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), have h2 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _), from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), ⟨e, begin intro i, dsimp only [e], refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_left, snoc_cast_succ, snoc_last, fin.succ_last, snoc_last, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last], exact hr₂ }, { refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_right, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last, snoc_last, fin.succ_last, snoc_last], exact hr₁ }, { erw [equiv.swap_apply_of_ne_of_ne h2 h1, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ], exact (s.step i).iso_refl } } end⟩ end equivalent lemma length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁ : s₁.length = 0) : s₂.length = 0 := begin have : s₁.bot = s₁.top, from congr_arg s₁ (fin.ext (by simp [hs₁])), have : (fin.last s₂.length) = (0 : fin s₂.length.succ), from s₂.injective (hb.symm.trans (this.trans ht)).symm, simpa [fin.ext_iff] end lemma length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : 0 < s₁.length → 0 < s₂.length := not_imp_not.1 begin simp only [pos_iff_ne_zero, ne.def, not_iff_not, not_not], exact length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb.symm ht.symm end lemma eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁0 : s₁.length = 0) : s₁ = s₂ := have ∀ x, x ∈ s₁ ↔ x = s₁.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero hs₁0 hx s₁.top_mem, λ hx, hx.symm ▸ s₁.top_mem⟩, have ∀ x, x ∈ s₂ ↔ x = s₂.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero (length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hs₁0) hx s₂.top_mem, λ hx, hx.symm ▸ s₂.top_mem⟩, by { ext, simp * } /-- Given a `composition_series`, `s`, and an element `x` such that `x` is maximal inside `s.top` there is a series, `t`, such that `t.top = x`, `t.bot = s.bot` and `snoc t s.top _` is equivalent to `s`. -/ lemma exists_top_eq_snoc_equivalant (s : composition_series X) (x : X) (hm : is_maximal x s.top) (hb : s.bot ≤ x) : ∃ t : composition_series X, t.bot = s.bot ∧ t.length + 1 = s.length ∧ ∃ htx : t.top = x, equivalent s (snoc t s.top (htx.symm ▸ hm)) := begin induction hn : s.length with n ih generalizing s x, { exact (ne_of_gt (lt_of_le_of_lt hb (lt_of_is_maximal hm)) (forall_mem_eq_of_length_eq_zero hn s.top_mem s.bot_mem)).elim }, { have h0s : 0 < s.length, from hn.symm ▸ nat.succ_pos _, by_cases hetx : s.erase_top.top = x, { use s.erase_top, simp [← hetx, hn] }, { have imxs : is_maximal (x ⊓ s.erase_top.top) s.erase_top.top, from is_maximal_of_eq_inf x s.top rfl (ne.symm hetx) hm (is_maximal_erase_top_top h0s), have := ih _ _ imxs (le_inf (by simpa) (le_top_of_mem s.erase_top.bot_mem)) (by simp [hn]), rcases this with ⟨t, htb, htl, htt, hteqv⟩, have hmtx : is_maximal t.top x, from is_maximal_of_eq_inf s.erase_top.top s.top (by rw [inf_comm, htt]) hetx (is_maximal_erase_top_top h0s) hm, use snoc t x hmtx, refine ⟨by simp [htb], by simp [htl], by simp, _⟩, have : s.equivalent ((snoc t s.erase_top.top (htt.symm ▸ imxs)).snoc s.top (by simpa using is_maximal_erase_top_top h0s)), { conv_lhs { rw eq_snoc_erase_top h0s }, exact equivalent.snoc hteqv (by simpa using (is_maximal_erase_top_top h0s).iso_refl) }, refine this.trans _, refine equivalent.snoc_snoc_swap _ _, { exact iso_symm (second_iso_of_eq hm (sup_eq_of_is_maximal hm (is_maximal_erase_top_top h0s) (ne.symm hetx)) htt.symm) }, { exact second_iso_of_eq (is_maximal_erase_top_top h0s) (sup_eq_of_is_maximal (is_maximal_erase_top_top h0s) hm hetx) (by rw [inf_comm, htt]) } } } end /-- The **Jordan-Hölder** theorem, stated for any `jordan_holder_lattice`. If two composition series start and finish at the same place, they are equivalent. -/ theorem jordan_holder (s₁ s₂ : composition_series X) (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : equivalent s₁ s₂ := begin induction hle : s₁.length with n ih generalizing s₁ s₂, { rw [eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hle] }, { have h0s₂ : 0 < s₂.length, from length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos hb ht (hle.symm ▸ nat.succ_pos _), rcases exists_top_eq_snoc_equivalant s₁ s₂.erase_top.top (ht.symm ▸ is_maximal_erase_top_top h0s₂) (hb.symm ▸ s₂.bot_erase_top ▸ bot_le_of_mem (top_mem _)) with ⟨t, htb, htl, htt, hteq⟩, have := ih t s₂.erase_top (by simp [htb, ← hb]) htt (nat.succ_inj'.1 (htl.trans hle)), refine hteq.trans _, conv_rhs { rw [eq_snoc_erase_top h0s₂] }, simp only [ht], exact equivalent.snoc this (by simp [htt, (is_maximal_erase_top_top h0s₂).iso_refl]) } end end composition_series
f7315e73385e40df632e197276a5081e61f7c97f
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/algebra/group.lean
4dccfdd7f220cf7003103cd2991cbabe7ece9daf
[ "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
20,556
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 Theory of topological groups. -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph open classical set filter topological_space open_locale classical topological_space filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_group section prio set_option default_priority 100 -- see Note [default priority] /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends has_continuous_add α : Prop := (continuous_neg : continuous (λa:α, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (α : Type*) [topological_space α] [group α] extends has_continuous_mul α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) end prio variables [topological_space α] [group α] @[to_additive] lemma continuous_inv [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv @[to_additive, continuity] lemma continuous.inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg @[to_additive] lemma continuous_on_inv [topological_group α] {s : set α} : continuous_on (λx:α, x⁻¹) s := continuous_inv.continuous_on @[to_additive] lemma continuous_on.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma tendsto_inv {α : Type*} [group α] [topological_space α] [topological_group α] (a : α) : tendsto (λ x, x⁻¹) (nhds a) (nhds (a⁻¹)) := continuous_inv.tendsto a /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (𝓝 a)) : tendsto (λx, (f x)⁻¹) x (𝓝 a⁻¹) := tendsto.comp (continuous_iff_continuous_at.mp topological_group.continuous_inv a) hf @[to_additive] lemma continuous_at.inv [topological_group α] [topological_space β] {f : β → α} {x : β} (hf : continuous_at f x) : continuous_at (λx, (f x)⁻¹) x := hf.inv @[to_additive] lemma continuous_within_at.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} {x : β} (hf : continuous_within_at f s x) : continuous_within_at (λx, (f x)⁻¹) s x := hf.inv @[to_additive] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous_fst.inv.prod_mk continuous_snd.inv } attribute [instance] prod.topological_add_group @[to_additive] protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left [topological_group α] (a : α) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map @[to_additive] protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right [topological_group α] (a : α) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv α } @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : α × α) := tendsto_mul (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ (v ∈ V) (w ∈ V), v * w⁻¹ ∈ s := begin have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) (𝓝 (1:α) ×ᶠ 𝓝 (1:α)) (𝓝 1), { simpa using (@tendsto_fst α α (𝓝 1) (𝓝 1)).mul tendsto_snd.inv }, have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ 𝓝 (1:α) ×ᶠ 𝓝 (1:α) := this (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (𝓝 (1 : α)) = 𝓝 (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (𝓝 1) (𝓝 1), { simpa using (@tendsto_id α (𝓝 1)).inv }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (𝓝 x) (𝓝 (x * x⁻¹)), { simpa }, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space α] [group α] [topological_group α] (N : subgroup α) (n : N.normal) @[to_additive] instance {α : Type u} [group α] [topological_space α] (N : subgroup α) : topological_space (quotient_group.quotient N) := by dunfold quotient_group.quotient; apply_instance open quotient_group @[to_additive] lemma quotient_group_saturate {α : Type u} [group α] (N : subgroup α) (s : set α) : (coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, quotient_group.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by { simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left], exact hi }⟩ } end @[to_additive] lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) := begin intros s s_op, change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)), rw quotient_group_saturate N s, apply is_open_Union, rintro ⟨n, _⟩, exact is_open_map_mul_right n s s_op end @[to_additive] instance topological_group_quotient (n : N.normal) : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) }, { exact (continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd) }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)), exact continuous_quot_mk.comp continuous_inv end } attribute [instance] topological_add_group_quotient end quotient_topological_group section topological_add_group variables [topological_space α] [add_group α] @[continuity] lemma continuous.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma continuous_sub [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_fst.sub continuous_snd lemma continuous_on.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := continuous_sub.comp_continuous_on (hf.prod hg) lemma filter.tendsto.sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x - g x) x (𝓝 (a - b)) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x end topological_add_group section prio set_option default_priority 100 -- see Note [default priority] /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z [] : filter α) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:α×α, p.1 - p.2) (Z ×ᶠ Z) Z) end prio namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) (Z α ×ᶠ Z α) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) (Z α ×ᶠ Z α) (Z α), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ Z α ×ᶠ Z α := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : α) : 𝓝 a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z α := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (Z α ×ᶠ Z α) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space α] [group α] [topological_group α] @[to_additive] lemma is_open_mul_left {s t : set α} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : α), a * x) '' t), assume a, apply is_open_map_mul_left, exact ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open_mul_right {s t : set α} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : α), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (α) lemma topological_group.t1_space (h : @is_closed α _ {1}) : t1_space α := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space α] : regular_space α := ⟨assume s a hs ha, let f := λ p : α × α, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)), -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:α) (by simpa [f]) in begin use s * t₂, use is_open_mul_left ht₂, use λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩, apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space α] : t2_space α := regular_space.t2_space α end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space α] [group α] [topological_group α] /-- Given a open neighborhood `U` of `1` there is a open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma one_open_separated_mul {U : set α} (h1U : is_open U) (h2U : (1 : α) ∈ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ V * V ⊆ U := begin rcases exists_nhds_square (continuous_mul U h1U) (by simp only [mem_preimage, one_mul, h2U] : ((1 : α), (1 : α)) ∈ (λ p : α × α, p.1 * p.2) ⁻¹' U) with ⟨V, h1V, h2V, h3V⟩, refine ⟨V, h1V, h2V, _⟩, rwa [← image_subset_iff, image_mul_prod] at h3V end /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ K * V ⊆ U := begin let W : α → set α := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, continuous_mul_left x U hU, have h2W : ∀ x ∈ K, (1 : α) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, one_open_separated_mul (h1W x) (h2W x.1 x.2), let X : K → set α := λ x, (λ y, (x : α)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, continuous_mul_left x⁻¹ (V x) (hV x).1) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : α)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set α} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset α, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : α, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space α] [comm_group α] [topological_group α] @[to_additive] lemma nhds_mul (x y : α) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_split ht with ⟨V, V_mem, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, ⟨V, V_mem, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:α, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
8b9abdc5002a398b3f4a2cd01cae2ab5d4c878a8
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Data/Option/Instances.lean
f18c71170117dc39fa993e025ae70fe72f63d63f
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
645
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Option.Basic universes u v theorem Option.eqOfEqSome {α : Type u} : ∀ {x y : Option α}, (∀z, x = some z ↔ y = some z) → x = y | none, none, h => rfl | none, some z, h => Option.noConfusion ((h z).2 rfl) | some z, none, h => Option.noConfusion ((h z).1 rfl) | some z, some w, h => Option.noConfusion ((h w).2 rfl) (congrArg some) theorem Option.eqNoneOfIsNone {α : Type u} : ∀ {o : Option α}, o.isNone → o = none | none, h => rfl
5d56b42496e9b7a057f9076e7840c517c1648f20
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0713.lean
271963f50cc14de348f0ccb9da36e4aae43b6e1e
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
148
lean
import data.list.basic open list universe u variables {α : Type} (x y z : α) (xs ys zs : list α) def mk_symm (xs : list α) := xs ++ reverse xs
0a5c1b2959a723abd6fba7c32604c9c9c70b3429
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/constructions/limits_of_products_and_equalizers.lean
269910e580fdf20d8d0a873763be831252fa072e
[]
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
6,333
lean
/- -- Copyright (c) 2020 Bhavik Mehta. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Bhavik Mehta, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.equalizers import Mathlib.category_theory.limits.shapes.finite_products import Mathlib.category_theory.limits.preserves.shapes.products import Mathlib.category_theory.limits.preserves.shapes.equalizers import Mathlib.PostPort universes u v u₂ namespace Mathlib /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. If a functor preserves all products and equalizers, then it preserves all limits. Similarly, if it preserves all finite products and equalizers, then it preserves all finite limits. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ namespace category_theory.limits -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers /-- (Implementation) Given the appropriate product and equalizer cones, build the cone for `F` which is limiting if the given cones are also. -/ def build_limit {C : Type u} [category C] {J : Type v} [small_category J] {F : J ⥤ C} {c₁ : fan (functor.obj F)} {c₂ : fan fun (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p) => functor.obj F (prod.snd (sigma.fst f))} (s : cone.X c₁ ⟶ cone.X c₂) (t : cone.X c₁ ⟶ cone.X c₂) (hs : ∀ (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p), s ≫ nat_trans.app (cone.π c₂) f = nat_trans.app (cone.π c₁) (prod.fst (sigma.fst f)) ≫ functor.map F (sigma.snd f)) (ht : ∀ (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p), t ≫ nat_trans.app (cone.π c₂) f = nat_trans.app (cone.π c₁) (prod.snd (sigma.fst f))) (i : fork s t) : cone F := cone.mk (cone.X i) (nat_trans.mk fun (j : J) => fork.ι i ≫ nat_trans.app (cone.π c₁) j) /-- (Implementation) Show the cone constructed in `build_limit` is limiting, provided the cones used in its construction are. -/ def build_is_limit {C : Type u} [category C] {J : Type v} [small_category J] {F : J ⥤ C} {c₁ : fan (functor.obj F)} {c₂ : fan fun (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p) => functor.obj F (prod.snd (sigma.fst f))} (s : cone.X c₁ ⟶ cone.X c₂) (t : cone.X c₁ ⟶ cone.X c₂) (hs : ∀ (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p), s ≫ nat_trans.app (cone.π c₂) f = nat_trans.app (cone.π c₁) (prod.fst (sigma.fst f)) ≫ functor.map F (sigma.snd f)) (ht : ∀ (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p), t ≫ nat_trans.app (cone.π c₂) f = nat_trans.app (cone.π c₁) (prod.snd (sigma.fst f))) {i : fork s t} (t₁ : is_limit c₁) (t₂ : is_limit c₂) (hi : is_limit i) : is_limit (build_limit s t hs ht i) := is_limit.mk fun (q : cone F) => is_limit.lift hi (fork.of_ι (is_limit.lift t₁ (fan.mk (cone.X q) fun (j : J) => nat_trans.app (cone.π q) j)) sorry) end has_limit_of_has_products_of_has_equalizers /-- Given the existence of the appropriate (possibly finite) products and equalizers, we know a limit of `F` exists. (This assumes the existence of all equalizers, which is technically stronger than needed.) -/ theorem has_limit_of_equalizer_and_product {C : Type u} [category C] {J : Type v} [small_category J] (F : J ⥤ C) [has_limit (discrete.functor (functor.obj F))] [has_limit (discrete.functor fun (f : sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p) => functor.obj F (prod.snd (sigma.fst f)))] [has_equalizers C] : has_limit F := sorry /-- Any category with products and equalizers has all limits. See https://stacks.math.columbia.edu/tag/002N. -/ theorem limits_from_equalizers_and_products {C : Type u} [category C] [has_products C] [has_equalizers C] : has_limits C := has_limits.mk fun (J : Type v) (𝒥 : small_category J) => has_limits_of_shape.mk fun (F : J ⥤ C) => has_limit_of_equalizer_and_product F /-- Any category with finite products and equalizers has all finite limits. See https://stacks.math.columbia.edu/tag/002O. -/ theorem finite_limits_from_equalizers_and_finite_products {C : Type u} [category C] [has_finite_products C] [has_equalizers C] : has_finite_limits C := fun (J : Type v) (_x : small_category J) (_x_1 : fin_category J) => has_limits_of_shape.mk fun (F : J ⥤ C) => has_limit_of_equalizer_and_product F /-- If a functor preserves equalizers and the appropriate products, it preserves limits. -/ def preserves_limit_of_preserves_equalizers_and_product {C : Type u} [category C] {J : Type v} [small_category J] {D : Type u₂} [category D] [has_limits_of_shape (discrete J) C] [has_limits_of_shape (discrete (sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p)) C] [has_equalizers C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [preserves_limits_of_shape (discrete J) G] [preserves_limits_of_shape (discrete (sigma fun (p : J × J) => prod.fst p ⟶ prod.snd p)) G] : preserves_limits_of_shape J G := sorry /-- If G preserves equalizers and finite products, it preserves finite limits. -/ def preserves_finite_limits_of_preserves_equalizers_and_finite_products {C : Type u} [category C] {D : Type u₂} [category D] [has_equalizers C] [has_finite_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [(J : Type v) → [_inst_8 : fintype J] → preserves_limits_of_shape (discrete J) G] (J : Type v) [small_category J] [fin_category J] : preserves_limits_of_shape J G := preserves_limit_of_preserves_equalizers_and_product G /-- If G preserves equalizers and products, it preserves all limits. -/ def preserves_limits_of_preserves_equalizers_and_products {C : Type u} [category C] {D : Type u₂} [category D] [has_equalizers C] [has_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [(J : Type v) → preserves_limits_of_shape (discrete J) G] : preserves_limits G := preserves_limits.mk fun (J : Type v) (𝒥 : small_category J) => preserves_limit_of_preserves_equalizers_and_product G
22b0637925db893fc829f301289ceea19fb7c16b
690889011852559ee5ac4dfea77092de8c832e7e
/src/data/nat/cast.lean
43cbf99fe4c9e7c79b8e06482eb4eead8f8e91d0
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
4,459
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group algebra.ring import tactic.norm_cast namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 @[priority 10] instance cast_coe : has_coe ℕ α := ⟨nat.cast⟩ @[simp, squash_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, move_cast] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl end @[simp, squash_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, move_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] instance [add_monoid α] [has_one α] : is_add_monoid_hom (coe : ℕ → α) := { map_zero := cast_zero, map_add := cast_add } @[simp, squash_cast, move_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, squash_cast, move_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp, move_cast] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp, move_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, move_cast] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] instance [semiring α] : is_semiring_hom (coe : ℕ → α) := by refine_struct {..}; simp theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp, elim_cast] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_lt_of_nonneg zero_lt_one (@cast_nonneg α _ m) | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp, elim_cast] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos [linear_ordered_semiring α] (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one theorem eq_cast [add_monoid α] [has_one α] (f : ℕ → α) (H0 : f 0 = 0) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n | 0 := H0 | (n+1) := by rw [Hadd, H1, eq_cast]; refl theorem eq_cast' [add_group α] [has_one α] (f : ℕ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n := eq_cast _ (by rw [← add_left_inj (f 0), add_zero, ← Hadd]) H1 Hadd @[simp, squash_cast] theorem cast_id (n : ℕ) : ↑n = n := (eq_cast id rfl rfl (λ _ _, rfl) n).symm @[simp, move_cast] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, move_cast] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, elim_cast] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) end nat
0842f1ad5c2cd0fb8c26118b879395a4216523ea
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/Simp/SimpLemmas.lean
bcef799690bd3a995f47ca769867b6366710579a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
12,391
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.DiscrTree import Lean.Meta.AppBuilder import Lean.Meta.Tactic.AuxLemma namespace Lean.Meta /-- The fields `levelParams` and `proof` are used to encode the proof of the simp lemma. If the `proof` is a global declaration `c`, we store `Expr.const c []` at `proof` without the universe levels, and `levelParams` is set to `#[]` When using the lemma, we create fresh universe metavariables. Motivation: most simp lemmas are global declarations, and this approach is faster and saves memory. The field `levelParams` is not empty only when we elaborate an expression provided by the user, and it contains universe metavariables. Then, we use `abstractMVars` to abstract the universe metavariables and create new fresh universe parameters that are stored at the field `levelParams`. -/ structure SimpLemma where keys : Array DiscrTree.Key := #[] levelParams : Array Name := #[] -- non empty for local universe polymorhic proofs. proof : Expr priority : Nat := eval_prio default post : Bool := true perm : Bool := false -- true is lhs and rhs are identical modulo permutation of variables name? : Option Name := none -- for debugging and tracing purposes deriving Inhabited def SimpLemma.getName (s : SimpLemma) : Name := match s.name? with | some n => n | none => "<unknown>" instance : ToFormat SimpLemma where format s := let perm := if s.perm then ":perm" else "" let name := format s.getName let prio := f!":{s.priority}" name ++ prio ++ perm instance : ToMessageData SimpLemma where toMessageData s := format s instance : BEq SimpLemma where beq e₁ e₂ := e₁.proof == e₂.proof structure SimpLemmas where pre : DiscrTree SimpLemma := DiscrTree.empty post : DiscrTree SimpLemma := DiscrTree.empty lemmaNames : Std.PHashSet Name := {} toUnfold : Std.PHashSet Name := {} erased : Std.PHashSet Name := {} deriving Inhabited def addSimpLemmaEntry (d : SimpLemmas) (e : SimpLemma) : SimpLemmas := if e.post then { d with post := d.post.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames } else { d with pre := d.pre.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames } where updateLemmaNames (s : Std.PHashSet Name) : Std.PHashSet Name := match e.name? with | none => s | some name => s.insert name def SimpLemmas.addDeclToUnfold (d : SimpLemmas) (declName : Name) : SimpLemmas := { d with toUnfold := d.toUnfold.insert declName } def SimpLemmas.isDeclToUnfold (d : SimpLemmas) (declName : Name) : Bool := d.toUnfold.contains declName def SimpLemmas.isLemma (d : SimpLemmas) (declName : Name) : Bool := d.lemmaNames.contains declName def SimpLemmas.eraseCore [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do return { d with erased := d.erased.insert declName, lemmaNames := d.lemmaNames.erase declName, toUnfold := d.toUnfold.erase declName } def SimpLemmas.erase [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do unless d.isLemma declName || d.isDeclToUnfold declName do throwError "'{declName}' does not have [simp] attribute" d.eraseCore declName 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 private partial def shouldPreprocess (type : Expr) : MetaM Bool := forallTelescopeReducing type fun xs result => return !result.isEq private partial def preprocess (e type : Expr) (inv : Bool) : MetaM (List (Expr × Expr)) := do let type ← whnf type if type.isForall then forallTelescopeReducing type fun xs type => do let e := mkAppN e xs let ps ← preprocess e type inv ps.mapM fun (e, type) => return (← mkLambdaFVars xs e, ← mkForallFVars xs type) else if let some (_, lhs, rhs) := type.eq? then if inv then let type ← mkEq rhs lhs let e ← mkEqSymm e return [(e, type)] else return [(e, type)] else if let some (lhs, rhs) := type.iff? then if inv then let type ← mkEq rhs lhs let e ← mkEqSymm (← mkPropExt e) return [(e, type)] else let type ← mkEq lhs rhs let e ← mkPropExt e return [(e, type)] else if let some (_, lhs, rhs) := type.ne? then if inv then throwError "invalid '←' modifier in rewrite rule to 'False'" let type ← mkEq (← mkEq lhs rhs) (mkConst ``False) let e ← mkEqFalse e return [(e, type)] else if let some p := type.not? then if inv then throwError "invalid '←' modifier in rewrite rule to 'False'" let type ← mkEq p (mkConst ``False) let e ← mkEqFalse e return [(e, type)] else if let some (type₁, type₂) := type.and? then let e₁ := mkProj ``And 0 e let e₂ := mkProj ``And 1 e return (← preprocess e₁ type₁ inv) ++ (← preprocess e₂ type₂ inv) else if inv then throwError "invalid '←' modifier in rewrite rule to 'True'" let type ← mkEq type (mkConst ``True) let e ← mkEqTrue e return [(e, type)] private def checkTypeIsProp (type : Expr) : MetaM Unit := unless (← isProp type) do throwError "invalid 'simp', proposition expected{indentExpr type}" private def mkSimpLemmaCore (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do let type ← instantiateMVars (← inferType e) withNewMCtxDepth do let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type let type ← whnfR type let (keys, perm) ← match type.eq? with | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs) | none => throwError "unexpected kind of 'simp' theorem{indentExpr type}" return { keys := keys, perm := perm, post := post, levelParams := levelParams, proof := proof, name? := name?, priority := prio } private def mkSimpLemmasFromConst (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) : MetaM (Array SimpLemma) := do let cinfo ← getConstInfo declName let val := mkConst declName (cinfo.levelParams.map mkLevelParam) withReducible do let type ← inferType val checkTypeIsProp type if inv || (← shouldPreprocess type) then let mut r := #[] for (val, type) in (← preprocess val type inv) do let auxName ← mkAuxLemma cinfo.levelParams type val r := r.push <| (← mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName) return r else #[← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName] inductive SimpEntry where | lemma : SimpLemma → SimpEntry | toUnfold : Name → SimpEntry deriving Inhabited abbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpLemmas def SimpExtension.getLemmas (ext : SimpExtension) : CoreM SimpLemmas := return ext.getState (← getEnv) def addSimpLemma (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let simpLemmas ← mkSimpLemmasFromConst declName post inv prio for simpLemma in simpLemmas do ext.add (SimpEntry.lemma simpLemma) attrKind def mkSimpAttr (attrName : Name) (attrDescr : String) (ext : SimpExtension) : IO Unit := registerBuiltinAttribute { name := attrName descr := attrDescr add := fun declName stx attrKind => let go : MetaM Unit := do let info ← getConstInfo declName if (← isProp info.type) then let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost let prio ← getAttrParamOptPrio stx[2] addSimpLemma ext declName post (inv := false) attrKind prio else if info.hasValue then ext.add (SimpEntry.toUnfold declName) attrKind else throwError "invalid 'simp', it is not a proposition nor a definition (to unfold)" discard <| go.run {} {} erase := fun declName => do let s ← ext.getState (← getEnv) let s ← s.erase declName modifyEnv fun env => ext.modifyState env fun _ => s } def mkSimpExt (extName : Name) : IO SimpExtension := registerSimpleScopedEnvExtension { name := extName initial := {} addEntry := fun d e => match e with | SimpEntry.lemma e => addSimpLemmaEntry d e | SimpEntry.toUnfold n => d.addDeclToUnfold n } def registerSimpAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter "Ext") : IO SimpExtension := do let ext ← mkSimpExt extName mkSimpAttr attrName attrDescr ext return ext builtin_initialize simpExtension : SimpExtension ← registerSimpAttr `simp "simplification theorem" def getSimpLemmas : CoreM SimpLemmas := simpExtension.getLemmas /- Auxiliary method for adding a global declaration to a `SimpLemmas` datastructure. -/ def SimpLemmas.addConst (s : SimpLemmas) (declName : Name) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) : MetaM SimpLemmas := do let simpLemmas ← mkSimpLemmasFromConst declName post inv prio return simpLemmas.foldl addSimpLemmaEntry s def SimpLemma.getValue (simpLemma : SimpLemma) : MetaM Expr := do if simpLemma.proof.isConst && simpLemma.levelParams.isEmpty then let info ← getConstInfo simpLemma.proof.constName! if info.levelParams.isEmpty then return simpLemma.proof else return simpLemma.proof.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar)) else let us ← simpLemma.levelParams.mapM fun _ => mkFreshLevelMVar simpLemma.proof.instantiateLevelParamsArray simpLemma.levelParams us private def preprocessProof (val : Expr) (inv : Bool) : MetaM (Array Expr) := do let type ← inferType val checkTypeIsProp type let ps ← preprocess val type inv return ps.toArray.map fun (val, _) => val /- Auxiliary method for creating simp lemmas from a proof term `val`. -/ def mkSimpLemmas (levelParams : Array Name) (proof : Expr) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM (Array SimpLemma) := withReducible do (← preprocessProof proof inv).mapM fun val => mkSimpLemmaCore val levelParams val post prio name? /- Auxiliary method for adding a local simp lemma to a `SimpLemmas` datastructure. -/ def SimpLemmas.add (s : SimpLemmas) (levelParams : Array Name) (proof : Expr) (inv : Bool := false) (post : Bool := true) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM SimpLemmas := do if proof.isConst then s.addConst proof.constName! post inv prio else let simpLemmas ← mkSimpLemmas levelParams proof post inv prio (← getName? proof) return simpLemmas.foldl addSimpLemmaEntry s where getName? (e : Expr) : MetaM (Option Name) := do match name? with | some _ => return name? | none => let f := e.getAppFn if f.isConst then return f.constName! else if f.isFVar then let localDecl ← getFVarLocalDecl f return localDecl.userName else return none end Lean.Meta
17f21fa57433288f0b6cc1248353322bd6be9a58
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/ring_theory/algebraic.lean
dd0e32aa6bd6fb36edc5423c3b6f616362a63f55
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
3,545
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.integral_closure /-! # Algebraic elements and algebraic extensions An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. An R-algebra is algebraic over R if and only if all its elements are algebraic over R. The main result in this file proves transitivity of algebraicity: a tower of algebraic field extensions is algebraic. -/ universe variables u v open_locale classical open polynomial section variables (R : Type u) {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] /-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/ def is_algebraic (x : A) : Prop := ∃ p : polynomial R, p ≠ 0 ∧ aeval R A x p = 0 variables {R} /-- A subalgebra is algebraic if all its elements are algebraic. -/ def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x variables (R A) /-- An algebra is algebraic if all its elements are algebraic. -/ def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x variables {R A} /-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/ lemma subalgebra.is_algebraic_iff (S : subalgebra R A) : S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (by convert S.algebra) := begin delta algebra.is_algebraic subalgebra.is_algebraic, rw [subtype.forall'], apply forall_congr, rintro ⟨x, hx⟩, apply exists_congr, intro p, apply and_congr iff.rfl, have h : function.injective (S.val) := subtype.val_injective, conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], }, apply eq_iff_eq_cancel_right.mpr, symmetry, -- TODO: add an `aeval`-specific version of `hom_eval₂` simp only [aeval_def], convert hom_eval₂ p (algebra_map R S) ↑S.val ⟨x, hx⟩, refl end /-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/ lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic := begin delta algebra.is_algebraic subalgebra.is_algebraic, simp only [algebra.mem_top, forall_prop_of_true, iff_self], end end section zero_ne_one variables (R : Type u) {A : Type v} [nonzero_comm_ring R] [comm_ring A] [algebra R A] /-- An integral element of an algebra is algebraic.-/ lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x := by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ } end zero_ne_one section field variables (K : Type u) {A : Type v} [field K] [comm_ring A] [algebra K A] /-- An element of an algebra over a field is algebraic if and only if it is integral.-/ lemma is_algebraic_iff_is_integral {x : A} : is_algebraic K x ↔ is_integral K x := begin refine ⟨_, is_integral.is_algebraic K⟩, rintro ⟨p, hp, hpx⟩, refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩, rw [alg_hom.map_mul, hpx, zero_mul], end end field namespace algebra variables {K : Type*} {L : Type*} {A : Type*} variables [field K] [field L] [comm_ring A] variables [algebra K L] [algebra L A] /-- If L is an algebraic field extension of K and A is an algebraic algebra over L, then A is algebraic over K. -/ lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) : is_algebraic K (comap K L A) := begin simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢, exact is_integral_trans L_alg A_alg, end end algebra
92ed06849ee24bfccf33b38ee411477034828ed3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/unification_hints1.lean
9c50d04c880647888436173292648a7d94519b46
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,811
lean
-- open list nat structure unification_constraint := {A : Type*} (lhs : A) (rhs : A) structure unification_hint := (pattern : unification_constraint) (constraints : list unification_constraint) namespace toy constants (A : Type) (f h : A → A) (x y z : A) attribute [irreducible] noncomputable definition g (x y : A) : A := f z #unify (g x y), (f z) attribute [unify] noncomputable definition toy_hint (x y : A) : unification_hint := unification_hint.mk (unification_constraint.mk (g x y) (f z)) [] #unify (g x y), (f z) print [unify] end toy namespace add constants (n : ℕ) attribute add [irreducible] #unify (n + 1), succ n attribute [unify] definition add_zero_hint (m n : ℕ) [has_add ℕ] [has_one ℕ] [has_zero ℕ] : unification_hint := unification_hint.mk (unification_constraint.mk (m + 1) (succ n)) [unification_constraint.mk m n] #unify (n + 1), (succ n) print [unify] end add namespace canonical inductive Canonical | mk : Π (carrier : Type*) (op : carrier → carrier), Canonical attribute [irreducible] definition Canonical.carrier (s : Canonical) : Type* := Canonical.rec_on s (λ c op, c) constants (A : Type) (f : A → A) (x : A) noncomputable definition A_canonical : Canonical := Canonical.mk A f #unify (Canonical.carrier A_canonical), A attribute [unify] noncomputable definition Canonical_hint (C : Canonical) : unification_hint := unification_hint.mk (unification_constraint.mk (Canonical.carrier C) A) [unification_constraint.mk C A_canonical] -- TODO(dhs): we mark carrier as irreducible and prove A_canonical explicitly to work around the fact that -- the default_type_context does not recognize the elaborator metavariables as metavariables, -- and so cannot perform the assignment. #unify (Canonical.carrier A_canonical), A print [unify] end canonical
5f618c5ac4250bebed2df320a868fbcbd39c30ba
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/ring.lean
9b97d0802cc4397406b1375329eb6b85b0c502a1
[ "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
2,409
lean
import tactic.ring import data.real.basic example (x y : ℕ) : x + y = y + x := by ring example (x y : ℕ) : x + y + y = 2 * y + x := by ring example (x y : ℕ) : x + id y = y + id x := by ring! example {α} [comm_ring α] (x y : α) : x + y + y - x = 2 * y := by ring example (x y : ℚ) : x / 2 + x / 2 = x := by ring example (x y : ℚ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring example (x y : ℝ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 15000 {ring} example (n : ℕ) : (n / 2) + (n / 2) = 2 * (n / 2) := by ring example {α} [field α] [char_zero α] (a : α) : a / 2 = a / 2 := by ring example {α} [linear_ordered_field α] (a b c : α) : a * (-c / b) * (-c / b) + -c + c = a * (c / b * (c / b)) := by ring example {α} [linear_ordered_field α] (a b c : α) : b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring example (x : ℚ) : x ^ (2 + 2) = x^4 := by ring_nf -- TODO: ring should work? example {α} [comm_ring α] (x : α) : x ^ 2 = x * x := by ring example {α} [linear_ordered_field α] (a b c : α) : b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring example {α} [linear_ordered_field α] (a b c : α) : b ^ 2 - 4 * a * c = 4 * a * 0 + b * b - 4 * a * c := by ring example {α} [comm_semiring α] (x y z : α) (n : ℕ) : (x + y) * (z * (y * y) + (x * x ^ n + (1 + ↑n) * x ^ n * y)) = x * (x * x ^ n) + ((2 + ↑n) * (x * x ^ n) * y + (x * z + (z * y + (1 + ↑n) * x ^ n)) * (y * y)) := by ring example {α} [comm_ring α] (a b c d e : α) : (-(a * b) + c + d) * e = (c + (d + -a * b)) * e := by ring example (a n s: ℕ) : a * (n - s) = (n - s) * a := by ring example (x y z : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : x / (y / z) + y ⁻¹ + 1 / (y * -x) = -1/ (x * y) + (x * z + 1) / y := begin field_simp, ring end example (a b c d x y : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x - c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x - c) / x) := begin field_simp, ring end example : (876544 : ℤ) * -1 + (1000000 - 123456) = 0 := by ring example (x y : ℝ) (hx : x ≠ 0) (hy : y ≠ 0) : 2 * x ^ 3 * 2 / (24 * x) = x ^ 2 / 6 := begin field_simp, ring end -- this proof style is not recommended practice example (A B : ℕ) (H : B * A = 2) : A * B = 2 := by {ring_nf, exact H}
acb98815c81624e3c691dfbeec5bff1446dba775
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/category/Module/basic.lean
6891e48b71bce5f79cd4b9900f38af0617a67bf1
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,865
lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import algebra.category.Group.basic import category_theory.concrete_category import category_theory.limits.shapes.kernels import category_theory.preadditive import linear_algebra.basic /-! # Category instance for modules over a ring We introduce the bundled category `Module` along with relevant forgetful functor to `AddCommGroup`. We furthermore show that `Module` is a preadditive category. -/ open category_theory open category_theory.limits open category_theory.limits.walking_parallel_pair universes v u variables (R : Type u) [ring R] /-- The category of R-modules and their morphisms. -/ structure Module := (carrier : Type v) [is_add_comm_group : add_comm_group carrier] [is_module : module R carrier] attribute [instance] Module.is_add_comm_group Module.is_module namespace Module -- TODO revisit this after #1438 merges, to check coercions and instances are handled consistently instance : has_coe_to_sort (Module.{v} R) := { S := Type v, coe := Module.carrier } instance : category (Module.{v} R) := { hom := λ M N, M →ₗ[R] N, id := λ M, 1, comp := λ A B C f g, g.comp f } instance : concrete_category.{v} (Module.{v} R) := { forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } instance has_forget_to_AddCommGroup : has_forget₂ (Module R) AddCommGroup := { forget₂ := { obj := λ M, AddCommGroup.of M, map := λ M₁ M₂ f, linear_map.to_add_monoid_hom f } } /-- The object in the category of R-modules associated to an R-module -/ def of (X : Type v) [add_comm_group X] [module R X] : Module R := ⟨X⟩ instance : has_zero (Module R) := ⟨of R punit⟩ instance : inhabited (Module R) := ⟨0⟩ @[simp] lemma coe_of (X : Type u) [add_comm_group X] [module R X] : (of R X : Type u) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original module. -/ @[simps] def of_self_iso (M : Module R) : Module.of R M ≅ M := { hom := 𝟙 M, inv := 𝟙 M } instance : subsingleton (of R punit) := by { rw coe_of R punit, apply_instance } instance : has_zero_object (Module.{v} R) := { zero := 0, unique_to := λ X, { default := (0 : punit →ₗ[R] X), uniq := λ _, linear_map.ext $ λ x, have h : x = 0, from dec_trivial, by simp only [h, linear_map.map_zero]}, unique_from := λ X, { default := (0 : X →ₗ[R] punit), uniq := λ _, linear_map.ext $ λ x, dec_trivial } } variables {R} {M N U : Module.{v} R} @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl end Module variables {R} variables {X₁ X₂ : Type v} /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom [add_comm_group X₁] [module R X₁] [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ Module.of R X₂) := id /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. -/ @[simps] def linear_equiv.to_Module_iso {g₁ : add_comm_group X₁} {g₂ : add_comm_group X₂} {m₁ : module R X₁} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso' {M N : Module.{v} R} (i : M ≃ₗ[R] N) : M ≅ N := { hom := i, inv := i.symm, hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } namespace category_theory.iso /-- Build a `linear_equiv` from an isomorphism in the category `Module R`. -/ @[simps] def to_linear_equiv {X Y : Module R} (i : X ≅ Y) : X ≃ₗ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_smul' := by tidy, }. end category_theory.iso /-- linear equivalences between `module`s are the same as (isomorphic to) isomorphisms in `Module` -/ @[simps] def linear_equiv_iso_Module_iso {X Y : Type u} [add_comm_group X] [add_comm_group Y] [module R X] [module R Y] : (X ≃ₗ[R] Y) ≅ (Module.of R X ≅ Module.of R Y) := { hom := λ e, e.to_Module_iso, inv := λ i, i.to_linear_equiv, } namespace Module section preadditive instance : preadditive (Module.{v} R) := { add_comp' := λ P Q R f f' g, show (f + f') ≫ g = f ≫ g + f' ≫ g, by { ext, simp }, comp_add' := λ P Q R f g g', show f ≫ (g + g') = f ≫ g + f ≫ g', by { ext, simp } } end preadditive section epi_mono variables {M N : Module.{v} R} (f : M ⟶ N) lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := linear_map.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ (as_hom u) (as_hom v)).1 lemma range_eq_top_of_epi [epi f] : f.range = ⊤ := linear_map.range_eq_top_of_cancel $ λ u v, (@cancel_epi _ _ _ _ _ f _ (as_hom u) (as_hom v)).1 lemma mono_of_ker_eq_bot (hf : f.ker = ⊥) : mono f := concrete_category.mono_of_injective _ $ linear_map.ker_eq_bot.1 hf lemma epi_of_range_eq_top (hf : f.range = ⊤) : epi f := concrete_category.epi_of_surjective _ $ linear_map.range_eq_top.1 hf end epi_mono end Module instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩
4a15a5c3171bef04c9b117ab911b8d9ebca2006f
785b41b0993f39cbfa9b02fe0940ce3f2f51a57d
/conf/xm3g.lean
74bf122c8f6561c0c58bbcf4073df56f090b16ec
[ "MIT" ]
permissive
loso3000/OpenWrt-DIY-1
75b0d70314d703203508218a29acefc3b914d32d
5858be81ee44199908cbaa1a752b17505c9834e8
refs/heads/main
1,690,532,461,283
1,631,008,241,000
1,631,008,241,000
354,817,508
1
0
MIT
1,617,623,493,000
1,617,623,492,000
null
UTF-8
Lean
false
false
7,710
lean
CONFIG_TARGET_ramips=y CONFIG_TARGET_ramips_mt7621=y CONFIG_TARGET_DEVICE_ramips_mt7621_DEVICE_xiaomi_mir3g=y # 不压缩efi # CONFIG_TARGET_IMAGES_GZIP is not set CONFIG_EFI_IMAGES=y CONFIG_TARGET_ROOTFS_TARGZ=n # CONFIG_VMDK_IMAGES is not set # ipv6 CONFIG_PACKAGE_ipv6helper=y CONFIG_PACKAGE_dnsmasq_full_dhcpv6=y # file system CONFIG_PACKAGE_kmod-fs-vfat=y CONFIG_PACKAGE_kmod-fs-nfs-common=y CONFIG_PACKAGE_kmod-fs-nfs=y CONFIG_PACKAGE_kmod-fs-nfs-v3=y CONFIG_PACKAGE_kmod-fs-nfs-v4=y CONFIG_PACKAGE_kmod-fs-antfs=y CONFIG_PACKAGE_kmod-fuse=y CONFIG_PACKAGE_kmod-fs-ext4=y CONFIG_PACKAGE_kmod-fs-squashfs=y #ksmbd #CONFIG_PACKAGE_kmod-fs-ksmbd=y #CONFIG_PACKAGE_kmod-nls-utf8=y #CONFIG_PACKAGE_kmod-nls-cp936=y #CONFIG_PACKAGE_kmod-nls-iso8859-1=y CONFIG_PACKAGE_kmod-ksmbd-utils=y # 添加网络配置 CONFIG_PACKAGE_ppp-mod-pptp=y #VPN客户端 CONFIG_PACKAGE_kmod-vmxnet3=y CONFIG_PACKAGE_kmod-pcnet32=y # add upnp CONFIG_PACKAGE_irqbalance=n CONFIG_PACKAGE_miniupnpd-igdv1=y CONFIG_PACKAGE_luci-app-upnp=y CONFIG_PACKAGE_luci-app-boostupnp=n # CONFIG_PACKAGE_luci-app-wol is not set CONFIG_PACKAGE_luci-app-wolplus=y # 工具 CONFIG_PACKAGE_iperf3=y #局域网测速 CONFIG_PACKAGE_snmpd=y #旁路由穿透显示真机器MAC CONFIG_PACKAGE_fdisk=y #分区工具 CONFIG_PACKAGE_wget=y CONFIG_PACKAGE_bash=y CONFIG_PACKAGE_curl=y # CONFIG_PACKAGE_autosamba is not set CONFIG_PACKAGE_autosamba-ksmbd=n CONFIG_PACKAGE_autosamba-samba4=y # CONFIG_PACKAGE_luci-app-accesscontrol is not set CONFIG_PACKAGE_luci-app-adbyby-plus is not set CONFIG_PACKAGE_luci-app-adguardhome=y CONFIG_PACKAGE_luci-app-advanced=y CONFIG_PACKAGE_luci-app-autotimeset=n CONFIG_PACKAGE_luci-app-rebootschedule=y # CONFIG_PACKAGE_luci-app-autoreboot is not set CONFIG_PACKAGE_luci-app-control-timewol=n CONFIG_PACKAGE_luci-app-control-weburl=y CONFIG_PACKAGE_luci-app-cpulimit=y CONFIG_PACKAGE_luci-app-diskman=y CONFIG_PACKAGE_luci-app-eqos=y CONFIG_PACKAGE_luci-app-hd-idle=y # CONFIG_PACKAGE_luci-app-ipsec-vpnd is not set CONFIG_PACKAGE_luci-app-jd-dailybonus=y CONFIG_PACKAGE_luci-app-koolproxyR=n CONFIG_PACKAGE_luci-app-netdata=y CONFIG_PACKAGE_luci-app-onliner=n CONFIG_PACKAGE_luci-app-openclash=y CONFIG_PACKAGE_luci-app-passwall=y # CONFIG_PACKAGE_luci-app-samba is not set CONFIG_PACKAGE_luci-app-samba4=y CONFIG_PACKAGE_luci-app-serverchan=y # CONFIG_PACKAGE_luci-app-sfe is no set # CONFIG_PACKAGE_luci-app-flowoffload is no set # CONFIG_PACKAGE_luci-app-filetransfer is not set CONFIG_PACKAGE_luci-app-smartdns=y CONFIG_PACKAGE_luci-app-ssr-plus=y CONFIG_PACKAGE_luci-app-timecontrol=y CONFIG_PACKAGE_luci-app-access-control=n CONFIG_PACKAGE_luci-app-ttyd=y CONFIG_PACKAGE_luci-app-turboacc=y # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_flow-offload=n # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_shortcut-fe=y # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_dnsforwarder=y CONFIG_PACKAGE_luci-app-vssr=y CONFIG_PACKAGE_luci-app-wrtbwmon=y CONFIG_PACKAGE_luci-app-nlbwmon=y CONFIG_PACKAGE_luci-app-netspeedtest=y CONFIG_PACKAGE_luci-app-dnsto=y CONFIG_PACKAGE_luci-app-bypass=n # CONFIG_PACKAGE_luci-app-bypass_INCLUDE_NaiveProxy=n # CONFIG_PACKAGE_luci-app-bypass_INCLUDE_V2ray=y CONFIG_PACKAGE_luci-app-dnsfilter=y CONFIG_PACKAGE_luci-app-vsftpd=y CONFIG_PACKAGE_luci-app-switch-lan-play=n CONFIG_PACKAGE_luci-app-mentohust=y # 主题 CONFIG_PACKAGE_luci-theme-atmaterial=n CONFIG_PACKAGE_luci-theme-ifit=n CONFIG_PACKAGE_luci-theme-edge=n CONFIG_PACKAGE_luci-theme-argon_new=y CONFIG_PACKAGE_luci-theme-btmod=n CONFIG_PACKAGE_luci-theme-opentomcat=n CONFIG_PACKAGE_luci-theme-opentopd=y #增加其它插件 CONFIG_PACKAGE_luci-app-tencentddns=n CONFIG_PACKAGE_luci-app-pushbot=n CONFIG_PACKAGE_luci-app-easymesh=n CONFIG_PACKAGE_luci-app-ksmbd=n CONFIG_PACKAGE_luci-app-cifsd=n CONFIG_PACKAGE_luci-app-cifs-mount=n CONFIG_PACKAGE_luci-app-xlnetacc is not set # CONFIG_PACKAGE_luci-app-zerotier is not set CONFIG_PACKAGE_luci-app-mwan3=y CONFIG_PACKAGE_luci-app-unblockneteasemusic=y # CONFIG_PACKAGE_luci-app-unblockmusic is not set # CONFIG_UnblockNeteaseMusic_Go=y # CONFIG_UnblockNeteaseMusic_NodeJS=y # CONFIG_PACKAGE_luci-app-minidlna is not set # CONFIG_PACKAGE_luci-app-rclone is not set # CONFIG_PACKAGE_luci-app-rclone_INCLUDE_fuse-utils is not set # CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-ng is not set # CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-webui is not set CONFIG_PACKAGE_luci-app-pptp-server=n CONFIG_PACKAGE_luci-app-pppoe-server=n CONFIG_PACKAGE_luci-app-ipsec-server=n CONFIG_PACKAGE_luci-app-docker=n CONFIG_PACKAGE_luci-app-dockerman=n CONFIG_PACKAGE_luci-app-koolddns=n CONFIG_PACKAGE_luci-app-syncdial=y CONFIG_PACKAGE_luci-app-softethervpn=n CONFIG_PACKAGE_luci-app-uugamebooster=y CONFIG_DEFAULT_luci-app-cpufreq=n CONFIG_PACKAGE_luci-app-udpxy=n CONFIG_PACKAGE_luci-app-socat=y CONFIG_PACKAGE_luci-app-oaf=n CONFIG_PACKAGE_luci-app-transmission=n CONFIG_PACKAGE_luci-app-usb-printer=n CONFIG_PACKAGE_luci-app-mwan3helper=n CONFIG_PACKAGE_luci-app-qbittorrent=n CONFIG_PACKAGE_luci-app-familycloud=n CONFIG_PACKAGE_luci-app-nps=n CONFIG_PACKAGE_luci-app-frpc=n CONFIG_PACKAGE_luci-app-nfs=n CONFIG_PACKAGE_luci-app-openvpn-server=n CONFIG_PACKAGE_luci-app-aria2=n CONFIG_PACKAGE_luci-app-openvpn=n CONFIG_PACKAGE_luci-app-ttnode=n CONFIG_TARGET_KERNEL_PARTSIZE=64 CONFIG_TARGET_ROOTFS_PARTSIZE=960 CONFIG_PACKAGE_kmod-ath=y CONFIG_PACKAGE_kmod-ath6kl=y CONFIG_PACKAGE_kmod-ath6kl-usb=y CONFIG_PACKAGE_kmod-ath9k-common=y CONFIG_PACKAGE_kmod-ath9k-htc=y CONFIG_PACKAGE_kmod-carl9170=y CONFIG_PACKAGE_kmod-lib80211=y CONFIG_PACKAGE_kmod-libertas-usb=y CONFIG_PACKAGE_kmod-mac80211=y CONFIG_PACKAGE_kmod-mt7601u=y CONFIG_PACKAGE_kmod-mt7603=y CONFIG_PACKAGE_kmod-mt7663u=y CONFIG_PACKAGE_kmod-mt76x0u=y CONFIG_PACKAGE_kmod-mt76x2u=y CONFIG_PACKAGE_kmod-net-prism54=y CONFIG_PACKAGE_kmod-net-rtl8192su=y CONFIG_PACKAGE_kmod-p54-common=y CONFIG_PACKAGE_kmod-p54-usb=y CONFIG_PACKAGE_kmod-rsi91x=y CONFIG_PACKAGE_kmod-rsi91x-usb=y CONFIG_PACKAGE_kmod-rt2500-usb=y CONFIG_PACKAGE_kmod-rt2800-lib=y CONFIG_PACKAGE_kmod-rt2800-usb=y CONFIG_PACKAGE_kmod-rt2x00-lib=y CONFIG_PACKAGE_kmod-rt2x00-usb=y CONFIG_PACKAGE_kmod-rt73-usb=y CONFIG_PACKAGE_kmod-rtl8187=y CONFIG_PACKAGE_kmod-rtl8192c-common=y CONFIG_PACKAGE_kmod-rtl8192cu=y CONFIG_PACKAGE_kmod-rtl8812au-ac=y CONFIG_PACKAGE_kmod-rtl8821cu=y CONFIG_PACKAGE_kmod-rtl8xxxu=y CONFIG_PACKAGE_kmod-rtlwifi=y CONFIG_PACKAGE_kmod-rtlwifi-usb=y CONFIG_PACKAGE_kmod-zd1211rw=y CONFIG_PACKAGE_ath9k-htc-firmware=y CONFIG_PACKAGE_libertas-usb-firmware=y CONFIG_PACKAGE_mt7601u-firmware=y CONFIG_PACKAGE_p54-usb-firmware=y CONFIG_PACKAGE_prism54-firmware=y CONFIG_PACKAGE_rs9113-firmware=y CONFIG_PACKAGE_rt2800-usb-firmware=y CONFIG_PACKAGE_rt73-usb-firmware=y CONFIG_PACKAGE_rtl8188eu-firmware=y CONFIG_PACKAGE_rtl8192cu-firmware=y CONFIG_PACKAGE_rtl8192eu-firmware=y CONFIG_PACKAGE_rtl8192su-firmware=y CONFIG_PACKAGE_rtl8723au-firmware=y CONFIG_PACKAGE_rtl8723bu-firmware=y CONFIG_PACKAGE_luci-app-netkeeper-interception=y CONFIG_PACKAGE_luci-i18n-netkeeper-interception-zh-cn=y CONFIG_PACKAGE_luci-i18n-netkeeper-zh-cn=y CONFIG_PACKAGE_luci-proto-netkeeper=y CONFIG_PACKAGE_kmod-usb-serial=y CONFIG_PACKAGE_kmod-usb-serial-option=y CONFIG_PACKAGE_kmod-usb-serial-wwan=y CONFIG_PACKAGE_usb-modeswitch=y CONFIG_PACKAGE_kmod-mii=y CONFIG_PACKAGE_luci-proto-qmi=y CONFIG_PACKAGE_qmi-utils=y CONFIG_PACKAGE_umbim=y CONFIG_PACKAGE_uqmi=y CONFIG_PACKAGE_comgt-ncm=y CONFIG_PACKAGE_luci-proto-ncm=y CONFIG_PACKAGE_comgt=y CONFIG_PACKAGE_kmod-usb-acm=y CONFIG_PACKAGE_luci-proto-3g=y CONFIG_PACKAGE_libimobiledevice-utils=y CONFIG_PACKAGE_libplist-utils=y CONFIG_PACKAGE_libusbmuxd-utils=y CONFIG_PACKAGE_usbmuxd=y CONFIG_PACKAGE_libudev-fbsd=y
d5465feb1d25b4bf715250f063d67ba5074dd6a8
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/analysis/calculus/deriv.lean
29b0f24de1c7a923a0af44345daad00bf4bd129b
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
70,678
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (nhds_within x s) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x {x}ᶜ) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (mem_nhds_sets (is_open_prod is_open_ne is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} : differentiable_within_at 𝕜 (λx, c x / d) s x := by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc] @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : differentiable_at 𝕜 (λ x, c x / d) x := by simp [div_eq_inv_mul, hc] lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} : differentiable_on 𝕜 (λx, c x / d) s := by simp [div_eq_inv_mul, differentiable_on.const_mul, hc] @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} : differentiable 𝕜 (λx, c x / d) := by simp [div_eq_inv_mul, differentiable.const_mul, hc] lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : deriv (λx, c x / d) x = (deriv c x) / d := by simp [div_eq_inv_mul, deriv_const_mul, hc] end division theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero, nat.cast_one] }, { simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_fpow m hx).has_deriv_at theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], exact filter.eventually_eq.deriv_eq (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
782d6078554124858f61146960311aecb533071b
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/missing_import.lean
86bdaa8163a22d9474f610253cab5a9e1d1e3ff4
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48
lean
import does.not.exist data.bitvec print bitvec
bf876d939a058f38cc56069b76eb30461dc8d759
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/int/cast/field.lean
2fe7363a6d4f249251e9d2a5ea4b8b9048be6d7e
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
1,259
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.int.cast.lemmas import algebra.field.defs import algebra.group_with_zero.units.lemmas /-! # Cast of integers into fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file concerns the canonical homomorphism `ℤ → F`, where `F` is a field. ## Main results * `int.cast_div`: if `n` divides `m`, then `↑(m / n) = ↑m / ↑n` -/ namespace int open nat variables {α : Type*} /-- Auxiliary lemma for norm_cast to move the cast `-↑n` upwards to `↑-↑n`. (The restriction to `field` is necessary, otherwise this would also apply in the case where `R = ℤ` and cause nontermination.) -/ @[norm_cast] lemma cast_neg_nat_cast {R} [field R] (n : ℕ) : ((-n : ℤ) : R) = -n := by simp @[simp] theorem cast_div [field α] {m n : ℤ} (n_dvd : n ∣ m) (n_nonzero : (n : α) ≠ 0) : ((m / n : ℤ) : α) = m / n := begin rcases n_dvd with ⟨k, rfl⟩, have : n ≠ 0, { rintro rfl, simpa using n_nonzero }, rw [int.mul_div_cancel_left _ this, int.cast_mul, mul_div_cancel_left _ n_nonzero], end end int
3dc8bb9d185cb632b6dbbb40f694460946b92439
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/full_subcategory.lean
425a3ad2c6e0c671cd61730d01325b6d82ee72a3
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
2,398
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton import category_theory.fully_faithful namespace category_theory universes v u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation section induced /- Induced categories. Given a category D and a function F : C → D from a type C to the objects of D, there is an essentially unique way to give C a category structure such that F becomes a fully faithful functor, namely by taking Hom_C(X, Y) = Hom_D(FX, FY). We call this the category induced from D along F. As a special case, if C is a subtype of D, this produces the full subcategory of D on the objects belonging to C. In general the induced category is equivalent to the full subcategory of D on the image of F. -/ variables {C : Sort u₁} {D : Sort u₂} [𝒟 : category.{v u₂} D] include 𝒟 variables (F : C → D) include F def induced_category : Sort u₁ := C instance induced_category.category : category.{v} (induced_category F) := { hom := λ X Y, F X ⟶ F Y, id := λ X, 𝟙 (F X), comp := λ _ _ _ f g, f ≫ g } def induced_functor : induced_category F ⥤ D := { obj := F, map := λ x y f, f } @[simp] lemma induced_functor.obj {X} : (induced_functor F).obj X = F X := rfl @[simp] lemma induced_functor.hom {X Y} {f : X ⟶ Y} : (induced_functor F).map f = f := rfl instance induced_category.fully_faithful : fully_faithful (induced_functor F) := { preimage := λ x y f, f } end induced section full_subcategory /- A full subcategory is the special case of an induced category with F = subtype.val. -/ variables {C : Sort u₂} [𝒞 : category.{v} C] include 𝒞 variables (Z : C → Prop) instance full_subcategory : category.{v} {X : C // Z X} := induced_category.category subtype.val def full_subcategory_inclusion : {X : C // Z X} ⥤ C := induced_functor subtype.val @[simp] lemma full_subcategory_inclusion.obj {X} : (full_subcategory_inclusion Z).obj X = X.val := rfl @[simp] lemma full_subcategory_inclusion.map {X Y} {f : X ⟶ Y} : (full_subcategory_inclusion Z).map f = f := rfl instance full_subcategory.fully_faithful : fully_faithful (full_subcategory_inclusion Z) := induced_category.fully_faithful subtype.val end full_subcategory end category_theory
6e1eedc3fc9c8dc266508bd4a52d3307d30aebb0
022215fec0be87ac6243b0f4fa3cc2939361d7d0
/src/category_theory/instances/Top/presheaf_of_functions.lean
c8567d58672e409dfb29e8cca2ed37bcec188dfa
[ "Apache-2.0" ]
permissive
PaulGustafson/mathlib
4aa7bc81ca971fdd7b6e50bf3a245fade2978391
c49ac06ff9fa1371e9b6050a121df618cfd3fb80
refs/heads/master
1,590,798,947,521
1,559,220,227,000
1,559,220,227,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,742
lean
-- Copyright (c) 2019 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.instances.Top.presheaf import category_theory.instances.TopCommRing.basic import category_theory.yoneda import ring_theory.subring import topology.algebra.continuous_functions universes v u open category_theory open category_theory.instances open topological_space open opposite namespace category_theory.instances.Top variables (X : Top.{v}) def presheaf_to_Top (T : Top.{v}) : X.presheaf (Type v) := (opens.to_Top X).op ⋙ (yoneda.obj T) -- TODO upgrade the result to TopCommRing? def continuous_functions (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) : CommRing.{v} := { α := unop X ⟶ TopCommRing.forget_to_Top.obj R, str := _root_.continuous_comm_ring } namespace continuous_functions @[simp] lemma one (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (x) : (monoid.one ↥(continuous_functions X R)).val x = 1 := rfl @[simp] lemma add (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (f g : continuous_functions X R) (x) : (comm_ring.add f g).val x = f.1 x + g.1 x := rfl @[simp] lemma mul (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (f g : continuous_functions X R) (x) : (ring.mul f g).val x = f.1 x * g.1 x := rfl def pullback {X Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) : continuous_functions X R ⟶ continuous_functions Y R := { val := λ g, f.unop ≫ g, property := { map_one := rfl, map_add := by tidy, map_mul := by tidy } } local attribute [extensionality] subtype.eq def map (X : Topᵒᵖ) {R S : TopCommRing} (φ : R ⟶ S) : continuous_functions X R ⟶ continuous_functions X S := { val := λ g, g ≫ (TopCommRing.forget_to_Top.map φ), property := { map_one := begin ext1, ext1, simp only [one], exact φ.2.1.map_one end, map_add := λ x y, begin ext1, ext1, simp only [function.comp_app, add], apply φ.2.1.map_add end, map_mul := λ x y, begin ext1, ext1, simp only [function.comp_app, mul], apply φ.2.1.map_mul end } } end continuous_functions def CommRing_yoneda : TopCommRing ⥤ (Topᵒᵖ ⥤ CommRing) := { obj := λ R, { obj := λ X, continuous_functions X R, map := λ X Y f, continuous_functions.pullback f R }, map := λ R S φ, { app := λ X, continuous_functions.map X φ } } def presheaf_to_TopCommRing (T : TopCommRing.{v}) : X.presheaf CommRing.{v} := (opens.to_Top X).op ⋙ (CommRing_yoneda.obj T) noncomputable def presheaf_ℝ (Y : Top) : Y.presheaf CommRing := presheaf_to_TopCommRing Y (TopCommRing.of ℝ) noncomputable def presheaf_ℂ (Y : Top) : Y.presheaf CommRing := presheaf_to_TopCommRing Y (TopCommRing.of ℂ) end category_theory.instances.Top
420b096540ad0a7c7f356fa0b878963388f17198
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/data/zmod/quadratic_reciprocity.lean
28a6e803539168cb3f0db962ebd6d06050815308
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
33,376
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.finite data.zmod.basic algebra.pi_instances open function finset nat finite_field zmodp namespace zmodp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : ℕ} (hp : nat.prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (λ h, by resetI; subst h; revert x; exact dec_trivial) (λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], λ hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.two_le dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) : (∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmodp p hp, y ^ 2 = -1) ↔ p % 4 ≠ 3 := have (-1 : zmodp p hp) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, hp.eq_two_or_odd.elim (λ hp, by resetI; subst hp; exact dec_trivial) (λ hp1, (mod_two_eq_zero_or_one (p / 2)).elim (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_zero, eq_self_iff_true, true_iff], assume h, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, h] at hp2, exact absurd hp2 dec_trivial, end) (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_one, iff_false_intro (zmodp.ne_neg_self hp hp1 one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at hp2, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp1, have hp4 : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp1 hp2, revert hp4, generalize : p % 4 = k, revert k, exact dec_trivial end)) lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (λ h, by revert a ha; resetI; subst h; exact dec_trivial) (λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : ℕ} (hp : nat.prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_range_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom (coe : units (zmodp p hp) → zmodp p hp), ← prod_hom (coe : ℕ → zmodp p hp)], exact eq.symm (prod_bij (λ a _, (a : zmodp p hp).1) (λ a ha, mem_erase.2 ⟨λ h, units.coe_ne_zero a $ fin.eq_of_veq h, by rw [mem_range, ← succ_sub hp.pos, succ_sub_one]; exact a.1.2⟩) (λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (λ b hb, have b ≠ 0 ∧ b < p, by rwa [mem_erase, mem_range, ← succ_sub hp.pos, succ_sub_one] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_range_prime_erase_zero {p : ℕ} (hp : nat.prime p) : ((range p).erase 0).prod (λ x, (x : zmodp p hp)) = -1 := by conv in (range p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom (coe : ℕ → zmodp p hp), finset.prod_range_id_eq_fact, wilsons_lemma] end zmodp namespace quadratic_reciprocity_aux variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) include hp hq hp1 hq1 hpq lemma filter_range_p_mul_q_div_two_eq : (range ((p * q) / 2).succ).filter (coprime p) = (range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x)) ∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p) := finset.ext.2 $ λ x, ⟨λ h, have hxp0 : x % p ≠ 0, by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd]; exact (mem_filter.1 h).2, mem_union.2 $ or_iff_not_imp_right.2 (λ h₁, mem_bind.2 ⟨x / p, mem_range.2 $ nat.div_lt_of_lt_mul (by_contradiction (λ h₂, let ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_not_gt h₂) in have hcp : c ≤ p / 2, from @nat.le_of_add_le_add_left (p * (q / 2)) _ _ (by rw [← hc, ← odd_mul_odd_div_two hp1 hq1]; exact le_of_lt_succ (mem_range.1 (mem_filter.1 h).1)), h₁ $ mem_image.2 ⟨c, mem_erase.2 ⟨λ h, hxp0 $ by simp [h, hc], mem_range.2 $ lt_succ_of_le $ hcp⟩, by rw hc; simp [mul_comm]⟩)), mem_image.2 ⟨x % p, mem_erase.2 $ by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd, mem_range]; exact ⟨(mem_filter.1 h).2, mod_lt _ hp.pos⟩, nat.mod_add_div _ _⟩⟩), λ h, mem_filter.2 $ (mem_union.1 h).elim (λ h, let ⟨m, hm₁, hm₂⟩ := mem_bind.1 h in let ⟨k, hk₁, hk₂⟩ := mem_image.1 hm₂ in ⟨mem_range.2 $ hk₂ ▸ (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 begin rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add], clear _let_match _let_match, exact calc 2 * k + 2 * (p * m) < 2 * p + 2 * (p * m) : add_lt_add_right ((mul_lt_mul_left dec_trivial).2 (by simp at hk₁; tauto)) _ ... = 2 * (p * (m + 1)) : by simp [mul_add, mul_assoc, mul_comm, mul_left_comm] ... ≤ 2 * (p * (q / 2)) : (mul_le_mul_left (show 0 < 2, from dec_trivial)).2 ((mul_le_mul_left hp.pos).2 $ succ_le_of_lt $ mem_range.1 hm₁) ... ≤ _ : by rw [mul_left_comm, two_mul_odd_div_two hq1, nat.mul_sub_left_distrib, ← nat.sub_add_comm (mul_pos hp.pos hq.pos), add_succ, succ_eq_add_one, nat.add_sub_cancel]; exact le_trans (nat.sub_le_self _ _) (nat.le_add_right _ _), end, by rw [nat.prime.coprime_iff_not_dvd hp, ← hk₂, ← nat.dvd_add_iff_left (dvd_mul_right _ _), dvd_iff_mod_eq_zero, mod_eq_of_lt]; clear _let_match _let_match; simp at hk₁; tauto⟩) (λ h, let ⟨m, hm₁, hm₂⟩ := mem_image.1 h in ⟨mem_range.2 $ hm₂ ▸ begin refine (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 _, rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add, ← mul_assoc 2, two_mul_odd_div_two hq1], exact calc 2 * m + (q - 1) * p ≤ 2 * (p / 2) + (q - 1) * p : add_le_add_right ((mul_le_mul_left dec_trivial).2 (le_of_lt_succ (mem_range.1 (by simp * at *)))) _ ... < _ : begin rw [two_mul_odd_div_two hp1, nat.mul_sub_right_distrib, one_mul], rw [← nat.sub_add_comm hp.pos, nat.add_sub_cancel' (le_mul_of_one_le_left' (nat.zero_le _) hq.pos), mul_comm], exact lt_add_of_pos_right _ dec_trivial end, end, by rw [hp.coprime_iff_not_dvd, dvd_iff_mod_eq_zero, ← hm₂, nat.add_mul_mod_self_right, mod_eq_of_lt (lt_of_lt_of_le _ (nat.div_lt_self hp.pos (show 1 < 2, from dec_trivial)))]; simp at hm₁; clear _let_match; tauto⟩)⟩ lemma prod_filter_range_p_mul_q_div_two_eq : (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = ((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) := calc (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = (range (q / 2)).prod (λ n, (((range p).erase 0).image (+ p * n)).prod (λ x, x)) * (((range (p / 2).succ).erase 0).image (+ (q / 2) * p)).prod (λ x, x) : by simp only [prod_image (λ _ _ _ _ h, add_right_cancel h)]; refl ... = ((range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x)) ∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p)).prod (λ x, x) : have h₁ : disjoint (finset.bind (range (q / 2)) (λ x, ((range p).erase 0).image (+ p * x))) (image (+ q / 2 * p) (erase (range (succ (p / 2))) 0)) := disjoint_iff.2 $ eq_empty_iff_forall_not_mem.2 $ λ x, begin suffices : ∀ a, a ≠ 0 → a ≤ p / 2 → a + q / 2 * p = x → ∀ b, b < q / 2 → ∀ c, c ≠ 0 → c < p → ¬c + p * b = x, { simpa [lt_succ_iff] }, assume a ha0 hap ha b hbq c hc0 hcp hc, rw mul_comm at ha, rw [← ((nat.div_mod_unique hp.pos).2 ⟨hc, hcp⟩).1, ← ((nat.div_mod_unique hp.pos).2 ⟨ha, lt_of_le_of_lt hap (nat.div_lt_self hp.pos dec_trivial)⟩).1] at hbq, exact lt_irrefl _ hbq end, have h₂ : ∀ x, x ∈ range (q / 2) → ∀ y, y ∈ range (q / 2) → x ≠ y → disjoint (image (+p * x) (erase (range p) 0)) (image (+ p * y) (erase (range p) 0)) := λ x hx y hy hxy, begin suffices : ∀ z a, a ≠ 0 → a < p → a + p * x = z → ∀ bpy b, b ≠ 0 → b < p → b + p * y = bpy → z ≠ bpy, { simpa [disjoint_iff_ne] }, assume z a ha0 hap ha bpy b hb0 hbp hb hzb, have : (a + p * x) / p = (b + p * y) / p, { rw [ha, hb, hzb] }, rw [nat.add_mul_div_left _ _ hp.pos, nat.add_mul_div_left _ _ hp.pos, (nat.div_eq_zero_iff hp.pos).2 hap, (nat.div_eq_zero_iff hp.pos).2 hbp] at this, simpa [hxy] end, by rw [prod_union h₁, prod_bind h₂] ... = (((range ((p * q) / 2).succ)).filter (coprime p)).prod (λ x, x) : prod_congr (filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq).symm (λ _ _, rfl) lemma prod_filter_range_p_mul_q_div_two_mod_p_eq : ((((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : zmodp p hp) = (-1) ^ (q / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) := begin rw [← prod_filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq, nat.cast_mul, ← prod_hom (coe : ℕ → zmodp p hp), ← prod_hom (coe : ℕ → zmodp p hp)], conv in ((finset.prod (erase (range p) 0) _ : ℕ) : zmodp p hp) { rw ← prod_hom (coe : ℕ → zmodp p hp) }, simp end lemma prod_filter_range_p_mul_q_not_coprime_eq : (((((range ((p * q) / 2).succ).filter (coprime p)).filter (λ x, ¬ coprime q x)).prod (λ x, x) : ℕ) : zmodp p hp) = q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) := have hcard : ((range (p / 2).succ).erase 0).card = p / 2 := by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], begin conv in ((q : zmodp p hp) ^ (p / 2)) { rw ← hcard }, rw [← prod_const, ← prod_mul_distrib, ← prod_hom (coe : ℕ → zmodp p hp)], exact eq.symm (prod_bij (λ a _, a * q) (λ a ha, have ha' : a ≤ p / 2 ∧ a > 0, by simp [nat.pos_iff_ne_zero, lt_succ_iff] at *; tauto, mem_filter.2 ⟨mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ (calc a * q ≤ q * (p / 2) : by rw mul_comm; exact mul_le_mul_left _ ha'.1 ... ≤ _ : by rw [mul_comm p, odd_mul_odd_div_two hq1 hp1]; exact nat.le_add_right _ _), by rw [hp.coprime_iff_not_dvd, hp.dvd_mul, not_or_distrib]; refine ⟨λ hpa, not_le_of_gt (show p / 2 < p, from nat.div_lt_self hp.pos dec_trivial) (le_trans (le_of_dvd ha'.2 hpa) ha'.1), by rwa [← hp.coprime_iff_not_dvd, coprime_primes hp hq]⟩⟩, by simp [hq.coprime_iff_not_dvd]⟩) (by simp [mul_comm]) (by simp [nat.mul_right_inj hq.pos]) (λ b hb, have hb' : (b ≤ p * q / 2 ∧ coprime p b) ∧ q ∣ b, by simpa [hq.coprime_iff_not_dvd, lt_succ_iff] using hb, have hb0 : b > 0, from nat.pos_of_ne_zero (λ hb0, by simpa [hb0, hp.coprime_iff_not_dvd] using hb'), ⟨b / q, mem_erase.2 ⟨nat.pos_iff_ne_zero.1 (nat.div_pos (le_of_dvd hb0 hb'.2) hq.pos), mem_range.2 $ lt_succ_of_le $ by rw [mul_comm, odd_mul_odd_div_two hq1 hp1] at hb'; have := @nat.div_le_div_right _ _ hb'.1.1 q; rwa [add_comm, nat.add_mul_div_left _ _ hq.pos, ((nat.div_eq_zero_iff hq.pos).2 (nat.div_lt_self hq.pos (lt_succ_self _))), zero_add] at this⟩, by rw nat.div_mul_cancel hb'.2⟩)) end lemma prod_range_p_mul_q_filter_coprime_mod_p (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) = (-1) ^ (q / 2) * q ^ (p / 2) := have hq0 : (q : zmodp p hp) ≠ 0, by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, coprime_primes hp hq], (domain.mul_right_inj (show (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) ≠ 0, from mul_ne_zero (pow_ne_zero _ hq0) (suffices h : ∀ (x : ℕ), ¬x = 0 → x ≤ p / 2 → ¬(x : zmodp p hp) = 0, by simpa [prod_eq_zero_iff, lt_succ_iff], assume x hx0 hxp, by rwa [← @nat.cast_zero (zmodp p hp), zmodp.eq_iff_modeq_nat, nat.modeq, zero_mod, mod_eq_of_lt (lt_of_le_of_lt hxp (nat.div_lt_self hp.pos (lt_succ_self _)))]))).1 $ have h₁ : disjoint ((range (succ (p * q / 2))).filter (coprime (p * q))) (filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))), by {rw [finset.filter_filter], apply finset.disjoint_filter.2, rintros _ _ hpq ⟨_, hq⟩, exact hq (coprime.coprime_mul_left hpq)}, calc ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) * (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) = (((range (succ (p * q / 2))).filter (coprime (p * q)) ∪ filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))).prod (λ x, x) : ℕ) : by rw [← prod_filter_range_p_mul_q_not_coprime_eq hp hq hp1 hq1 hpq, ← nat.cast_mul, ← prod_union h₁] ... = (((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : congr_arg coe (prod_congr (by simp [finset.ext, coprime_mul_iff_left]; tauto) (λ _ _, rfl)) ... = _ : by rw [prod_filter_range_p_mul_q_div_two_mod_p_eq hp hq hp1 hq1 hpq]; cases zmodp.pow_div_two_eq_neg_one_or_one hp hq0; simp [h, _root_.pow_succ] lemma card_range_p_mul_q_filter_not_coprime : card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = (q / 2).succ := calc card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = card ((range (q / 2).succ).image (* p)) : congr_arg card $ finset.ext.2 $ λ x, begin rw [mem_filter, mem_range, hp.coprime_iff_not_dvd, not_not, mem_image], exact ⟨λ ⟨h, ⟨m, hm⟩⟩, ⟨m, mem_range.2 (lt_of_mul_lt_mul_left (by rw ← hm; exact lt_of_lt_of_le h (by rw [succ_le_iff, mul_succ, odd_mul_odd_div_two hp1 hq1]; exact add_lt_add_left (div_lt_self hp.pos (lt_succ_self 1)) _)) (nat.zero_le p)), hm.symm ▸ mul_comm m p⟩, λ ⟨m, hm₁, hm₂⟩, ⟨lt_succ_of_le (by rw [← hm₂, odd_mul_odd_div_two hp1 hq1]; exact le_trans (by rw mul_comm; exact mul_le_mul_left _ (le_of_lt_succ (mem_range.1 hm₁))) (le_add_right _ _)), by simp [hm₂.symm]⟩⟩ end ... = _ : by rw [card_image_of_injective _ (λ _ _ h, (nat.mul_right_inj hp.pos).1 h), card_range] lemma prod_filter_range_p_mul_q_div_two_eq_prod_product : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) := have hpqpnat : (((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) : ℤ) = (p * q : ℤ), by simp, have hpqpnat' : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) = p * q, by simp, have hpq1 : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) % 2 = 1, from nat.odd_mul_odd hp1 hq1, have hpq1' : p * q > 1, from one_lt_mul hp.pos hq.one_lt, have hhq0 : ∀ a : ℕ, coprime q a → a ≠ 0, from λ a, imp_not_comm.1 $ by simp [hq.coprime_iff_not_dvd] {contextual := tt}, have hpq0 : 0 < p * q / 2, from nat.div_pos (succ_le_of_lt $ one_lt_mul hp.pos hq.one_lt) dec_trivial, have hinj : ∀ a₁ a₂ : ℕ, a₁ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → a₂ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → (if (a₁ : zmodp q hq).1 ≤ q / 2 then ((a₁ : zmodp p hp).1, (a₁ : zmodp q hq).1) else ((-a₁ : zmodp p hp).1, (-a₁ : zmodp q hq).1)) = (if (a₂ : zmodp q hq).1 ≤ q / 2 then ((a₂ : zmodp p hp).1, (a₂ : zmodp q hq).1) else ((-a₂ : zmodp p hp).1, (-a₂ : zmodp q hq).1)) → a₁ = a₂, from λ a b ha hb h, have ha' : a ≤ (p * q) / 2 ∧ coprime (p * q) a, by simpa [lt_succ_iff] using ha, have hapq' : a < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) := lt_of_le_of_lt ha'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have hb' : b ≤ (p * q) / 2 ∧ coprime (p * q) b, by simpa [lt_succ_iff, coprime_mul_iff_left] using hb, have hbpq' : b < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) := lt_of_le_of_lt hb'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have val_inj : ∀ {p : ℕ} (hp : nat.prime p) (x y : zmodp p hp), x.val = y.val ↔ x = y, from λ _ _ _ _, ⟨fin.eq_of_veq, fin.veq_of_eq⟩, have hbpq0 : (b : zmod (⟨p * q, mul_pos hp.pos hq.pos⟩)) ≠ 0, by rw [ne.def, zmod.eq_zero_iff_dvd_nat]; exact λ h, not_coprime_of_dvd_of_dvd hpq1' (dvd_refl (p * q)) h hb'.2, have habneg : ¬((a : zmodp p hp) = -b ∧ (a : zmodp q hq) = -b), begin rw [← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_neg, ← int.cast_neg, zmodp.eq_iff_modeq_int, zmodp.eq_iff_modeq_int, @int.modeq.modeq_and_modeq_iff_modeq_mul _ _ p q ((coprime_primes hp hq).2 hpq), ← hpqpnat, ← zmod.eq_iff_modeq_int, int.cast_coe_nat, int.cast_neg, int.cast_coe_nat], assume h, rw [← hpqpnat', ← zmod.val_cast_of_lt hbpq', zmod.le_div_two_iff_lt_neg hpq1 hbpq0, ← h, zmod.val_cast_of_lt hapq', ← not_le] at hb', exact hb'.1 ha'.1, end, have habneg' : ¬((-a : zmodp p hp) = b ∧ (-a : zmodp q hq) = b), by rwa [← neg_inj', neg_neg, ← @neg_inj' _ _ (-a : zmodp q hq), neg_neg], suffices (a : zmodp p hp) = b ∧ (a : zmodp q hq) = b, by rw [← mod_eq_of_lt hapq', ← mod_eq_of_lt hbpq']; rwa [zmodp.eq_iff_modeq_nat, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_and_modeq_iff_modeq_mul ((coprime_primes hp hq).2 hpq)] at this, by split_ifs at h; simp * at *, have hmem : ∀ a : ℕ, a ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → (if (a : zmodp q hq).1 ≤ q / 2 then ((a : zmodp p hp).1, (a : zmodp q hq).1) else ((-a : zmodp p hp).1, (-a : zmodp q hq).1)) ∈ ((range p).erase 0).product ((range (succ (q / 2))).erase 0), from λ x, have hxp : ∀ {p : ℕ} (hp : nat.prime p), (x : zmodp p hp).val = 0 ↔ p ∣ x, from λ p hp, by rw [zmodp.val_cast_nat, nat.dvd_iff_mod_eq_zero], have hxpneg : ∀ {p : ℕ} (hp : nat.prime p), (-x : zmodp p hp).val = 0 ↔ p ∣ x, from λ p hp, by rw [← int.cast_coe_nat x, ← int.cast_neg, ← int.coe_nat_inj', zmodp.coe_val_cast_int, int.coe_nat_zero, ← int.dvd_iff_mod_eq_zero, dvd_neg, int.coe_nat_dvd], have hxplt : (x : zmodp p hp).val < p := (x : zmodp p hp).2, have hxpltneg : (-x : zmodp p hp).val < p := (-x : zmodp p hp).2, have hneglt : ¬(x : zmodp q hq).val ≤ q / 2 → (x : zmodp q hq) ≠ 0 → (-x : zmodp q hq).val ≤ q / 2, from λ hx₁ hx0, by rwa [zmodp.le_div_two_iff_lt_neg hq hq1 hx0, not_lt] at hx₁, by split_ifs; simp [zmodp.eq_zero_iff_dvd_nat hq, (x : zmodp p hp).2, coprime_mul_iff_left, lt_succ_iff, h, *, hp.coprime_iff_not_dvd, hq.coprime_iff_not_dvd, (x : zmodp p hp).2, (-x : zmodp p hp).2] {contextual := tt}, prod_bij (λ x _, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp).val, (x : zmodp q hq).val) else ((-x : zmodp p hp).val, (-x : zmodp q hq).val)) hmem (λ a ha, by split_ifs; simp [*, prod.ext_iff] at *) hinj (surj_on_of_inj_on_of_card_le _ hmem hinj (@nat.le_of_add_le_add_right (q / 2 + (p / 2).succ) _ _ (calc card (finset.product (erase (range p) 0) (erase (range (succ (q / 2))) 0)) + (q / 2 + (p / 2).succ) = (p * q) / 2 + 1 : by rw [card_product, card_erase_of_mem (mem_range.2 hp.pos), card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, card_range, pred_succ, ← add_assoc, ← succ_mul, succ_pred_eq_of_pos hp.pos, odd_mul_odd_div_two hp1 hq1, add_succ] ... = card (range (p * q / 2).succ) : by rw card_range ... = card ((range (p * q / 2).succ).filter (coprime (p * q)) ∪ ((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0 ∪ (range (p * q / 2).succ).filter (λ x, ¬coprime q x)) : congr_arg card (by simp [finset.ext, coprime_mul_iff_left]; tauto) ... ≤ card ((range (p * q / 2).succ).filter (coprime (p * q))) + card (((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0) + card ((range (p * q / 2).succ).filter (λ x, ¬coprime q x)) : le_trans (card_union_le _ _) (add_le_add_right (card_union_le _ _) _) ... = _ : by rw [card_erase_of_mem, card_range_p_mul_q_filter_not_coprime hp hq hp1 hq1 hpq, mul_comm p q, card_range_p_mul_q_filter_not_coprime hq hp hq1 hp1 hpq.symm, pred_succ, add_assoc]; simp [range_succ, hp.coprime_iff_not_dvd, hpq0]))) lemma prod_range_div_two_erase_zero : ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2 * (-1) ^ (p / 2) = -1 := have hcard : card (erase (range (succ (p / 2))) 0) = p / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have hp2 : p / 2 < p, from div_lt_self hp.pos dec_trivial, have h₁ : (range (p / 2).succ).erase 0 = ((range p).erase 0).filter (λ x, (x : zmodp p hp).val ≤ p / 2) := finset.ext.2 (λ a, ⟨λ h, mem_filter.2 $ by rw [mem_erase, mem_range, lt_succ_iff] at h; exact ⟨mem_erase.2 ⟨h.1, mem_range.2 (lt_of_le_of_lt h.2 hp2)⟩, by rw zmodp.val_cast_of_lt hp (lt_of_le_of_lt h.2 hp2); exact h.2⟩, λ h, mem_erase.2 ⟨by simp at h; tauto, by rw [mem_filter, mem_erase, mem_range] at h; rw [mem_range, lt_succ_iff, ← zmodp.val_cast_of_lt hp h.1.2]; exact h.2⟩⟩), have hmem : ∀ x ∈ (range (p / 2).succ).erase 0, x ≠ 0 ∧ x ≤ p / 2, from λ x hx, by simpa [lt_succ_iff] using hx, have hmemv : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp).val = x, from λ x hx, zmodp.val_cast_of_lt hp (lt_of_le_of_lt (hmem x hx).2 hp2), have hmem0 : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp) ≠ 0, from λ x hx, fin.ne_of_vne $ by simp [hmemv x hx, (hmem x hx).1], have hmem0' : ∀ x ∈ (range (p / 2).succ).erase 0, (-x : zmodp p hp) ≠ 0, from λ x hx, neg_ne_zero.2 (hmem0 x hx), have h₂ : ((range (p / 2).succ).erase 0).prod (λ x : ℕ, (x : zmodp p hp) * -1) = (((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) := prod_bij (λ a _, (-a : zmodp p hp).1) (λ a ha, mem_filter.2 ⟨mem_erase.2 ⟨fin.vne_of_ne (hmem0' a ha), mem_range.2 (-a : zmodp p hp).2⟩, by simp [zmodp.le_div_two_iff_lt_neg hp hp1 (hmem0' a ha), hmemv a ha, (hmem a ha).2]; tauto⟩) (by simp) (λ a₁ a₂ ha₁ ha₂ h, by rw [← hmemv a₁ ha₁, ← hmemv a₂ ha₂]; exact fin.veq_of_eq (by rw neg_inj (fin.eq_of_veq h))) (λ b hb, have hb' : (b ≠ 0 ∧ b < p) ∧ (¬(b : zmodp p hp).1 ≤ p / 2), by simpa using hb, have hbv : (b : zmodp p hp).1 = b, from zmodp.val_cast_of_lt hp hb'.1.2, have hb0 : (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by simp [hbv, hb'.1.1], ⟨(-b : zmodp p hp).1, mem_erase.2 ⟨fin.vne_of_ne (neg_ne_zero.2 hb0 : _), mem_range.2 $ lt_succ_of_le $ by rw [← not_lt, ← zmodp.le_div_two_iff_lt_neg hp hp1 hb0]; exact hb'.2⟩, by simp [hbv]⟩), calc ((((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2)) * (-1) ^ (p / 2) = ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) * ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp) * -1) : by rw prod_mul_distrib; simp [_root_.pow_two, hcard, mul_assoc] ... = (((range p).erase 0).filter (λ x : ℕ, (x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) * (((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) : by rw [h₂, h₁] ... = ((range p).erase 0).prod (λ x, (x : zmodp p hp)) : begin rw ← prod_union, { exact finset.prod_congr (by simp [finset.ext, -not_lt, -not_le]; tauto) (λ _ _, rfl) }, { apply disjoint_filter.2, tauto } end ... = -1 : by simp lemma range_p_product_range_q_div_two_prod : (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) = ((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) := have hcard : card (erase (range (succ (q / 2))) 0) = q / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have finset.prod (erase (range (succ (q / 2))) 0) (λ x : ℕ, (x : zmodp q hq)) ^ 2 = -((-1 : zmodp q hq) ^ (q / 2)), from (domain.mul_right_inj (show (-1 : zmodp q hq) ^ (q / 2) ≠ 0, from pow_ne_zero _ (neg_ne_zero.2 zero_ne_one.symm))).1 $ by rw [prod_range_div_two_erase_zero hq hp hq1 hp1 hpq.symm, ← neg_mul_eq_neg_mul, ← _root_.pow_add, ← two_mul, pow_mul, _root_.pow_two]; simp, have finset.prod (erase (range (succ (q / 2))) 0) (λ x, (x : zmodp q hq)) ^ card (erase (range p) 0) = (- 1) ^ (p / 2) * ((-1) ^ (p / 2 * (q / 2))), by rw [card_erase_of_mem (mem_range.2 hp.pos), card_range, pred_eq_sub_one, ← two_mul_odd_div_two hp1, pow_mul, this, mul_comm (p / 2), pow_mul, ← _root_.mul_pow]; simp, by simp [prod_product, (prod_mk_prod _ _ _).symm, prod_pow, prod_nat_pow, prod_const, *, zmodp.prod_range_prime_erase_zero hp] lemma prod_range_p_mul_q_div_two_ite_eq : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then 1 else -1) * ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := calc ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, (if (x : zmodp q hq).1 ≤ (q / 2) then 1 else -1) * ((x : zmodp p hp), (x : zmodp q hq))) : prod_congr rfl (λ _ _, by split_ifs; simp) ... = _ : by rw [prod_mul_distrib, ← prod_mk_prod, prod_hom (coe : ℕ → zmodp p hp), prod_range_p_mul_q_filter_coprime_mod_p hp hq hp1 hq1 hpq, prod_hom (coe : ℕ → zmodp q hq), mul_comm p q, prod_range_p_mul_q_filter_coprime_mod_p hq hp hq1 hp1 hpq.symm] end quadratic_reciprocity_aux open quadratic_reciprocity_aux variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) namespace zmodp def legendre_sym (a p : ℕ) (hp : nat.prime p) : ℤ := if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) (hp : nat.prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.two_le (succ_pos 1))] else (nat.prime.eq_two_or_odd hp).elim (λ hp2, begin resetI; subst hp2, suffices : ∀ a : zmodp 2 nat.prime_two, (((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 nat.prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (λ hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : nat.prime p) (ha : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * theorem quadratic_reciprocity (hp : nat.prime p) (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hneg_one_or_one : ((range (p * q / 2).succ).filter (coprime (p * q))).prod (λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = 1 ∨ ((range (p * q / 2).succ).filter (coprime (p * q))).prod (λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = -1 := finset.induction_on ((range (p * q / 2).succ).filter (coprime (p * q))) (or.inl rfl) (λ a s h, by simp [prod_insert h]; split_ifs; finish), have h : (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) = ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) ∨ (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) = - ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := begin have := prod_filter_range_p_mul_q_div_two_eq_prod_product hp hq hp1 hq1 hpq, rw [prod_range_p_mul_q_div_two_ite_eq hp hq hp1 hq1 hpq, range_p_product_range_q_div_two_prod hp hq hp1 hq1 hpq] at this, cases hneg_one_or_one with h h; simp * at * end, begin have := ne_neg_self hp hp1 one_ne_zero, have := ne_neg_self hq hq1 one_ne_zero, generalize hnp : (-1 : ℤ) ^ (p / 2) = np, have hnpp : (-1 : zmodp q hq) ^ (p / 2) = np, by simp [hnp.symm], generalize hnq : (-1 : ℤ) ^ (q / 2) = nq, have hnqp : (-1 : zmodp p hp) ^ (q / 2) = nq, by simp [hnq.symm], have hnqq : (-1 : zmodp q hq) ^ (q / 2) = nq, by simp [hnq.symm], cases legendre_sym_eq_one_or_neg_one q hp (zmodp.prime_ne_zero hp hq hpq); cases legendre_sym_eq_one_or_neg_one p hq (zmodp.prime_ne_zero hq hp hpq.symm); cases @neg_one_pow_eq_or ℤ _ (p / 2); cases @neg_one_pow_eq_or ℤ _ (q / 2); simp [*, pow_mul, (legendre_sym_eq_pow p q hq).symm, (legendre_sym_eq_pow q p hp).symm, prod.ext_iff] at *; cc end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by resetI; subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
42078d6da3f831d6cf257c2328c0d1928fd79b6e
8711b4976859218c98ea2129103249d693a4178b
/src/modal_logic/universal.lean
7cadd877f57e2430578cf38233408040ea5ec7fb
[]
no_license
kendfrey/modal_logic
e2433c122ff7012aa743739283ceaa3451e41e79
c07b5524de478cb57d796d0617b28990c7c77770
refs/heads/master
1,679,147,393,521
1,615,255,686,000
1,615,255,686,000
345,164,286
0
0
null
null
null
null
UTF-8
Lean
false
false
873
lean
import modal_logic.classes import modal_logic.axioms -- This file provides a modal system with a universal accessibility relation. open modal_logic namespace modal_logic def universal.has_acc [world] : has_acc World := ⟨λ w v, true⟩ localized "attribute [instance] modal_logic.universal.has_acc" in modal_frame.universal def universal_frame [world] : modal_frame := ⟨⟩ localized "attribute [instance] modal_logic.universal_frame" in modal_frame.universal instance [modal_frame] : is_refl World (≺) := ⟨λ w, trivial⟩ instance [modal_frame] : is_trans World (≺) := ⟨λ w v u h h', trivial⟩ instance [modal_frame] : is_symm World (≺) := ⟨λ w v h, trivial⟩ instance [modal_frame] : is_preorder World (≺) := ⟨⟩ instance [modal_frame] : is_equiv World (≺) := ⟨⟩ instance [modal_frame] : is_per World (≺) := ⟨⟩ end modal_logic
5941512d42bce58675c114353f4df5dee9e733fe
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/hindman.lean
ca9e61f6c7bc375eeca1801f970719cb0d77f8b6
[ "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
11,450
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import topology.stone_cech import topology.algebra.semigroup import data.stream.init /-! # Hindman's theorem on finite sums We prove Hindman's theorem on finite sums, using idempotent ultrafilters. Given an infinite sequence `a₀, a₁, a₂, …` of positive integers, the set `FS(a₀, …)` is the set of positive integers that can be expressed as a finite sum of `aᵢ`'s, without repetition. Hindman's theorem asserts that whenever the positive integers are finitely colored, there exists a sequence `a₀, a₁, a₂, …` such that `FS(a₀, …)` is monochromatic. There is also a stronger version, saying that whenever a set of the form `FS(a₀, …)` is finitely colored, there exists a sequence `b₀, b₁, b₂, …` such that `FS(b₀, …)` is monochromatic and contained in `FS(a₀, …)`. We prove both these versions for a general semigroup `M` instead of `ℕ+` since it is no harder, although this special case implies the general case. The idea of the proof is to extend the addition `(+) : M → M → M` to addition `(+) : βM → βM → βM` on the space `βM` of ultrafilters on `M`. One can prove that if `U` is an _idempotent_ ultrafilter, i.e. `U + U = U`, then any `U`-large subset of `M` contains some set `FS(a₀, …)` (see `exists_FS_of_large`). And with the help of a general topological argument one can show that any set of the form `FS(a₀, …)` is `U`-large according to some idempotent ultrafilter `U` (see `exists_idempotent_ultrafilter_le_FS`). This is enough to prove the theorem since in any finite partition of a `U`-large set, one of the parts is `U`-large. ## Main results - `FS_partition_regular`: the strong form of Hindman's theorem - `exists_FS_of_finite_cover`: the weak form of Hindman's theorem ## Tags Ramsey theory, ultrafilter -/ open filter /-- Multiplication of ultrafilters given by `∀ᶠ m in U*V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m*m')`. -/ @[to_additive "Addition of ultrafilters given by `∀ᶠ m in U+V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m+m')`." ] def ultrafilter.has_mul {M} [has_mul M] : has_mul (ultrafilter M) := { mul := λ U V, (*) <$> U <*> V } local attribute [instance] ultrafilter.has_mul ultrafilter.has_add /- We could have taken this as the definition of `U * V`, but then we would have to prove that it defines an ultrafilter. -/ @[to_additive] lemma ultrafilter.eventually_mul {M} [has_mul M] (U V : ultrafilter M) (p : M → Prop) : (∀ᶠ m in ↑(U * V), p m) ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m * m') := iff.rfl /-- Semigroup structure on `ultrafilter M` induced by a semigroup structure on `M`. -/ @[to_additive "Additive semigroup structure on `ultrafilter M` induced by an additive semigroup structure on `M`."] def ultrafilter.semigroup {M} [semigroup M] : semigroup (ultrafilter M) := { mul_assoc := λ U V W, ultrafilter.coe_inj.mp $ filter.ext' $ λ p, by simp only [ultrafilter.eventually_mul, mul_assoc] ..ultrafilter.has_mul } local attribute [instance] ultrafilter.semigroup ultrafilter.add_semigroup /- We don't prove `continuous_mul_right`, because in general it is false! -/ @[to_additive] lemma ultrafilter.continuous_mul_left {M} [semigroup M] (V : ultrafilter M) : continuous (* V) := topological_space.is_topological_basis.continuous ultrafilter_basis_is_basis _ $ set.forall_range_iff.mpr $ λ s, ultrafilter_is_open_basic { m : M | ∀ᶠ m' in V, m * m' ∈ s } namespace hindman /-- `FS a` is the set of finite sums in `a`, i.e. `m ∈ FS a` if `m` is the sum of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ inductive FS {M} [add_semigroup M] : stream M → set M | head (a : stream M) : FS a a.head | tail (a : stream M) (m : M) (h : FS a.tail m) : FS a m | cons (a : stream M) (m : M) (h : FS a.tail m) : FS a (a.head + m) /-- `FP a` is the set of finite products in `a`, i.e. `m ∈ FP a` if `m` is the product of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ @[to_additive FS] inductive FP {M} [semigroup M] : stream M → set M | head (a : stream M) : FP a a.head | tail (a : stream M) (m : M) (h : FP a.tail m) : FP a m | cons (a : stream M) (m : M) (h : FP a.tail m) : FP a (a.head * m) /-- If `m` and `m'` are finite products in `M`, then so is `m * m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late. -/ @[to_additive "If `m` and `m'` are finite sums in `M`, then so is `m + m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late."] lemma FP.mul {M} [semigroup M] {a : stream M} {m : M} (hm : m ∈ FP a) : ∃ n, ∀ m' ∈ FP (a.drop n), m * m' ∈ FP a := begin induction hm with a a m hm ih a m hm ih, { exact ⟨1, λ m hm, FP.cons a m hm⟩, }, { cases ih with n hn, use n+1, intros m' hm', exact FP.tail _ _ (hn _ hm'), }, { cases ih with n hn, use n+1, intros m' hm', rw mul_assoc, exact FP.cons _ _ (hn _ hm'), }, end @[to_additive exists_idempotent_ultrafilter_le_FS] lemma exists_idempotent_ultrafilter_le_FP {M} [semigroup M] (a : stream M) : ∃ U : ultrafilter M, U * U = U ∧ ∀ᶠ m in U, m ∈ FP a := begin let S : set (ultrafilter M) := ⋂ n, { U | ∀ᶠ m in U, m ∈ FP (a.drop n) }, obtain ⟨U, hU, U_idem⟩ := exists_idempotent_in_compact_subsemigroup _ S _ _ _, { refine ⟨U, U_idem, _⟩, convert set.mem_Inter.mp hU 0, }, { exact ultrafilter.continuous_mul_left }, { apply is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed, { intros n U hU, apply eventually.mono hU, rw [add_comm, ←stream.drop_drop, ←stream.tail_eq_drop], exact FP.tail _ }, { intro n, exact ⟨pure _, mem_pure.mpr $ FP.head _⟩, }, { exact (ultrafilter_is_closed_basic _).is_compact, }, { intro n, apply ultrafilter_is_closed_basic, }, }, { exact is_closed.is_compact (is_closed_Inter $ λ i, ultrafilter_is_closed_basic _) }, { intros U hU V hV, rw set.mem_Inter at *, intro n, rw [set.mem_set_of_eq, ultrafilter.eventually_mul], apply eventually.mono (hU n), intros m hm, obtain ⟨n', hn⟩ := FP.mul hm, apply eventually.mono (hV (n' + n)), intros m' hm', apply hn, simpa only [stream.drop_drop] using hm', } end @[to_additive exists_FS_of_large] lemma exists_FP_of_large {M} [semigroup M] (U : ultrafilter M) (U_idem : U * U = U) (s₀ : set M) (sU : s₀ ∈ U) : ∃ a, FP a ⊆ s₀ := begin /- Informally: given a `U`-large set `s₀`, the set `s₀ ∩ { m | ∀ᶠ m' in U, m * m' ∈ s₀ }` is also `U`-large (since `U` is idempotent). Thus in particular there is an `a₀` in this intersection. Now let `s₁` be the intersection `s₀ ∩ { m | a₀ * m ∈ s₀ }`. By choice of `a₀`, this is again `U`-large, so we can repeat the argument starting from `s₁`, obtaining `a₁`, `s₂`, etc. This gives the desired infinite sequence. -/ have exists_elem : ∀ {s : set M} (hs : s ∈ U), (s ∩ { m | ∀ᶠ m' in U, m * m' ∈ s }).nonempty := λ s hs, ultrafilter.nonempty_of_mem (inter_mem hs $ by { rw ←U_idem at hs, exact hs }), let elem : { s // s ∈ U } → M := λ p, (exists_elem p.property).some, let succ : { s // s ∈ U } → { s // s ∈ U } := λ p, ⟨p.val ∩ { m | elem p * m ∈ p.val }, inter_mem p.2 $ show _, from set.inter_subset_right _ _ (exists_elem p.2).some_mem⟩, use stream.corec elem succ (subtype.mk s₀ sU), suffices : ∀ (a : stream M) (m ∈ FP a), ∀ p, a = stream.corec elem succ p → m ∈ p.val, { intros m hm, exact this _ m hm ⟨s₀, sU⟩ rfl, }, clear sU s₀, intros a m h, induction h with b b n h ih b n h ih, { rintros p rfl, rw [stream.corec_eq, stream.head_cons], exact set.inter_subset_left _ _ (set.nonempty.some_mem _), }, { rintros p rfl, refine set.inter_subset_left _ _ (ih (succ p) _), rw [stream.corec_eq, stream.tail_cons], }, { rintros p rfl, have := set.inter_subset_right _ _ (ih (succ p) _), { simpa only using this }, rw [stream.corec_eq, stream.tail_cons], }, end /-- The strong form of **Hindman's theorem**: in any finite cover of an FP-set, one the parts contains an FP-set. -/ @[to_additive FS_partition_regular "The strong form of **Hindman's theorem**: in any finite cover of an FS-set, one the parts contains an FS-set."] lemma FP_partition_regular {M} [semigroup M] (a : stream M) (s : set (set M)) (sfin : s.finite) (scov : FP a ⊆ ⋃₀ s) : ∃ (c ∈ s) (b : stream M), FP b ⊆ c := let ⟨U, idem, aU⟩ := exists_idempotent_ultrafilter_le_FP a in let ⟨c, cs, hc⟩ := (ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset aU scov) in ⟨c, cs, exists_FP_of_large U idem c hc⟩ /-- The weak form of **Hindman's theorem**: in any finite cover of a nonempty semigroup, one of the parts contains an FP-set. -/ @[to_additive exists_FS_of_finite_cover "The weak form of **Hindman's theorem**: in any finite cover of a nonempty additive semigroup, one of the parts contains an FS-set."] lemma exists_FP_of_finite_cover {M} [semigroup M] [nonempty M] (s : set (set M)) (sfin : s.finite) (scov : ⊤ ⊆ ⋃₀ s) : ∃ (c ∈ s) (a : stream M), FP a ⊆ c := let ⟨U, hU⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left (@ultrafilter.continuous_mul_left M _) in let ⟨c, c_s, hc⟩ := (ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset univ_mem scov) in ⟨c, c_s, exists_FP_of_large U hU c hc⟩ @[to_additive FS_iter_tail_sub_FS] lemma FP_drop_subset_FP {M} [semigroup M] (a : stream M) (n : ℕ) : FP (a.drop n) ⊆ FP a := begin induction n with n ih, { refl }, rw [nat.succ_eq_one_add, ←stream.drop_drop], exact trans (FP.tail _) ih, end @[to_additive] lemma FP.singleton {M} [semigroup M] (a : stream M) (i : ℕ) : a.nth i ∈ FP a := by { induction i with i ih generalizing a, { apply FP.head }, { apply FP.tail, apply ih } } @[to_additive] lemma FP.mul_two {M} [semigroup M] (a : stream M) (i j : ℕ) (ij : i < j) : a.nth i * a.nth j ∈ FP a := begin refine FP_drop_subset_FP _ i _, rw ←stream.head_drop, apply FP.cons, rcases le_iff_exists_add.mp (nat.succ_le_of_lt ij) with ⟨d, hd⟩, have := FP.singleton (a.drop i).tail d, rw [stream.tail_eq_drop, stream.nth_drop, stream.nth_drop] at this, convert this, rw [hd, add_comm, nat.succ_add, nat.add_succ], end @[to_additive] lemma FP.finset_prod {M} [comm_monoid M] (a : stream M) (s : finset ℕ) (hs : s.nonempty) : s.prod (λ i, a.nth i) ∈ FP a := begin refine FP_drop_subset_FP _ (s.min' hs) _, induction s using finset.strong_induction with s ih, rw [←finset.mul_prod_erase _ _ (s.min'_mem hs), ←stream.head_drop], cases (s.erase (s.min' hs)).eq_empty_or_nonempty with h h, { rw [h, finset.prod_empty, mul_one], exact FP.head _ }, { apply FP.cons, rw [stream.tail_eq_drop, stream.drop_drop, add_comm], refine set.mem_of_subset_of_mem _ (ih _ (finset.erase_ssubset $ s.min'_mem hs) h), have : s.min' hs + 1 ≤ (s.erase (s.min' hs)).min' h := nat.succ_le_of_lt (finset.min'_lt_of_mem_erase_min' _ _ $ finset.min'_mem _ _), cases le_iff_exists_add.mp this with d hd, rw [hd, add_comm, ←stream.drop_drop], apply FP_drop_subset_FP } end end hindman
3b10d5a0b177d28821e7b17cfc3b869afe08efea
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/measure_theory/outer_measure.lean
ff1c99243f277c9b823b4ac0cce4d501a4d697d6
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
19,849
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Outer measures -- overapproximations of measures -/ import analysis.specific_limits import measure_theory.measurable_space noncomputable theory open set finset function filter encodable open_locale classical namespace measure_theory structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑'i, measure_of (s i))) namespace outer_measure instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ section basic variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α} @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0) {β} [encodable β] (s : β → set α) : (∑' b, m (s b)) = ∑' i, m (⋃ b ∈ decode2 β i, s b) := begin have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some, { intros n h, cases decode2 β n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 β n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑'i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := begin convert m.Union (λ b, cond b s₁ s₂), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ @[ext] lemma ext : ∀{μ₁ μ₂ : outer_measure α}, (∀s, μ₁ s = μ₂ s) → μ₁ = μ₂ | ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add' (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, zero_add _ } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≤ (∑' (i : ℕ), m.val (f i)) : m.val.Union_nat _ ... ≤ (∑'i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩ protected lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms := λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩ protected lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m := λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩ protected lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := outer_measure.Sup_le $ assume m' h', h' _ hm protected lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := outer_measure.le_Sup hm instance : complete_lattice (outer_measure α) := { top := Sup univ, le_top := assume a, outer_measure.le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, outer_measure.Sup_le, le_Sup := assume s m, outer_measure.le_Sup, Inf := Inf, Inf_le := assume s m, outer_measure.Inf_le, le_Inf := assume s m, outer_measure.le_Inf, sup := λa b, Sup {a, b}, le_sup_left := assume a b, outer_measure.le_Sup $ by simp, le_sup_right := assume a b, outer_measure.le_Sup $ by simp, sup_le := assume a b c ha hb, outer_measure.Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := λa b, Inf {a, b}, inf_le_left := assume a b, outer_measure.Inf_le $ by simp, inf_le_right := assume a b, outer_measure.Inf_le $ by simp, le_inf := assume a b c ha hb, outer_measure.le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ λ i, le_supr (λ (m : {a : outer_measure α // ∃ i, f i = a}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum def map {β} (f : α → β) (m : outer_measure α) : outer_measure β := { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β, map} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl instance : has_scalar ennreal (outer_measure α) := ⟨λ a m, { measure_of := λs, a * m s, empty := by simp, mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := λ s, by rw ennreal.tsum_mul_left; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) : (a • m) s = a * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _, add_smul := λ a b m, ext $ λ s, add_mul _ _ _, mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _, one_smul := λ m, ext $ λ s, one_mul _, zero_smul := λ m, ext $ λ s, zero_mul _, smul_zero := λ a, ext $ λ s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := h in top_unique $ le_supr_of_le ⟨(⊤ : ennreal) • dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑'i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑'i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑'i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq, add_comm] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂) private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end private def caratheodory_dynkin : measurable_space.dynkin_system α := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `μ`, the Caratheodory measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter lemma is_caratheodory {s : set α} : caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set α} : caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable s := let o := (outer_measure.of_function m h₀) in (is_caratheodory_le o).2 $ λ t, le_infi $ λ f, le_infi $ λ hf, begin refine le_trans (add_le_add' (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal := ⨆(h : s.nonempty), ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s @[simp] lemma Inf_gen_empty (m : set (outer_measure α)) : Inf_gen m ∅ = 0 := by simp [Inf_gen, empty_not_nonempty] lemma Inf_gen_nonempty1 (m : set (outer_measure α)) (t : set α) (h : t.nonempty) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := by rw [Inf_gen, supr_pos h] lemma Inf_gen_nonempty2 (m : set (outer_measure α)) (μ) (h : μ ∈ m) (t) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin cases t.eq_empty_or_nonempty with ht ht, { simp [ht], refine (bot_unique $ infi_le_of_le μ $ _).symm, refine infi_le_of_le h (le_refl ⊥) }, { exact Inf_gen_nonempty1 m t ht } end lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) := begin refine le_antisymm (assume t', le_of_function.2 (assume t, _) _) (_root_.le_Inf $ assume μ hμ t, le_trans (outer_measure.of_function_le _ _ _) _); cases t.eq_empty_or_nonempty with ht ht; simp [ht, Inf_gen_nonempty1], { assume μ hμ, exact (show Inf m ≤ μ, from _root_.Inf_le hμ) t }, { exact infi_le_of_le μ (infi_le _ hμ) } end end Inf_gen end outer_measure end measure_theory
909cac2d8fab62f05630da920d219a47c3e02308
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/hott/init/types/prod.hlean
77885a0ee8cd8779b24ffe53af18c29dafbad53e
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,584
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.types.prod Author: Leonardo de Moura, Jeremy Avigad -/ prelude import ..wf ..num definition pair := @prod.mk namespace prod notation A * B := prod A B notation A × B := prod A B namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 abbreviation pr₁ := @pr1 abbreviation pr₂ := @pr2 end ops namespace low_precedence_times reserve infixr `*`:30 -- conflicts with notation for multiplication infixr `*` := prod end low_precedence_times -- TODO: add lemmas about flip to hott/types/prod.hlean definition flip {A B : Type} (a : A × B) : B × A := pair (pr2 a) (pr1 a) notation `pr₁` := pr1 notation `pr₂` := pr2 -- notation for n-ary tuples notation `(` h `,` t:(foldl `,` (e r, prod.mk r e) h) `)` := t open well_founded section variables {A B : Type} variable (Ra : A → A → Type) variable (Rb : B → B → Type) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Type := | left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Type := intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end context parameters {A B : Type} parameters {Ra : A → A → Type} {Rb : B → B → Type} infix `≺`:50 := lex Ra Rb definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)), λb, acc.rec_on (acb b) (λxb acb (iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @prod.lex.rec_on A B Ra Rb (λp₁ p₂ h, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λa b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb) end end prod
4ef7e6ed0b9c2505a3abd6d2f9d7348adca7bec2
e429a7c31201d4c56a2716f77a99c4831967b0de
/gcd.lean
abb0de5977a50711aaadf82fefe5396e708919bd
[]
no_license
jthickstun/lean
cdb5ee8ec78294167d771a6167c0947419afa9eb
8254b987f06be1f98ef2e0cc33b7d4655d77dc85
refs/heads/master
1,620,156,057,836
1,557,865,724,000
1,557,865,724,000
106,618,304
8
1
null
null
null
null
UTF-8
Lean
false
false
2,149
lean
import .definitions namespace nt /- We've committed a minor sin here. We use a computational definition of gcd (Euclid's algorithm) but we never actually prove that it computes the gcd; we just state enough properties of it to ram through the proof of Euclid's lemma. This is fine from a formal perspective, but the pedagogy leaves something to be desired. One question is whether we need to talk about Euclid's algorithm at all? Is it possible to give a conceptual definition of gcd, get these 5 facts and proceed from there to Euclid's lemma? Are there going to be decidability issues that force us to write down the computational definition anyway if we go this route? -/ -- ripped from mathlib lemma gcd_dvd (m n : ℕ) : (nat.gcd m n ∣ m) ∧ (nat.gcd m n ∣ n) := nat.gcd.induction m n (λn, by rw nat.gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←nat.gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (nat.dvd_mod_iff IH₂).1 IH₁⟩) -- ripped from mathlib lemma dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ nat.gcd m n := nat.gcd.induction m n (λn _ kn, by rw nat.gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw nat.gcd_rec; exact IH ((nat.dvd_mod_iff H1).2 H2) H1) -- ripped from mathlib lemma gcd_mul_left (m n k : ℕ) : nat.gcd (m * n) (m * k) = m * nat.gcd n k := nat.gcd.induction n k (λk, by repeat {rw nat.mul_zero <|> rw nat.gcd_zero_left}) (λk n H IH, by rwa [←nat.mul_mod_mul_left, ←nat.gcd_rec, ←nat.gcd_rec] at IH) -- ripped from mathlib lemma gcd_mul_right (m n k : ℕ) : nat.gcd (m * n) (k * n) = nat.gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (nat.gcd m k) n, gcd_mul_left] lemma p_not_dvd_coprime {p n : ℕ} : ¬ p ∣ n → irreducible p → nat.gcd p n = 1 := begin intros, simp [irreducible] at a_1, have hdiv : (nat.gcd p n ∣ p) ∧ (nat.gcd p n ∣ n), from gcd_dvd p n, have : nat.gcd p n ∣ p, from hdiv.left, have h : nat.gcd p n = p ∨ nat.gcd p n = 1, from a_1.right.right (nat.gcd p n) this, cases h, { have : p ∣ n, by simp [a_2] at hdiv; exact hdiv, contradiction }, { assumption } end end nt
6fcb3a90653325537476a4b8a627eb7196d8cd71
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/category_theory/abelian/opposite.lean
5f7725253b888cfa84a71723e62c7aaefa94a116
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
4,099
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.abelian.basic import category_theory.preadditive.opposite import category_theory.limits.opposites import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # The opposite of an abelian category is abelian. -/ noncomputable theory namespace category_theory open category_theory.limits variables (C : Type*) [category C] [abelian C] local attribute [instance] has_finite_limits_of_has_equalizers_and_finite_products has_finite_colimits_of_has_coequalizers_and_finite_coproducts has_finite_limits_opposite has_finite_colimits_opposite has_finite_products_opposite instance : abelian Cᵒᵖ := { normal_mono_of_mono := λ X Y f m, by exactI normal_mono_of_normal_epi_unop _ (normal_epi_of_epi f.unop), normal_epi_of_epi := λ X Y f m, by exactI normal_epi_of_normal_mono_unop _ (normal_mono_of_mono f.unop), } section variables {C} {X Y : C} (f : X ⟶ Y) {A B : Cᵒᵖ} (g : A ⟶ B) -- TODO: Generalize (this will work whenever f has a cokernel) -- (The abelian case is probably sufficient for most applications.) /-- The kernel of `f.op` is the opposite of `cokernel f`. -/ @[simps] def kernel_op_unop : (kernel f.op).unop ≅ cokernel f := { hom := (kernel.lift f.op (cokernel.π f).op $ by simp [← op_comp]).unop, inv := cokernel.desc f (kernel.ι f.op).unop $ by { rw [← f.unop_op, ← unop_comp, f.unop_op], simp }, hom_inv_id' := begin rw [← unop_id, ← (cokernel.desc f _ _).unop_op, ← unop_comp], congr' 1, dsimp, ext, simp [← op_comp], end, inv_hom_id' := begin dsimp, ext, simp [← unop_comp], end } -- TODO: Generalize (this will work whenever f has a kernel) -- (The abelian case is probably sufficient for most applications.) /-- The cokernel of `f.op` is the opposite of `kernel f`. -/ @[simps] def cokernel_op_unop : (cokernel f.op).unop ≅ kernel f := { hom := kernel.lift f (cokernel.π f.op).unop $ by { rw [← f.unop_op, ← unop_comp, f.unop_op], simp }, inv := (cokernel.desc f.op (kernel.ι f).op $ by simp [← op_comp]).unop, hom_inv_id' := begin rw [← unop_id, ← (kernel.lift f _ _).unop_op, ← unop_comp], congr' 1, dsimp, ext, simp [← op_comp], end, inv_hom_id' := begin dsimp, ext, simp [← unop_comp], end } /-- The kernel of `g.unop` is the opposite of `cokernel g`. -/ @[simps] def kernel_unop_op : opposite.op (kernel g.unop) ≅ cokernel g := (cokernel_op_unop g.unop).op /-- The cokernel of `g.unop` is the opposite of `kernel g`. -/ @[simps] def cokernel_unop_op : opposite.op (cokernel g.unop) ≅ kernel g := (kernel_op_unop g.unop).op lemma cokernel.π_op : (cokernel.π f.op).unop = (cokernel_op_unop f).hom ≫ kernel.ι f ≫ eq_to_hom (opposite.unop_op _).symm := by simp [cokernel_op_unop] lemma kernel.ι_op : (kernel.ι f.op).unop = eq_to_hom (opposite.unop_op _) ≫ cokernel.π f ≫ (kernel_op_unop f).inv := by simp [kernel_op_unop] /-- The kernel of `f.op` is the opposite of `cokernel f`. -/ @[simps] def kernel_op_op : kernel f.op ≅ opposite.op (cokernel f) := (kernel_op_unop f).op.symm /-- The cokernel of `f.op` is the opposite of `kernel f`. -/ @[simps] def cokernel_op_op : cokernel f.op ≅ opposite.op (kernel f) := (cokernel_op_unop f).op.symm /-- The kernel of `g.unop` is the opposite of `cokernel g`. -/ @[simps] def kernel_unop_unop : kernel g.unop ≅ (cokernel g).unop := (kernel_unop_op g).unop.symm lemma kernel.ι_unop : (kernel.ι g.unop).op = eq_to_hom (opposite.op_unop _) ≫ cokernel.π g ≫ (kernel_unop_op g).inv := by simp lemma cokernel.π_unop : (cokernel.π g.unop).op = (cokernel_unop_op g).hom ≫ kernel.ι g ≫ eq_to_hom (opposite.op_unop _).symm := by simp /-- The cokernel of `g.unop` is the opposite of `kernel g`. -/ @[simps] def cokernel_unop_unop : cokernel g.unop ≅ (kernel g).unop := (cokernel_unop_op g).unop.symm end end category_theory
b07f00980fa665d4a3a3013b291e9eec2e6687fa
26ac254ecb57ffcb886ff709cf018390161a9225
/src/meta/expr.lean
c08ea34386e2906a80d0c69eefca2443e2282c96
[ "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
36,035
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` 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. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` 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`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Returns true if `e` contains a `sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
83e50d747ddac7a7a3ef52476835d35f4a09f708
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/enriched/products.lean
23674f6fd042784e01f719911602dfe0d485f3fd
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
990
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 .enriched_category import ..monoidal_categories.braided_monoidal_category namespace tqft.categories.enriched.products open tqft.categories open tqft.categories.enriched open tqft.categories.monoidal_category open tqft.categories.braided_monoidal_category -- definition ProductCategory { V : Category } { m : MonoidalStructure V } { σ : Symmetry m } ( C D : EnrichedCategory m ) : EnrichedCategory m := { -- Obj := C.Obj × D.Obj, -- Hom := λ X Y, m.tensorObjects (C.Hom X.1 Y.1) (D.Hom X.2 Y.2), -- compose := λ X Y Z, sorry, -- PROJECT Writing this requires so many associators! we better provide some help. -- identity := sorry, -- left_identity := sorry, -- right_identity := sorry, -- associativity := sorry -- } end tqft.categories.enriched.products
f117bf134e1e77dbe0db82df1b5f91d7a8d4d639
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/unused_univ.lean
082886d22825f9205595e67077f2b20642a65667
[ "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
273
lean
-- variable (y : Nat) def f.{u} (x : Nat) : Nat := -- error unused universe parameter 'u' x universe u def f.{v, w} (α : Type v) (a : α) : α := -- error unused universe parameter 'w' a axiom f.{w} (α : Type u) (a : α) : α -- error unused universe parameter 'w'
a867774f10a478913985749dc1ffc1672730d102
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/module/torsion.lean
aac753fdcdd609e965b857127a96542ef15ea43a
[ "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
21,347
lean
/- Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pierre-Alexandre Bazin -/ import algebra.module import linear_algebra.quotient import ring_theory.ideal.quotient import ring_theory.non_zero_divisors import algebra.direct_sum.module import group_theory.torsion import linear_algebra.isomorphisms import group_theory.torsion /-! # Torsion submodules ## Main definitions * `torsion_of R M x` : the torsion ideal of `x`, containing all `a` such that `a • x = 0`. * `submodule.torsion_by R M a` : the `a`-torsion submodule, containing all elements `x` of `M` such that `a • x = 0`. * `submodule.torsion_by_set R M s` : the submodule containing all elements `x` of `M` such that `a • x = 0` for all `a` in `s`. * `submodule.torsion' R M S` : the `S`-torsion submodule, containing all elements `x` of `M` such that `a • x = 0` for some `a` in `S`. * `submodule.torsion R M` : the torsion submoule, containing all elements `x` of `M` such that `a • x = 0` for some non-zero-divisor `a` in `R`. * `module.is_torsion_by R M a` : the property that defines a `a`-torsion module. Similarly, `is_torsion_by_set`, `is_torsion'` and `is_torsion`. * `module.is_torsion_by_set.module` : Creates a `R ⧸ I`-module from a `R`-module that `is_torsion_by_set R _ I`. ## Main statements * `quot_torsion_of_equiv_span_singleton` : isomorphism between the span of an element of `M` and the quotient by its torsion ideal. * `torsion' R M S` and `torsion R M` are submodules. * `torsion_by_set_eq_torsion_by_span` : torsion by a set is torsion by the ideal generated by it. * `submodule.torsion_by_is_torsion_by` : the `a`-torsion submodule is a `a`-torsion module. Similar lemmas for `torsion'` and `torsion`. * `submodule.torsion_is_internal` : a `∏ i, p i`-torsion module is the internal direct sum of its `p i`-torsion submodules when the `p i` are pairwise coprime. * `submodule.no_zero_smul_divisors_iff_torsion_bot` : a module over a domain has `no_zero_smul_divisors` (that is, there is no non-zero `a`, `x` such that `a • x = 0`) iff its torsion submodule is trivial. * `submodule.quotient_torsion.torsion_eq_bot` : quotienting by the torsion submodule makes the torsion submodule of the new module trivial. If `R` is a domain, we can derive an instance `submodule.quotient_torsion.no_zero_smul_divisors : no_zero_smul_divisors R (M ⧸ torsion R M)`. ## Notation * The notions are defined for a `comm_semiring R` and a `module R M`. Some additional hypotheses on `R` and `M` are required by some lemmas. * The letters `a`, `b`, ... are used for scalars (in `R`), while `x`, `y`, ... are used for vectors (in `M`). ## Tags Torsion, submodule, module, quotient -/ section variables (R M : Type*) [semiring R] [add_comm_monoid M] [module R M] /--The torsion ideal of `x`, containing all `a` such that `a • x = 0`.-/ @[simps] def torsion_of (x : M) : ideal R := (linear_map.to_span_singleton R M x).ker variables {R M} @[simp] lemma mem_torsion_of_iff (x : M) (a : R) : a ∈ torsion_of R M x ↔ a • x = 0 := iff.rfl end section variables (R M : Type*) [ring R] [add_comm_group M] [module R M] /--The span of `x` in `M` is isomorphic to `R` quotiented by the torsion ideal of `x`.-/ noncomputable def quot_torsion_of_equiv_span_singleton (x : M) : (R ⧸ torsion_of R M x) ≃ₗ[R] (R ∙ x) := (linear_map.to_span_singleton R M x).quot_ker_equiv_range.trans $ linear_equiv.of_eq _ _ (linear_map.span_singleton_eq_range R M x).symm @[simp] lemma quot_torsion_of_equiv_span_singleton_apply_mk (x : M) (a : R) : quot_torsion_of_equiv_span_singleton R M x (submodule.quotient.mk a) = a • ⟨x, submodule.mem_span_singleton_self x⟩ := rfl end open_locale non_zero_divisors section defs variables (R M : Type*) [comm_semiring R] [add_comm_monoid M] [module R M] namespace submodule /-- The `a`-torsion submodule for `a` in `R`, containing all elements `x` of `M` such that `a • x = 0`. -/ @[simps] def torsion_by (a : R) : submodule R M := (distrib_mul_action.to_linear_map _ _ a).ker /-- The submodule containing all elements `x` of `M` such that `a • x = 0` for all `a` in `s`. -/ @[simps] def torsion_by_set (s : set R) : submodule R M := Inf (torsion_by R M '' s) /-- The `S`-torsion submodule, containing all elements `x` of `M` such that `a • x = 0` for some `a` in `S`. -/ @[simps] def torsion' (S : Type*) [comm_monoid S] [distrib_mul_action S M] [smul_comm_class S R M] : submodule R M := { carrier := { x | ∃ a : S, a • x = 0 }, zero_mem' := ⟨1, smul_zero _⟩, add_mem' := λ x y ⟨a, hx⟩ ⟨b, hy⟩, ⟨b * a, by rw [smul_add, mul_smul, mul_comm, mul_smul, hx, hy, smul_zero, smul_zero, add_zero]⟩, smul_mem' := λ a x ⟨b, h⟩, ⟨b, by rw [smul_comm, h, smul_zero]⟩ } /-- The torsion submodule, containing all elements `x` of `M` such that `a • x = 0` for some non-zero-divisor `a` in `R`. -/ @[reducible] def torsion := torsion' R M R⁰ end submodule namespace module /-- A `a`-torsion module is a module where every element is `a`-torsion. -/ @[reducible] def is_torsion_by (a : R) := ∀ ⦃x : M⦄, a • x = 0 /-- A module where every element is `a`-torsion for all `a` in `s`. -/ @[reducible] def is_torsion_by_set (s : set R) := ∀ ⦃x : M⦄ ⦃a : s⦄, (a : R) • x = 0 /-- A `S`-torsion module is a module where every element is `a`-torsion for some `a` in `S`. -/ @[reducible] def is_torsion' (S : Type*) [has_scalar S M] := ∀ ⦃x : M⦄, ∃ a : S, a • x = 0 /-- A torsion module is a module where every element is `a`-torsion for some non-zero-divisor `a`. -/ @[reducible] def is_torsion := ∀ ⦃x : M⦄, ∃ a : R⁰, a • x = 0 end module end defs variables {R M : Type*} namespace submodule open module variables [comm_semiring R] [add_comm_monoid M] [module R M] (s : set R) (a : R) @[simp] lemma smul_torsion_by (x : torsion_by R M a) : a • x = 0 := subtype.ext x.prop @[simp] lemma smul_coe_torsion_by (x : torsion_by R M a) : a • (x : M) = 0 := x.prop @[simp] lemma mem_torsion_by_iff (x : M) : x ∈ torsion_by R M a ↔ a • x = 0 := iff.rfl @[simp] lemma mem_torsion_by_set_iff (x : M) : x ∈ torsion_by_set R M s ↔ ∀ a : s, (a : R) • x = 0 := begin refine ⟨λ h ⟨a, ha⟩, mem_Inf.mp h _ (set.mem_image_of_mem _ ha), λ h, mem_Inf.mpr _⟩, rintro _ ⟨a, ha, rfl⟩, exact h ⟨a, ha⟩ end @[simp] lemma torsion_by_singleton_eq : torsion_by_set R M {a} = torsion_by R M a := begin ext x, simp only [mem_torsion_by_set_iff, set_coe.forall, subtype.coe_mk, set.mem_singleton_iff, forall_eq, mem_torsion_by_iff] end @[simp] lemma is_torsion_by_singleton_iff : is_torsion_by_set R M {a} ↔ is_torsion_by R M a := begin refine ⟨λ h x, @h _ ⟨_, set.mem_singleton _⟩, λ h x, _⟩, rintro ⟨b, rfl : b = a⟩, exact @h _ end lemma is_torsion_by_set_iff_torsion_by_set_eq_top : is_torsion_by_set R M s ↔ torsion_by_set R M s = ⊤ := ⟨λ h, eq_top_iff.mpr (λ _ _, (mem_torsion_by_set_iff _ _).mpr $ @h _), λ h x, by { rw [← mem_torsion_by_set_iff, h], trivial }⟩ /-- A `a`-torsion module is a module whose `a`-torsion submodule is the full space. -/ lemma is_torsion_by_iff_torsion_by_eq_top : is_torsion_by R M a ↔ torsion_by R M a = ⊤ := by rw [← torsion_by_singleton_eq, ← is_torsion_by_singleton_iff, is_torsion_by_set_iff_torsion_by_set_eq_top] lemma torsion_by_set_is_torsion_by_set : is_torsion_by_set R (torsion_by_set R M s) s := λ ⟨x, hx⟩ a, subtype.ext $ (mem_torsion_by_set_iff _ _).mp hx a /-- The `a`-torsion submodule is a `a`-torsion module. -/ lemma torsion_by_is_torsion_by : is_torsion_by R (torsion_by R M a) a := λ _, smul_torsion_by _ _ @[simp] lemma torsion_by_torsion_by_eq_top : torsion_by R (torsion_by R M a) a = ⊤ := (is_torsion_by_iff_torsion_by_eq_top a).mp $ torsion_by_is_torsion_by a @[simp] lemma torsion_by_set_torsion_by_set_eq_top : torsion_by_set R (torsion_by_set R M s) s = ⊤ := (is_torsion_by_set_iff_torsion_by_set_eq_top s).mp $ torsion_by_set_is_torsion_by_set s lemma torsion_by_set_le_torsion_by_set_of_subset {s t : set R} (st : s ⊆ t) : torsion_by_set R M t ≤ torsion_by_set R M s := Inf_le_Inf $ λ _ ⟨a, ha, h⟩, ⟨a, st ha, h⟩ /-- Torsion by a set is torsion by the ideal generated by it. -/ lemma torsion_by_set_eq_torsion_by_span : torsion_by_set R M s = torsion_by_set R M (ideal.span s) := begin refine le_antisymm (λ x hx, _) (torsion_by_set_le_torsion_by_set_of_subset subset_span), rw mem_torsion_by_set_iff at hx ⊢, suffices : ideal.span s ≤ torsion_of R M x, { rintro ⟨a, ha⟩, exact this ha }, rw ideal.span_le, exact λ a ha, hx ⟨a, ha⟩ end lemma is_torsion_by_set_iff_is_torsion_by_span : is_torsion_by_set R M s ↔ is_torsion_by_set R M (ideal.span s) := by rw [is_torsion_by_set_iff_torsion_by_set_eq_top, is_torsion_by_set_iff_torsion_by_set_eq_top, torsion_by_set_eq_torsion_by_span] lemma torsion_by_span_singleton_eq : torsion_by_set R M (R ∙ a) = torsion_by R M a := ((torsion_by_set_eq_torsion_by_span _).symm.trans $ torsion_by_singleton_eq _) lemma is_torsion_by_span_singleton_iff : is_torsion_by_set R M (R ∙ a) ↔ is_torsion_by R M a := ((is_torsion_by_set_iff_is_torsion_by_span _).symm.trans $ is_torsion_by_singleton_iff _) lemma torsion_by_le_torsion_by_of_dvd (a b : R) (dvd : a ∣ b) : torsion_by R M a ≤ torsion_by R M b := begin rw [← torsion_by_span_singleton_eq, ← torsion_by_singleton_eq], apply torsion_by_set_le_torsion_by_set_of_subset, rintro c (rfl : c = b), exact ideal.mem_span_singleton.mpr dvd end @[simp] lemma torsion_by_one : torsion_by R M 1 = ⊥ := eq_bot_iff.mpr (λ _ h, by { rw [mem_torsion_by_iff, one_smul] at h, exact h }) @[simp] lemma torsion_by_univ : torsion_by_set R M set.univ = ⊥ := by { rw [eq_bot_iff, ← torsion_by_one, ← torsion_by_singleton_eq], exact torsion_by_set_le_torsion_by_set_of_subset (λ _ _, trivial) } section coprime open_locale big_operators open dfinsupp variables {ι : Type*} {p : ι → R} {S : finset ι} (hp : pairwise (is_coprime on λ s : S, p s)) include hp lemma supr_torsion_by_eq_torsion_by_prod : (⨆ i : S, torsion_by R M (p i)) = torsion_by R M (∏ i in S, p i) := begin cases S.eq_empty_or_nonempty with h h, { rw [h, finset.prod_empty, torsion_by_one], convert supr_of_empty _, exact subtype.is_empty_false }, apply le_antisymm, { apply supr_le _, rintro ⟨i, is⟩, exact torsion_by_le_torsion_by_of_dvd _ _ (finset.dvd_prod_of_mem p is) }, { intros x hx, classical, rw mem_supr_iff_exists_dfinsupp', cases (exists_sum_eq_one_iff_pairwise_coprime h).mpr hp with f hf, use equiv_fun_on_fintype.inv_fun (λ i, ⟨(f i * ∏ j in S \ {i}, p j) • x, begin obtain ⟨i, is⟩ := i, change p i • (f i * ∏ j in S \ {i}, _) • _ = _, change _ • _ = _ at hx, rw [smul_smul, mul_comm, mul_assoc, mul_smul, ← finset.prod_eq_prod_diff_singleton_mul is, hx, smul_zero] end⟩), simp only [equiv.inv_fun_as_coe, sum_eq_sum_fintype, coe_eq_zero, eq_self_iff_true, implies_true_iff, finset.univ_eq_attach, equiv_fun_on_fintype_apply], change ∑ i : S, ((f i * ∏ j in S \ {i}, p j) • x) = x, have : ∑ i : S, _ = _ := S.sum_finset_coe (λ i, f i * ∏ j in S \ {i}, p j), rw [← finset.sum_smul, this, hf, one_smul] } end lemma torsion_by_independent : complete_lattice.independent (λ i : S, torsion_by R M (p i)) := λ i, begin classical, dsimp, rw [disjoint_iff, eq_bot_iff], intros x hx, rw submodule.mem_inf at hx, obtain ⟨hxi, hxj⟩ := hx, have hxi : p i • x = 0 := hxi, rw mem_supr_iff_exists_dfinsupp' at hxj, cases hxj with f hf, obtain ⟨b, c, h1⟩ := pairwise_coprime_iff_coprime_prod.mp hp i i.2, rw [mem_bot, ← one_smul _ x, ← h1, add_smul], convert (zero_add (0:M)), { rw [mul_smul, hxi, smul_zero] }, { rw [← hf, smul_sum, sum_eq_zero], intro j, by_cases ji : j = i, { convert smul_zero _, rw ← mem_bot _, convert coe_mem (f j), symmetry, rw supr_eq_bot, intro hj', exfalso, exact hj' ji }, { have hj' : ↑j ∈ S \ {i}, { rw finset.mem_sdiff, refine ⟨j.2, λ hj', ji _⟩, ext, rw ← finset.mem_singleton, exact hj' }, rw [finset.prod_eq_prod_diff_singleton_mul hj', ← mul_assoc, mul_smul], have : (⨆ (H : ¬j = i), torsion_by R M (p j)) ≤ torsion_by R M (p j) := supr_const_le, have : _ • _ = _ := this (coe_mem _), rw [this, smul_zero] } } end end coprime end submodule section needs_group variables [comm_ring R] [add_comm_group M] [module R M] namespace submodule open_locale big_operators variables {ι : Type*} {p : ι → R} {S : finset ι} (hp : pairwise (is_coprime on λ s : S, p s)) include hp /--If the `p i` are pairwise coprime, a `∏ i, p i`-torsion module is the internal direct sum of its `p i`-torsion submodules.-/ lemma torsion_is_internal [decidable_eq ι] (hM : torsion_by R M (∏ i in S, p i) = ⊤) : direct_sum.submodule_is_internal (λ i : S, torsion_by R M (p i)) := direct_sum.submodule_is_internal_of_independent_of_supr_eq_top (torsion_by_independent hp) (by { rw ← hM, exact supr_torsion_by_eq_torsion_by_prod hp}) end submodule namespace module variables {I : ideal R} (hM : is_torsion_by_set R M I) include hM /-- can't be an instance because hM can't be inferred -/ def is_torsion_by_set.has_scalar : has_scalar (R ⧸ I) M := { smul := λ b x, quotient.lift_on' b (• x) $ λ b₁ b₂ h, begin show b₁ • x = b₂ • x, have : (-b₁ + b₂) • x = 0 := @hM x ⟨_, h⟩, rw [add_smul, neg_smul, neg_add_eq_zero] at this, exact this end } @[simp] lemma is_torsion_by_set.mk_smul (b : R) (x : M) : by haveI := hM.has_scalar; exact ideal.quotient.mk I b • x = b • x := rfl /-- A `(R ⧸ I)`-module is a `R`-module which `is_torsion_by_set R M I`. -/ def is_torsion_by_set.module : module (R ⧸ I) M := @function.surjective.module_left _ _ _ _ _ _ _ hM.has_scalar _ ideal.quotient.mk_surjective (is_torsion_by_set.mk_smul hM) end module namespace submodule instance (I : ideal R) : module (R ⧸ I) (torsion_by_set R M I) := module.is_torsion_by_set.module $ torsion_by_set_is_torsion_by_set I @[simp] lemma torsion_by_set.mk_smul (I : ideal R) (b : R) (x : torsion_by_set R M I) : ideal.quotient.mk I b • x = b • x := rfl instance (I : ideal R) {S : Type*} [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] [is_scalar_tower S R R] : is_scalar_tower S (R ⧸ I) (torsion_by_set R M I) := { smul_assoc := λ b d x, quotient.induction_on' d $ λ c, (smul_assoc b c x : _) } /-- The `a`-torsion submodule as a `(R ⧸ R∙a)`-module. -/ instance (a : R) : module (R ⧸ R ∙ a) (torsion_by R M a) := module.is_torsion_by_set.module $ (is_torsion_by_span_singleton_iff a).mpr $ torsion_by_is_torsion_by a @[simp] lemma torsion_by.mk_smul (a b : R) (x : torsion_by R M a) : ideal.quotient.mk (R ∙ a) b • x = b • x := rfl instance (a : R) {S : Type*} [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] [is_scalar_tower S R R] : is_scalar_tower S (R ⧸ R ∙ a) (torsion_by R M a) := { smul_assoc := λ b d x, quotient.induction_on' d $ λ c, (smul_assoc b c x : _) } end submodule end needs_group namespace submodule section torsion' open module variables [comm_semiring R] [add_comm_monoid M] [module R M] variables (S : Type*) [comm_monoid S] [distrib_mul_action S M] [smul_comm_class S R M] @[simp] lemma mem_torsion'_iff (x : M) : x ∈ torsion' R M S ↔ ∃ a : S, a • x = 0 := iff.rfl @[simp] lemma mem_torsion_iff (x : M) : x ∈ torsion R M ↔ ∃ a : R⁰, a • x = 0 := iff.rfl @[simps] instance : has_scalar S (torsion' R M S) := ⟨λ s x, ⟨s • x, by { obtain ⟨x, a, h⟩ := x, use a, dsimp, rw [smul_comm, h, smul_zero] }⟩⟩ instance : distrib_mul_action S (torsion' R M S) := subtype.coe_injective.distrib_mul_action ((torsion' R M S).subtype).to_add_monoid_hom (λ (c : S) x, rfl) instance : smul_comm_class S R (torsion' R M S) := ⟨λ s a x, subtype.ext $ smul_comm _ _ _⟩ /-- A `S`-torsion module is a module whose `S`-torsion submodule is the full space. -/ lemma is_torsion'_iff_torsion'_eq_top : is_torsion' M S ↔ torsion' R M S = ⊤ := ⟨λ h, eq_top_iff.mpr (λ _ _, @h _), λ h x, by { rw [← @mem_torsion'_iff R, h], trivial }⟩ /-- The `S`-torsion submodule is a `S`-torsion module. -/ lemma torsion'_is_torsion' : is_torsion' (torsion' R M S) S := λ ⟨x, ⟨a, h⟩⟩, ⟨a, subtype.ext h⟩ @[simp] lemma torsion'_torsion'_eq_top : torsion' R (torsion' R M S) S = ⊤ := (is_torsion'_iff_torsion'_eq_top S).mp $ torsion'_is_torsion' S /-- The torsion submodule of the torsion submodule (viewed as a module) is the full torsion module. -/ @[simp] lemma torsion_torsion_eq_top : torsion R (torsion R M) = ⊤ := torsion'_torsion'_eq_top R⁰ /-- The torsion submodule is always a torsion module. -/ lemma torsion_is_torsion : module.is_torsion R (torsion R M) := torsion'_is_torsion' R⁰ lemma is_torsion'_powers_iff (p : R) : is_torsion' M (submonoid.powers p) ↔ ∀ x : M, ∃ n : ℕ, p ^ n • x = 0 := ⟨λ h x, let ⟨⟨a, ⟨n, rfl⟩⟩, hx⟩ := @h x in ⟨n, hx⟩, λ h x, let ⟨n, hn⟩ := h x in ⟨⟨_, ⟨n, rfl⟩⟩, hn⟩⟩ end torsion' section torsion variables [comm_semiring R] [add_comm_monoid M] [module R M] [no_zero_divisors R] [nontrivial R] lemma coe_torsion_eq_annihilator_ne_bot : (torsion R M : set M) = { x : M | (R ∙ x).annihilator ≠ ⊥ } := begin ext x, simp_rw [submodule.ne_bot_iff, mem_annihilator, mem_span_singleton], exact ⟨λ ⟨a, hax⟩, ⟨a, λ _ ⟨b, hb⟩, by rw [← hb, smul_comm, ← submonoid.smul_def, hax, smul_zero], non_zero_divisors.coe_ne_zero _⟩, λ ⟨a, hax, ha⟩, ⟨⟨_, mem_non_zero_divisors_of_ne_zero ha⟩, hax x ⟨1, one_smul _ _⟩⟩⟩ end /-- A module over a domain has `no_zero_smul_divisors` iff its torsion submodule is trivial. -/ lemma no_zero_smul_divisors_iff_torsion_eq_bot : no_zero_smul_divisors R M ↔ torsion R M = ⊥ := begin split; intro h, { haveI : no_zero_smul_divisors R M := h, rw eq_bot_iff, rintro x ⟨a, hax⟩, change (a : R) • x = 0 at hax, cases eq_zero_or_eq_zero_of_smul_eq_zero hax with h0 h0, { exfalso, exact non_zero_divisors.coe_ne_zero a h0 }, { exact h0 } }, { exact { eq_zero_or_eq_zero_of_smul_eq_zero := λ a x hax, begin by_cases ha : a = 0, { left, exact ha }, { right, rw [← mem_bot _, ← h], exact ⟨⟨a, mem_non_zero_divisors_of_ne_zero ha⟩, hax⟩ } end } } end end torsion namespace quotient_torsion variables [comm_ring R] [add_comm_group M] [module R M] /-- Quotienting by the torsion submodule gives a torsion-free module. -/ @[simp] lemma torsion_eq_bot : torsion R (M ⧸ torsion R M) = ⊥ := eq_bot_iff.mpr $ λ z, quotient.induction_on' z $ λ x ⟨a, hax⟩, begin rw [quotient.mk'_eq_mk, ← quotient.mk_smul, quotient.mk_eq_zero] at hax, rw [mem_bot, quotient.mk'_eq_mk, quotient.mk_eq_zero], cases hax with b h, exact ⟨b * a, (mul_smul _ _ _).trans h⟩ end instance no_zero_smul_divisors [is_domain R] : no_zero_smul_divisors R (M ⧸ torsion R M) := no_zero_smul_divisors_iff_torsion_eq_bot.mpr torsion_eq_bot end quotient_torsion end submodule namespace ideal.quotient open submodule lemma torsion_by_eq_span_singleton {R : Type*} [comm_ring R] (a b : R) (ha : a ∈ R⁰) : torsion_by R (R ⧸ R ∙ a * b) a = R ∙ (mk _ b) := begin ext x, rw [mem_torsion_by_iff, mem_span_singleton], obtain ⟨x, rfl⟩ := mk_surjective x, split; intro h, { rw [← mk_eq_mk, ← quotient.mk_smul, quotient.mk_eq_zero, mem_span_singleton] at h, obtain ⟨c, h⟩ := h, rw [smul_eq_mul, smul_eq_mul, mul_comm, mul_assoc, mul_cancel_left_mem_non_zero_divisor ha, mul_comm] at h, use c, rw [← h, ← mk_eq_mk, ← quotient.mk_smul, smul_eq_mul, mk_eq_mk] }, { obtain ⟨c, h⟩ := h, rw [← h, smul_comm, ← mk_eq_mk, ← quotient.mk_smul, (quotient.mk_eq_zero _).mpr $ mem_span_singleton_self _, smul_zero] } end end ideal.quotient namespace add_monoid theorem is_torsion_iff_is_torsion_nat [add_comm_monoid M] : add_monoid.is_torsion M ↔ module.is_torsion ℕ M := begin refine ⟨λ h x, _, λ h x, _⟩, { obtain ⟨n, h0, hn⟩ := (is_of_fin_add_order_iff_nsmul_eq_zero x).mp (h x), exact ⟨⟨n, mem_non_zero_divisors_of_ne_zero $ ne_of_gt h0⟩, hn⟩ }, { rw is_of_fin_add_order_iff_nsmul_eq_zero, obtain ⟨n, hn⟩ := @h x, refine ⟨n, nat.pos_of_ne_zero (non_zero_divisors.coe_ne_zero _), hn⟩ } end theorem is_torsion_iff_is_torsion_int [add_comm_group M] : add_monoid.is_torsion M ↔ module.is_torsion ℤ M := begin refine ⟨λ h x, _, λ h x, _⟩, { obtain ⟨n, h0, hn⟩ := (is_of_fin_add_order_iff_nsmul_eq_zero x).mp (h x), exact ⟨⟨n, mem_non_zero_divisors_of_ne_zero $ ne_of_gt $ int.coe_nat_pos.mpr h0⟩, (coe_nat_zsmul _ _).trans hn⟩ }, { rw is_of_fin_add_order_iff_nsmul_eq_zero, obtain ⟨n, hn⟩ := @h x, exact exists_nsmul_eq_zero_of_zsmul_eq_zero (non_zero_divisors.coe_ne_zero n) hn } end end add_monoid
86de0a0409b4d7673a564144d1829d2d1ff40b54
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/discrTreeIota.lean
ad09962355e2166fb5e67a2983a6e729e41ec060
[ "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
599
lean
@[simp] theorem liftOn_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : Quot.liftOn (Quot.mk r a) f h = f a := rfl theorem eq_iff_true_of_subsingleton [Subsingleton α] (x y : α) : x = y ↔ True := iff_true _ ▸ Subsingleton.elim .. section attribute [simp] eq_iff_true_of_subsingleton end @[simp] theorem PUnit.default_eq_unit : (default : PUnit) = PUnit.unit := rfl set_option trace.Meta.Tactic.simp.discharge true set_option trace.Meta.Tactic.simp.unify true set_option trace.Meta.Tactic.simp.rewrite true example : (default : PUnit) = x := by simp
268e4854c4aae8fadada9a2f319be287761c3151
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Data/Lsp/InitShutdown.lean
260d592346a7c8b1631f320b1e1b23b7d82e77de
[ "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
3,221
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Lsp.Capabilities import Lean.Data.Lsp.Workspace import Lean.Data.Json /-! Functionality to do with initializing and shutting down the server ("General Messages" section of LSP spec). -/ namespace Lean namespace Lsp open Json structure ClientInfo where name : String version? : Option String := none deriving ToJson, FromJson inductive Trace where | off | messages | verbose instance : FromJson Trace := ⟨fun j => match j.getStr? with | some "off" => Trace.off | some "messages" => Trace.messages | some "verbose" => Trace.verbose | _ => none⟩ instance Trace.hasToJson : ToJson Trace := ⟨fun | Trace.off => "off" | Trace.messages => "messages" | Trace.verbose => "verbose"⟩ /-- Lean-specific initialization options. -/ structure InitializationOptions where /-- Time (in milliseconds) which must pass since latest edit until elaboration begins. Lower values may make editors feel faster at the cost of higher CPU usage. Defaults to 200ms. -/ editDelay? : Option Nat deriving ToJson, FromJson structure InitializeParams where processId? : Option Int := none clientInfo? : Option ClientInfo := none /- We don't support the deprecated rootPath (rootPath? : Option String) -/ rootUri? : Option String := none initializationOptions? : Option InitializationOptions := none capabilities : ClientCapabilities /- If omitted, we default to off. -/ trace : Trace := Trace.off workspaceFolders? : Option (Array WorkspaceFolder) := none deriving ToJson instance : FromJson InitializeParams where fromJson? j := OptionM.run do /- Many of these params can be null instead of not present. For ease of implementation, we're liberal: missing params, wrong json types and null all map to none, even if LSP sometimes only allows some subset of these. In cases where LSP makes a meaningful distinction between different kinds of missing values, we'll follow accordingly. -/ let processId? := j.getObjValAs? Int "processId" let clientInfo? := j.getObjValAs? ClientInfo "clientInfo" let rootUri? := j.getObjValAs? String "rootUri" let initializationOptions? := j.getObjValAs? InitializationOptions "initializationOptions" let capabilities ← j.getObjValAs? ClientCapabilities "capabilities" let trace := (j.getObjValAs? Trace "trace").getD Trace.off let workspaceFolders? := j.getObjValAs? (Array WorkspaceFolder) "workspaceFolders" return ⟨processId?, clientInfo?, rootUri?, initializationOptions?, capabilities, trace, workspaceFolders?⟩ inductive InitializedParams where | mk instance : FromJson InitializedParams := ⟨fun _ => InitializedParams.mk⟩ instance : ToJson InitializedParams := ⟨fun _ => Json.null⟩ structure ServerInfo where name : String version? : Option String := none deriving ToJson, FromJson structure InitializeResult where capabilities : ServerCapabilities serverInfo? : Option ServerInfo := none deriving ToJson, FromJson end Lsp end Lean
860fc0129a1b91a022cc2da133f477b62a1c8c54
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/basic.lean
243f4ca3953a486927a28a75942fa6be0821c654
[ "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
25,971
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.smul_with_zero import group_theory.group_action.group import tactic.abel /-! # Modules over a ring > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define * `module R M` : an additive commutative monoid `M` is a `module` over a `semiring R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. ## Implementation notes In typical mathematical usage, our definition of `module` corresponds to "semimodule", and the word "module" is reserved for `module R M` where `R` is a `ring` and `M` an `add_comm_group`. If `R` is a `field` and `M` an `add_comm_group`, `M` would be called an `R`-vector space. Since those assumptions can be made by changing the typeclasses applied to `R` and `M`, without changing the axioms in `module`, mathlib calls everything a `module`. In older versions of mathlib, we had separate `semimodule` and `vector_space` abbreviations. This caused inference issues in some cases, while not providing any real advantages, so we decided to use a canonical `module` typeclass throughout. ## Tags semimodule, module, vector space -/ open function universes u v variables {α R k S M M₂ M₃ ι : Type*} /-- A module is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[ext, protect_proj] class module (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] (r s : R) (x y : M) /-- A module over a semiring automatically inherits a `mul_action_with_zero` structure. -/ @[priority 100] -- see Note [lower instance priority] instance module.to_mul_action_with_zero : mul_action_with_zero R M := { smul_zero := smul_zero, zero_smul := module.zero_smul, ..(infer_instance : mul_action R M) } instance add_comm_monoid.nat_module : module ℕ M := { one_smul := one_nsmul, mul_smul := λ m n a, mul_nsmul a m n, smul_add := λ n a b, nsmul_add a b n, smul_zero := nsmul_zero, zero_smul := zero_nsmul, add_smul := λ r s x, add_nsmul x r s } lemma add_monoid.End.nat_cast_def (n : ℕ) : (↑n : add_monoid.End M) = distrib_mul_action.to_add_monoid_End ℕ M n := rfl theorem add_smul : (r + s) • x = r • x + s • x := module.add_smul r s x lemma convex.combo_self {a b : R} (h : a + b = 1) (x : M) : a • x + b • x = x := by rw [←add_smul, h, one_smul] variables (R) theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x @[simp] lemma inv_of_two_smul_add_inv_of_two_smul [invertible (2 : R)] (x : M) : (⅟2 : R) • x + (⅟2 : R) • x = x := convex.combo_self inv_of_two_add_inv_of_two _ /-- Pullback a `module` structure along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.module [add_comm_monoid M₂] [has_smul R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `module` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.module [add_comm_monoid M₂] [has_smul R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_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.distrib_mul_action_left`. -/ @[reducible] def function.surjective.module_left {R S M : Type*} [semiring R] [add_comm_monoid M] [module R M] [semiring S] [has_smul S M] (f : R →+* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : module S M := { smul := (•), zero_smul := λ x, by rw [← f.map_zero, hsmul, zero_smul], add_smul := hf.forall₂.mpr (λ a b x, by simp only [← f.map_add, hsmul, add_smul]), .. hf.distrib_mul_action_left f.to_monoid_hom hsmul } variables {R} (M) /-- Compose a `module` with a `ring_hom`, with action `f s • m`. See note [reducible non-instances]. -/ @[reducible] def module.comp_hom [semiring S] (f : S →+* R) : module S M := { smul := has_smul.comp.smul f, add_smul := λ r s x, by simp [add_smul], .. mul_action_with_zero.comp_hom M f.to_monoid_with_zero_hom, .. distrib_mul_action.comp_hom M (f : S →* R) } variables (R) (M) /-- `(•)` as an `add_monoid_hom`. This is a stronger version of `distrib_mul_action.to_add_monoid_End` -/ @[simps apply_apply] def module.to_add_monoid_End : R →+* add_monoid.End M := { map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul], ..distrib_mul_action.to_add_monoid_End R M } /-- A convenience alias for `module.to_add_monoid_End` as an `add_monoid_hom`, usually to allow the use of `add_monoid_hom.flip`. -/ def smul_add_hom : R →+ M →+ M := (module.to_add_monoid_End R M).to_add_monoid_hom variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma module.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] @[simp] lemma smul_add_one_sub_smul {R : Type*} [ring R] [module R M] {r : R} {m : M} : r • m + (1 - r) • m = m := by rw [← add_smul, add_sub_cancel'_right, one_smul] end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `module` over a `ring` carries a natural `add_comm_group` structure. See note [reducible non-instances]. -/ @[reducible] def module.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [module R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, show (-1 : R) • a + a = 0, by { nth_rewrite 1 ← one_smul _ a, rw [← add_smul, add_left_neg, zero_smul] }, ..(infer_instance : add_comm_monoid M), } variables {R} section add_comm_group variables (R M) [semiring R] [add_comm_group M] instance add_comm_group.int_module : module ℤ M := { one_smul := one_zsmul, mul_smul := λ m n a, mul_zsmul a m n, smul_add := λ n a b, zsmul_add a b n, smul_zero := zsmul_zero, zero_smul := zero_zsmul, add_smul := λ r s x, add_zsmul x r s } lemma add_monoid.End.int_cast_def (z : ℤ) : (↑z : add_monoid.End M) = distrib_mul_action.to_add_monoid_End ℤ M z := rfl /-- A structure containing most informations as in a module, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a module structure by checking less properties, in `module.of_core`. -/ @[nolint has_nonempty_instance] structure module.core extends has_smul R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `module.core`, when the underlying space is an `add_comm_group`. -/ def module.of_core (H : module.core R M) : module R M := by letI := H.to_has_smul; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } lemma convex.combo_eq_smul_sub_add [module R M] {x y : M} {a b : R} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + x : by rw [smul_sub, convex.combo_self h] end add_comm_group /-- A variant of `module.ext` that's convenient for term-mode. -/ -- We'll later use this to show `module ℕ M` and `module ℤ M` are subsingletons. lemma module.ext' {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin ext, exact w _ _ end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero_left $ by rw [← add_smul, add_left_neg, zero_smul] @[simp] lemma neg_smul_neg : -r • -x = r • x := by rw [neg_smul, smul_neg, neg_neg] @[simp] theorem units.neg_smul (u : Rˣ) (x : M) : -u • x = - (u • x) := by rw [units.smul_def, units.coe_neg, neg_smul, units.smul_def] variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] end module /-- A module over a `subsingleton` semiring is a `subsingleton`. We cannot register this as an instance because Lean has no way to guess `R`. -/ protected theorem module.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : subsingleton M := mul_action_with_zero.subsingleton R M /-- A semiring is `nontrivial` provided that there exists a nontrivial module over this semiring. -/ protected theorem module.nontrivial (R M : Type*) [semiring R] [nontrivial M] [add_comm_monoid M] [module R M] : nontrivial R := mul_action_with_zero.nontrivial R M @[priority 910] -- see Note [lower instance priority] instance semiring.to_module [semiring R] : module R R := { smul_add := mul_add, add_smul := add_mul, zero_smul := zero_mul, smul_zero := mul_zero } /-- Like `semiring.to_module`, but multiplies on the right. -/ @[priority 910] -- see Note [lower instance priority] instance semiring.to_opposite_module [semiring R] : module Rᵐᵒᵖ R := { smul_add := λ r x y, add_mul _ _ _, add_smul := λ r x y, mul_add _ _ _, ..monoid_with_zero.to_opposite_mul_action_with_zero R} /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_module [semiring R] [semiring S] (f : R →+* S) : module R S := module.comp_hom S f /-- The tautological action by `R →+* R` on `R`. This generalizes `function.End.apply_mul_action`. -/ instance ring_hom.apply_distrib_mul_action [semiring R] : distrib_mul_action (R →+* R) R := { smul := ($), smul_zero := ring_hom.map_zero, smul_add := ring_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma ring_hom.smul_def [semiring R] (f : R →+* R) (a : R) : f • a = f a := rfl /-- `ring_hom.apply_distrib_mul_action` is faithful. -/ instance ring_hom.apply_has_faithful_smul [semiring R] : has_faithful_smul (R →+* R) R := ⟨ring_hom.ext⟩ section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] section variables (R) /-- `nsmul` is equal to any other module structure via a cast. -/ lemma nsmul_eq_smul_cast (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { rw [nat.succ_eq_add_one, nat.cast_succ, add_smul, add_smul, one_smul, ih, one_smul], } end end /-- Convert back any exotic `ℕ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_monoid`s should normally have exactly one `ℕ`-module structure by design. -/ lemma nat_smul_eq_nsmul (h : module ℕ M) (n : ℕ) (x : M) : @has_smul.smul ℕ M h.to_has_smul n x = n • x := by rw [nsmul_eq_smul_cast ℕ n x, nat.cast_id] /-- All `ℕ`-module structures are equal. Not an instance since in mathlib all `add_comm_monoid` should normally have exactly one `ℕ`-module structure by design. -/ def add_comm_monoid.nat_module.unique : unique (module ℕ M) := { default := by apply_instance, uniq := λ P, module.ext' P _ $ λ n, nat_smul_eq_nsmul P n } instance add_comm_monoid.nat_is_scalar_tower : is_scalar_tower ℕ R M := { smul_assoc := λ n x y, nat.rec_on n (by simp only [zero_smul]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ih]) } end add_comm_monoid section add_comm_group variables [semiring S] [ring R] [add_comm_group M] [module S M] [module R M] section variables (R) /-- `zsmul` is equal to any other module structure via a cast. -/ lemma zsmul_eq_smul_cast (n : ℤ) (b : M) : n • b = (n : R) • b := have (smul_add_hom ℤ M).flip b = ((smul_add_hom R M).flip b).comp (int.cast_add_hom R), by { ext, simp }, add_monoid_hom.congr_fun this n end /-- Convert back any exotic `ℤ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_group`s should normally have exactly one `ℤ`-module structure by design. -/ lemma int_smul_eq_zsmul (h : module ℤ M) (n : ℤ) (x : M) : @has_smul.smul ℤ M h.to_has_smul n x = n • x := by rw [zsmul_eq_smul_cast ℤ n x, int.cast_id] /-- All `ℤ`-module structures are equal. Not an instance since in mathlib all `add_comm_group` should normally have exactly one `ℤ`-module structure by design. -/ def add_comm_group.int_module.unique : unique (module ℤ M) := { default := by apply_instance, uniq := λ P, module.ext' P _ $ λ n, int_smul_eq_zsmul P n } end add_comm_group lemma map_int_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [ring R] [ring S] [module R M] [module S M₂] (x : ℤ) (a : M) : f ((x : R) • a) = (x : S) • f a := by simp only [←zsmul_eq_smul_cast, map_zsmul] lemma map_nat_cast_smul [add_comm_monoid M] [add_comm_monoid M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [semiring R] [semiring S] [module R M] [module S M₂] (x : ℕ) (a : M) : f ((x : R) • a) = (x : S) • f a := by simp only [←nsmul_eq_smul_cast, map_nsmul] lemma map_inv_nat_cast_smul [add_comm_monoid M] [add_comm_monoid M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [division_semiring R] [division_semiring S] [module R M] [module S M₂] (n : ℕ) (x : M) : f ((n⁻¹ : R) • x) = (n⁻¹ : S) • f x := begin by_cases hR : (n : R) = 0; by_cases hS : (n : S) = 0, { simp [hR, hS] }, { suffices : ∀ y, f y = 0, by simp [this], clear x, intro x, rw [← inv_smul_smul₀ hS (f x), ← map_nat_cast_smul f R S], simp [hR] }, { suffices : ∀ y, f y = 0, by simp [this], clear x, intro x, rw [← smul_inv_smul₀ hR x, map_nat_cast_smul f R S, hS, zero_smul] }, { rw [← inv_smul_smul₀ hS (f _), ← map_nat_cast_smul f R S, smul_inv_smul₀ hR] } end lemma map_inv_int_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [division_ring R] [division_ring S] [module R M] [module S M₂] (z : ℤ) (x : M) : f ((z⁻¹ : R) • x) = (z⁻¹ : S) • f x := begin obtain ⟨n, rfl | rfl⟩ := z.eq_coe_or_neg, { rw [int.cast_coe_nat, int.cast_coe_nat, map_inv_nat_cast_smul _ R S] }, { simp_rw [int.cast_neg, int.cast_coe_nat, inv_neg, neg_smul, map_neg, map_inv_nat_cast_smul _ R S] }, end lemma map_rat_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [division_ring R] [division_ring S] [module R M] [module S M₂] (c : ℚ) (x : M) : f ((c : R) • x) = (c : S) • f x := by rw [rat.cast_def, rat.cast_def, div_eq_mul_inv, div_eq_mul_inv, mul_smul, mul_smul, map_int_cast_smul f R S, map_inv_nat_cast_smul f R S] lemma map_rat_smul [add_comm_group M] [add_comm_group M₂] [module ℚ M] [module ℚ M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (c : ℚ) (x : M) : f (c • x) = c • f x := rat.cast_id c ▸ map_rat_cast_smul f ℚ ℚ c x /-- There can be at most one `module ℚ E` structure on an additive commutative group. -/ instance subsingleton_rat_module (E : Type*) [add_comm_group E] : subsingleton (module ℚ E) := ⟨λ P Q, module.ext' P Q $ λ r x, @map_rat_smul _ _ _ _ P Q _ _ (add_monoid_hom.id E) r x⟩ /-- If `E` is a vector space over two division semirings `R` and `S`, then scalar multiplications agree on inverses of natural numbers in `R` and `S`. -/ lemma inv_nat_cast_smul_eq {E : Type*} (R S : Type*) [add_comm_monoid E] [division_semiring R] [division_semiring S] [module R E] [module S E] (n : ℕ) (x : E) : (n⁻¹ : R) • x = (n⁻¹ : S) • x := map_inv_nat_cast_smul (add_monoid_hom.id E) R S n x /-- If `E` is a vector space over two division rings `R` and `S`, then scalar multiplications agree on inverses of integer numbers in `R` and `S`. -/ lemma inv_int_cast_smul_eq {E : Type*} (R S : Type*) [add_comm_group E] [division_ring R] [division_ring S] [module R E] [module S E] (n : ℤ) (x : E) : (n⁻¹ : R) • x = (n⁻¹ : S) • x := map_inv_int_cast_smul (add_monoid_hom.id E) R S n x /-- If `E` is a vector space over a division ring `R` and has a monoid action by `α`, then that action commutes by scalar multiplication of inverses of natural numbers in `R`. -/ lemma inv_nat_cast_smul_comm {α E : Type*} (R : Type*) [add_comm_monoid E] [division_semiring R] [monoid α] [module R E] [distrib_mul_action α E] (n : ℕ) (s : α) (x : E) : (n⁻¹ : R) • s • x = s • (n⁻¹ : R) • x := (map_inv_nat_cast_smul (distrib_mul_action.to_add_monoid_hom E s) R R n x).symm /-- If `E` is a vector space over a division ring `R` and has a monoid action by `α`, then that action commutes by scalar multiplication of inverses of integers in `R` -/ lemma inv_int_cast_smul_comm {α E : Type*} (R : Type*) [add_comm_group E] [division_ring R] [monoid α] [module R E] [distrib_mul_action α E] (n : ℤ) (s : α) (x : E) : (n⁻¹ : R) • s • x = s • (n⁻¹ : R) • x := (map_inv_int_cast_smul (distrib_mul_action.to_add_monoid_hom E s) R R n x).symm /-- If `E` is a vector space over two division rings `R` and `S`, then scalar multiplications agree on rational numbers in `R` and `S`. -/ lemma rat_cast_smul_eq {E : Type*} (R S : Type*) [add_comm_group E] [division_ring R] [division_ring S] [module R E] [module S E] (r : ℚ) (x : E) : (r : R) • x = (r : S) • x := map_rat_cast_smul (add_monoid_hom.id E) R S r x instance add_comm_group.int_is_scalar_tower {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M]: is_scalar_tower ℤ R M := { smul_assoc := λ n x y, ((smul_add_hom R M).flip y).map_zsmul x n } instance is_scalar_tower.rat {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] [module ℚ R] [module ℚ M] : is_scalar_tower ℚ R M := { smul_assoc := λ r x y, map_rat_smul ((smul_add_hom R M).flip y) r x } instance smul_comm_class.rat {R : Type u} {M : Type v} [semiring R] [add_comm_group M] [module R M] [module ℚ M] : smul_comm_class ℚ R M := { smul_comm := λ r x y, (map_rat_smul (smul_add_hom R M x) r y).symm } instance smul_comm_class.rat' {R : Type u} {M : Type v} [semiring R] [add_comm_group M] [module R M] [module ℚ M] : smul_comm_class R ℚ M := smul_comm_class.symm _ _ _ section no_zero_smul_divisors /-! ### `no_zero_smul_divisors` This section defines the `no_zero_smul_divisors` class, and includes some tests for the vanishing of elements (especially in modules over division rings). -/ /-- `no_zero_smul_divisors R M` states that a scalar multiple is `0` only if either argument is `0`. This a version of saying that `M` is torsion free, without assuming `R` is zero-divisor free. The main application of `no_zero_smul_divisors R M`, when `M` is a module, is the result `smul_eq_zero`: a scalar multiple is `0` iff either argument is `0`. It is a generalization of the `no_zero_divisors` class to heterogeneous multiplication. -/ class no_zero_smul_divisors (R M : Type*) [has_zero R] [has_zero M] [has_smul R M] : Prop := (eq_zero_or_eq_zero_of_smul_eq_zero : ∀ {c : R} {x : M}, c • x = 0 → c = 0 ∨ x = 0) export no_zero_smul_divisors (eq_zero_or_eq_zero_of_smul_eq_zero) /-- Pullback a `no_zero_smul_divisors` instance along an injective function. -/ lemma function.injective.no_zero_smul_divisors {R M N : Type*} [has_zero R] [has_zero M] [has_zero N] [has_smul R M] [has_smul R N] [no_zero_smul_divisors R N] (f : M → N) (hf : function.injective f) (h0 : f 0 = 0) (hs : ∀ (c : R) (x : M), f (c • x) = c • f x) : no_zero_smul_divisors R M := ⟨λ c m h, or.imp_right (@hf _ _) $ h0.symm ▸ eq_zero_or_eq_zero_of_smul_eq_zero (by rw [←hs, h, h0])⟩ @[priority 100] -- See note [lower instance priority] instance no_zero_divisors.to_no_zero_smul_divisors [has_zero R] [has_mul R] [no_zero_divisors R] : no_zero_smul_divisors R R := ⟨λ c x, eq_zero_or_eq_zero_of_mul_eq_zero⟩ lemma smul_ne_zero [has_zero R] [has_zero M] [has_smul R M] [no_zero_smul_divisors R M] {c : R} {x : M} (hc : c ≠ 0) (hx : x ≠ 0) : c • x ≠ 0 := λ h, (eq_zero_or_eq_zero_of_smul_eq_zero h).elim hc hx section smul_with_zero variables [has_zero R] [has_zero M] [smul_with_zero R M] [no_zero_smul_divisors R M] {c : R} {x : M} @[simp] lemma smul_eq_zero : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨eq_zero_or_eq_zero_of_smul_eq_zero, λ h, h.elim (λ h, h.symm ▸ zero_smul R x) (λ h, h.symm ▸ smul_zero c)⟩ lemma smul_ne_zero_iff : c • x ≠ 0 ↔ c ≠ 0 ∧ x ≠ 0 := by rw [ne.def, smul_eq_zero, not_or_distrib] end smul_with_zero section module variables [semiring R] [add_comm_monoid M] [module R M] section nat variables (R) (M) [no_zero_smul_divisors R M] [char_zero R] include R lemma nat.no_zero_smul_divisors : no_zero_smul_divisors ℕ M := ⟨by { intros c x, rw [nsmul_eq_smul_cast R, smul_eq_zero], simp }⟩ @[simp] lemma two_nsmul_eq_zero {v : M} : 2 • v = 0 ↔ v = 0 := by { haveI := nat.no_zero_smul_divisors R M, simp [smul_eq_zero] } end nat variables (R M) /-- If `M` is an `R`-module with one and `M` has characteristic zero, then `R` has characteristic zero as well. Usually `M` is an `R`-algebra. -/ lemma char_zero.of_module (M) [add_comm_monoid_with_one M] [char_zero M] [module R M] : char_zero R := begin refine ⟨λ m n h, @nat.cast_injective M _ _ _ _ _⟩, rw [← nsmul_one, ← nsmul_one, nsmul_eq_smul_cast R m (1 : M), nsmul_eq_smul_cast R n (1 : M), h] end end module section add_comm_group -- `R` can still be a semiring here variables [semiring R] [add_comm_group M] [module R M] section smul_injective variables (M) lemma smul_right_injective [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) : function.injective ((•) c : M → M) := (injective_iff_map_eq_zero (smul_add_hom R M c)).2 $ λ a ha, (smul_eq_zero.mp ha).resolve_left hc variables {M} lemma smul_right_inj [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) {x y : M} : c • x = c • y ↔ x = y := (smul_right_injective M hc).eq_iff end smul_injective section nat variables (R M) [no_zero_smul_divisors R M] [char_zero R] include R lemma self_eq_neg {v : M} : v = - v ↔ v = 0 := by rw [← two_nsmul_eq_zero R M, two_smul, add_eq_zero_iff_eq_neg] lemma neg_eq_self {v : M} : - v = v ↔ v = 0 := by rw [eq_comm, self_eq_neg R M] lemma self_ne_neg {v : M} : v ≠ -v ↔ v ≠ 0 := (self_eq_neg R M).not lemma neg_ne_self {v : M} : -v ≠ v ↔ v ≠ 0 := (neg_eq_self R M).not end nat end add_comm_group section module variables [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] section smul_injective variables (R) lemma smul_left_injective {x : M} (hx : x ≠ 0) : function.injective (λ (c : R), c • x) := λ c d h, sub_eq_zero.mp ((smul_eq_zero.mp (calc (c - d) • x = c • x - d • x : sub_smul c d x ... = 0 : sub_eq_zero.mpr h)).resolve_right hx) end smul_injective end module section group_with_zero variables [group_with_zero R] [add_monoid M] [distrib_mul_action R M] /-- This instance applies to `division_semiring`s, in particular `nnreal` and `nnrat`. -/ @[priority 100] -- see note [lower instance priority] instance group_with_zero.to_no_zero_smul_divisors : no_zero_smul_divisors R M := ⟨λ c x h, or_iff_not_imp_left.2 $ λ hc, (smul_eq_zero_iff_eq' hc).1 h⟩ end group_with_zero @[priority 100] -- see note [lower instance priority] instance rat_module.no_zero_smul_divisors [add_comm_group M] [module ℚ M] : no_zero_smul_divisors ℤ M := ⟨λ k x h, by simpa [zsmul_eq_smul_cast ℚ k x] using h⟩ end no_zero_smul_divisors @[simp] lemma nat.smul_one_eq_coe {R : Type*} [semiring R] (m : ℕ) : m • (1 : R) = ↑m := by rw [nsmul_eq_mul, mul_one] @[simp] lemma int.smul_one_eq_coe {R : Type*} [ring R] (m : ℤ) : m • (1 : R) = ↑m := by rw [zsmul_eq_mul, mul_one] assert_not_exists multiset
7f7cd4f11f7067ab1904884ab060d338cdc3a1df
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/ring_theory/integral_closure.lean
ea52150557bdc1c1ddec58b2ccef800ee68930a2
[ "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
24,000
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.algebra_tower import ring_theory.polynomial.scale_roots /-! # Integral closure of a subring. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `ring_hom.is_integral_elem (f : R →+* A) (x : A)` : `x` is integral with respect to the map `f`, * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ open_locale classical open_locale big_operators open polynomial submodule section ring variables {R A : Type*} variables [comm_ring R] [ring A] /-- An element `x` of `A` is said to be integral over `R` with respect to `f` if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/ def ring_hom.is_integral_elem (f : R →+* A) (x : A) := ∃ p : polynomial R, monic p ∧ eval₂ f x p = 0 /-- A ring homomorphism `f : R →+* A` is said to be integral if every element `A` is integral with respect to the map `f` -/ def ring_hom.is_integral (f : R →+* A) := ∀ x : A, f.is_integral_elem x variables [algebra R A] (R) /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/ def is_integral (x : A) : Prop := (algebra_map R A).is_integral_elem x variable (A) /-- An algebra is integral if every element of the extension is integral over the base ring -/ def algebra.is_integral : Prop := (algebra_map R A).is_integral variables {R A} theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := ⟨X - C x, monic_X_sub_C _, by simp⟩ theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_submodule_noetherian (S : subalgebra R A) (H : is_noetherian R (S : submodule R A)) (x : A) (hx : x ∈ S) : is_integral R x := begin letI : algebra R S := S.algebra, letI : ring S := S.ring R A, suffices : is_integral R (⟨x, hx⟩ : S), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg subtype.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, finsupp.sum], rw ← p.support.sum_hom subtype.val, { refine finset.sum_congr rfl (λ n hn, _), change _ = _ * _, rw is_monoid_hom.map_pow coe, refl, split; intros; refl }, refine { map_add := _, map_zero := _ }; intros; refl }, refine is_integral_of_noetherian H ⟨x, hx⟩ end end ring section variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R A] [algebra R B] theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) := let ⟨p, hp, hpx⟩ := hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩ theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B] (x : B) (hx : is_integral R x) : is_integral A x := let ⟨p, hp, hpx⟩ := hx in ⟨p.map $ algebra_map R A, monic_map _ hp, by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩ section local attribute [instance] subset.comm_ring algebra.of_is_subring theorem is_integral_of_subring {x : A} (T : set R) [is_subring T] (hx : is_integral T x) : is_integral R x := is_integral_of_is_scalar_tower x hx theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) r := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, refine ⟨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, _⟩, erw [← aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A) : submodule R A).fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range at hr, rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw ← aeval_def at hfx, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, finsupp.sum], refine sum_mem _ (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s : submodule R A).fg := set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x, by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_map_top, map_top, linear_map.mem_range, algebra.mem_bot], refl }⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : (S : submodule R A).fg) (x : A) (hx : x ∈ S) : is_integral R x := begin cases HS with y hy, obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ (S : submodule R A), by { rw ← hy, exact subset_span hp }, have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ (S : submodule R A) := λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2), rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_iff_total] at this, choose ly hly1 hly2, let S₀ : set R := ring.closure ↑(lx.frange ∪ finset.bind finset.univ (finsupp.frange ∘ ly)), refine is_integral_of_subring S₀ _, letI : comm_ring S₀ := @subtype.comm_ring _ _ _ ring.closure.is_subring, letI : algebra S₀ A := algebra.of_is_subring _, have : span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A), { rw span_mul_span, refine span_le.2 (λ z hz, _), rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩, { rw one_mul, exact subset_span hq }, rcases hq with rfl | hq, { rw mul_one, exact subset_span (or.inr hp) }, erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, rw [finsupp.total_apply, finsupp.sum], refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _), have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ := ring.subset_closure (finset.mem_union_right _ $ finset.mem_bind.2 ⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _, finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩), change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) }, haveI : is_subring (span S₀ (insert 1 ↑y : set A) : set A) := { one_mem := subset_span $ or.inl rfl, mul_mem := λ p q hp hq, this $ mul_mem_mul hp hq, zero_mem := (span S₀ (insert 1 ↑y : set A)).zero_mem, add_mem := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem, neg_mem := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem }, have : span S₀ (insert 1 ↑y : set A) = algebra.adjoin S₀ (↑y : set A), { refine le_antisymm (span_le.2 $ set.insert_subset.2 ⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩) (λ z hz, _), rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw ← submodule.mem_coe, refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ λ t, _) (λ t ht, subset_span $ or.inr ht)) hz, rw algebra.algebra_map_eq_smul_one, exact smul_mem (span S₀ (insert 1 ↑y : set A)) _ (subset_span $ or.inl rfl) }, haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _), refine is_integral_of_submodule_noetherian (algebra.adjoin S₀ ↑y) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw [finset.coe_insert, this]⟩) _ _, rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _), have : lx r ∈ S₀ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)), change (⟨_, this⟩ : S₀) • r ∈ _, rw finsupp.mem_supported at hlx1, exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _ end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure ({x, y} : set A)) : is_integral R z := begin have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz) end theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).map_zero ▸ is_integral_algebra_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).map_one ▸ is_integral_algebra_map theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem (ring.subset_closure (or.inl rfl))) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := is_integral_add hx (is_integral_neg hy) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := is_integral_of_mem_closure hx hy (is_submonoid.mul_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) variables (R A) /-- The integral closure of R in an R-algebra A. -/ def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, zero_mem' := is_integral_zero, one_mem' := is_integral_one, add_mem' := λ _ _, is_integral_add, mul_mem' := λ _ _, is_integral_mul, algebra_map_mem' := λ x, is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, (M : submodule R A).fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ variables {R} {A} /-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/ lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) : (integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B := begin ext y, rw subalgebra.mem_map, split, { rintros ⟨x, hx, rfl⟩, exact is_integral_alg_hom f hx }, { intro hy, use [f.symm y, is_integral_alg_hom (f.symm : B →ₐ[R] A) hy], simp } end lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x := let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $ by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩ theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1) (hx : is_integral R (x * y)) : is_integral R x := begin obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx, refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩, convert scale_roots_aeval_eq_zero hp, rw [mul_comm x y, ← mul_assoc, hr, one_mul], end theorem is_integral_of_is_integral_mul_unit' {R S : Type*} [comm_ring R] [comm_ring S] {f : R →+* S} (x y : S) (r : R) (hr : f r * y = 1) (hx : f.is_integral_elem (x * y)) : f.is_integral_elem x := @is_integral_of_is_integral_mul_unit R S _ _ f.to_algebra x y r hr hx /-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/ lemma is_integral_of_mem_closure' (G : set A) (hG : ∀ x ∈ G, is_integral R x) : ∀ x ∈ (subring.closure G), is_integral R x := λ x hx, subring.closure_induction hx hG is_integral_zero is_integral_one (λ _ _, is_integral_add) (λ _, is_integral_neg) (λ _ _, is_integral_mul) lemma is_integral_of_mem_closure'' {S : Type*} [comm_ring S] {f : R →+* S} (G : set S) (hG : ∀ x ∈ G, f.is_integral_elem x) : ∀ x ∈ (subring.closure G), f.is_integral_elem x := λ x hx, @is_integral_of_mem_closure' R S _ _ f.to_algebra G hG x hx end section algebra open algebra variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra A B] [algebra R B] lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) : is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x := begin generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S, have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S, { intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0, { rw hi, exact subalgebra.zero_mem _ }, rw ← hS, exact subset_adjoin (finsupp.mem_frange.2 ⟨hi, i, rfl⟩) }, obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) = (p.map $ algebra_map A B), { rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) B)).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval x) hq, convert hq using 1; symmetry; apply eval_map }, end variables [algebra R A] [is_scalar_tower R A B] /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) : is_integral R x := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set B := ↑(p.map $ algebra_map A B).frange, refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl), refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _, { rw [finset.mem_coe, finsupp.mem_frange] at hx, rcases hx with ⟨_, i, rfl⟩, show is_integral R ((p.map $ algebra_map A B).coeff i), rw coeff_map, convert is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B := λ x, is_integral_trans hA x (hB x) lemma ring_hom.is_integral_trans {R A B : Type*} [comm_ring R] [comm_ring A] [comm_ring B] {f : R →+* A} {g : A →+* B} (hf : f.is_integral) (hg : g.is_integral) : (g.comp f).is_integral := @algebra.is_integral_trans R A B _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R A B _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hf hg lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A := λ x, (h x).rec_on (λ y hy, (hy ▸ is_integral_algebra_map : is_integral R x)) lemma is_integral_of_surjective' {R A : Type*} [comm_ring R] [comm_ring A] {f : R →+* A} (hf : function.surjective f) : f.is_integral := @is_integral_of_surjective R A _ _ f.to_algebra hf /-- If `R → A → B` is an algebra tower with `A → B` injective, then if the entire tower is an integral extension so is `R → A` -/ lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B)) {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p, ⟨hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map, eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp', rw [eval₂_eq_eval_map], exact H hp', end lemma is_integral_tower_bot_of_is_integral' {R A B : Type*} [comm_ring R] [comm_ring A] [comm_ring B] (f : R →+* A) (g : A →+* B) (hg : function.injective g) (hfg : (g.comp f).is_integral) : f.is_integral := λ x, @is_integral_tower_bot_of_is_integral R A B _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R A B _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hg x (hfg (g x)) lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A] [comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := is_integral_tower_bot_of_is_integral (algebra_map A B).injective h /-- If `R → A → B` is an algebra tower, then if the entire tower is an integral extension so is `A → B` -/ lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp', exact hp', end lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) : is_integral (I.comap (algebra_map R A)).quotient I.quotient := begin rintros ⟨x⟩, obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hRA x, refine ⟨p.map (ideal.quotient.mk _), ⟨monic_map _ p_monic, _⟩⟩, simpa only [aeval_def, hom_eval₂, eval₂_map] using congr_arg (ideal.quotient.mk I) hpx end lemma is_integral_quotient_of_is_integral' {R S : Type*} [comm_ring R] [comm_ring S] {f : R →+* S} {I : ideal S} (hf : f.is_integral) : (ideal.quotient_map I f le_rfl).is_integral := @is_integral_quotient_of_is_integral R S _ _ f.to_algebra I hf /-- If the integral extension `R → S` is injective, and `S` is a field, then `R` is also a field -/ lemma is_field_of_is_integral_of_is_field {R S : Type*} [integral_domain R] [integral_domain S] [algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S)) (hS : is_field S) : is_field R := begin refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ a ha, _⟩, -- Let `a_inv` be the inverse of `algebra_map R S a`, -- then we need to show that `a_inv` is of the form `algebra_map R S b`. obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (λ h, ha (hRS (trans h (ring_hom.map_zero _).symm))), -- Let `p : polynomial R` be monic with root `a_inv`, -- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`). -- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`. obtain ⟨p, p_monic, hp⟩ := H a_inv, use -∑ (i : ℕ) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1), -- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`. -- TODO: this could be a lemma for `polynomial.reverse`. have hq : ∑ (i : ℕ) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0, { apply (algebra_map R S).injective_iff.mp hRS, have a_inv_ne_zero : a_inv ≠ 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero), refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero), rw [eval₂_eq_sum_range] at hp, rw [ring_hom.map_sum, finset.sum_mul], refine (finset.sum_congr rfl (λ i hi, _)).trans hp, rw [ring_hom.map_mul, mul_assoc], congr, have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i, { rw [← pow_add a_inv, nat.sub_add_cancel (nat.le_of_lt_succ (finset.mem_range.mp hi))] }, rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] }, -- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`. -- TODO: we could use a lemma for `polynomial.div_X` here. rw [finset.sum_range_succ, p_monic.coeff_nat_degree, one_mul, nat.sub_self, pow_zero, add_eq_zero_iff_eq_neg, eq_comm] at hq, rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul], convert hq using 2, refine finset.sum_congr rfl (λ i hi, _), have : 1 ≤ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi), rw [mul_assoc, ← pow_succ', nat.sub_add_cancel this] end end algebra section local attribute [instance] subset.comm_ring algebra.of_is_subring theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (integral_closure R A : set A) A = ⊥ := eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2 ⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra _ integral_closure.is_integral x hx⟩, rfl⟩ end section integral_domain variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S] instance : integral_domain (integral_closure R S) := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.mp zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨a, ha⟩ ⟨b, hb⟩ h, or.imp subtype.ext_iff_val.mpr subtype.ext_iff_val.mpr (eq_zero_or_eq_zero_of_mul_eq_zero (subtype.ext_iff_val.mp h)), ..(integral_closure R S).comm_ring R S } end integral_domain
6a3e11a887a5e6e1ad012c68e57d7aff5b12eeff
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/types/pi.hlean
32dec003eccd93f7518c9e7bf8b8e8eea6548d41
[ "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
13,921
hlean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import types.sigma arity cubical.square open eq equiv is_equiv funext sigma unit bool is_trunc prod function sigma.ops namespace pi variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths are charactirized in [init/funext] -/ /- homotopy.symm is an equivalence -/ definition homotopy.symm_symm {A : Type} {P : A → Type} {f g : Πx, P x} (H : f ~ g) : H⁻¹ʰᵗʸ⁻¹ʰᵗʸ = H := begin apply eq_of_homotopy, intro x, apply inv_inv end definition is_equiv_homotopy_symm : is_equiv (homotopy.symm : f ~ g → g ~ f) := adjointify homotopy.symm homotopy.symm homotopy.symm_symm homotopy.symm_symm /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition eq_equiv_homotopy (f g : Πx, B x) : (f = g) ≃ (f ~ g) := equiv.mk apd10 _ definition pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := !eq_equiv_homotopy definition is_equiv_eq_of_homotopy (f g : Πx, B x) : is_equiv (eq_of_homotopy : f ~ g → f = g) := _ definition homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk eq_of_homotopy _ /- Transport -/ definition pi_transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, !tr_inv_tr ▸ (p ▸D (f (p⁻¹ ▸ b)))) := by induction p; reflexivity /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition pi_transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) (b : A') : (transport _ p f) b = p ▸ (f b) := by induction p; reflexivity /- Pathovers -/ definition pi_pathover' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apd011 C p q] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_left' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a), f b =[apd011 C p !pathover_tr] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_right' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apd011 C p !tr_pathover] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_constant {C : A → A' → Type} {f : Π(b : A'), C a b} {g : Π(b : A'), C a' b} {p : a = a'} (r : Π(b : A'), f b =[p] g b) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, exact eq_of_pathover_idp (r b), end -- a version where C is uncurried, but where the conclusion of r is still a proper pathover -- instead of a heterogenous equality definition pi_pathover {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)), end definition pi_pathover_left {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a), f b =[dpair_eq_dpair p !pathover_tr] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b) end definition pi_pathover_right {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[dpair_eq_dpair p !tr_pathover] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b) end /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply eq_of_homotopy_idp end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃ (transport (λa, Π(b : B a), C a b) p f = g) -/ definition heq_piD (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, !homotopy_equiv_eq) g definition heq_pi {C : A → Type} (p : a = a') (f : Π(b : B a), C a) (g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, !homotopy_equiv_eq) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/ definition heq_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), p ▸D (f b) = g (p ▸ b)) := eq.rec_on p (λg, !equiv.rfl) g end /- Functorial action -/ variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') /- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/ definition pi_functor [unfold_full] : (Π(a:A), B a) → (Π(a':A'), B' a') := λg a', f1 a' (g (f0 a')) definition pi_functor_left [unfold_full] (B : A → Type) : (Π(a:A), B a) → (Π(a':A'), B (f0 a')) := pi_functor f0 (λa, id) definition pi_functor_right [unfold_full] {B' : A → Type} (f1 : Π(a:A), B a → B' a) : (Π(a:A), B a) → (Π(a:A), B' a) := pi_functor id f1 definition ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g') : ap (pi_functor f0 f1) (eq_of_homotopy h) = eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a')))) := begin apply (is_equiv_rect (@apd10 A B g g')), intro p, clear h, cases p, apply concat, exact (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)), apply symm, apply eq_of_homotopy_idp end /- Equivalences -/ definition is_equiv_pi_functor [instance] [constructor] [H0 : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) := begin apply (adjointify (pi_functor f0 f1) (pi_functor f0⁻¹ (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), begin intro h, apply eq_of_homotopy, intro a', esimp, rewrite [adj f0 a',-tr_compose,fn_tr_eq_tr_fn _ f1,right_inv (f1 _)], apply apdt end, begin intro h, apply eq_of_homotopy, intro a, esimp, rewrite [left_inv (f1 _)], apply apdt end end definition pi_equiv_pi_of_is_equiv [constructor] [H : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') := equiv.mk (pi_functor f0 f1) _ definition pi_equiv_pi [constructor] (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a')) : (Πa, B a) ≃ (Πa', B' a') := pi_equiv_pi_of_is_equiv (to_fun f0) (λa', to_fun (f1 a')) definition pi_equiv_pi_right [constructor] {P Q : A → Type} (g : Πa, P a ≃ Q a) : (Πa, P a) ≃ (Πa, Q a) := pi_equiv_pi equiv.rfl g /- Equivalence if one of the types is contractible -/ definition pi_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A] : (Πa, B a) ≃ B (center A) := begin fapply equiv.MK, { intro f, exact f (center A)}, { intro b a, exact center_eq a ▸ b}, { intro b, rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]}, { intro f, apply eq_of_homotopy, intro a, induction (center_eq a), rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]} end definition pi_equiv_of_is_contr_right [constructor] [H : Πa, is_contr (B a)] : (Πa, B a) ≃ unit := begin fapply equiv.MK, { intro f, exact star}, { intro u a, exact !center}, { intro u, induction u, reflexivity}, { intro f, apply eq_of_homotopy, intro a, apply is_prop.elim} end /- Interaction with other type constructors -/ -- most of these are in the file of the other type constructor definition pi_empty_left [constructor] (B : empty → Type) : (Πx, B x) ≃ unit := begin fapply equiv.MK, { intro f, exact star}, { intro x y, contradiction}, { intro x, induction x, reflexivity}, { intro f, apply eq_of_homotopy, intro y, contradiction}, end definition pi_unit_left [constructor] (B : unit → Type) : (Πx, B x) ≃ B star := !pi_equiv_of_is_contr_left definition pi_bool_left [constructor] (B : bool → Type) : (Πx, B x) ≃ B ff × B tt := begin fapply equiv.MK, { intro f, exact (f ff, f tt)}, { intro x b, induction x, induction b: assumption}, { intro x, induction x, reflexivity}, { intro f, apply eq_of_homotopy, intro b, induction b: reflexivity}, end definition pi_bool_left_natural {A B : bool → Type} (g : Πx, A x → B x) : hsquare (pi_bool_left A) (pi_bool_left B) (pi_functor_right g) (prod_functor (g ff) (g tt)) := begin intro h, esimp end definition pi_bool_left_inv_natural {A B : bool → Type} (g : Πx, A x → B x) : hsquare (pi_bool_left A)⁻¹ᵉ (pi_bool_left B)⁻¹ᵉ (prod_functor (g ff) (g tt)) (pi_functor_right g) := (pi_bool_left_natural g)⁻¹ʰᵗʸʰ /- Truncatedness: any dependent product of n-types is an n-type -/ theorem is_trunc_pi (B : A → Type) (n : ℕ₋₂) [H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) := begin revert B H, induction n with n IH, { intros B H, apply is_contr.mk (λa, !center), intro f, apply eq_of_homotopy, intro x, apply (center_eq (f x)) }, { intros B H, fapply is_trunc_succ_intro, intro f g, fapply is_trunc_equiv_closed, apply equiv.symm, apply eq_equiv_homotopy, apply IH, intro a, show is_trunc n (f a = g a), from is_trunc_eq n (f a) (g a) } end local attribute is_trunc_pi [instance] theorem is_trunc_pi_eq (n : ℕ₋₂) (f g : Πa, B a) [H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) := is_trunc_equiv_closed_rev n !eq_equiv_homotopy _ theorem is_trunc_not [instance] (n : ℕ₋₂) (A : Type) : is_trunc (n.+1) ¬A := by unfold not;exact _ theorem is_prop_pi_eq [instance] [priority 490] (a : A) : is_prop (Π(a' : A), a = a') := is_prop_of_imp_is_contr ( assume (f : Πa', a = a'), have is_contr A, from is_contr.mk a f, by exact _) /- force type clas resolution -/ theorem is_prop_neg (A : Type) : is_prop (¬A) := _ local attribute ne [reducible] theorem is_prop_ne [instance] {A : Type} (a b : A) : is_prop (a ≠ b) := _ definition is_contr_pi_of_neg {A : Type} (B : A → Type) (H : ¬ A) : is_contr (Πa, B a) := begin apply is_contr.mk (λa, empty.elim (H a)), intro f, apply eq_of_homotopy, intro x, contradiction end /- Symmetry of Π -/ definition is_equiv_flip [instance] {P : A → A' → Type} : is_equiv (@function.flip A A' P) := begin fapply is_equiv.mk, exact (@function.flip _ _ (function.flip P)), repeat (intro f; apply idp) end definition pi_comm_equiv {P : A → A' → Type} : (Πa b, P a b) ≃ (Πb a, P a b) := equiv.mk (@function.flip _ _ P) _ /- Dependent functions are equivalent to nondependent functions into the total space together with a homotopy -/ definition pi_equiv_arrow_sigma_right [constructor] {A : Type} {B : A → Type} (f : Πa, B a) : Σ(f : A → Σa, B a), pr1 ∘ f ~ id := ⟨λa, ⟨a, f a⟩, λa, idp⟩ definition pi_equiv_arrow_sigma_left.{u v} [unfold 3] {A : Type.{u}} {B : A → Type.{v}} (v : Σ(f : A → Σa, B a), pr1 ∘ f ~ id) (a : A) : B a := transport B (v.2 a) (v.1 a).2 open funext definition pi_equiv_arrow_sigma [constructor] {A : Type} (B : A → Type) : (Πa, B a) ≃ Σ(f : A → Σa, B a), pr1 ∘ f ~ id := begin fapply equiv.MK, { exact pi_equiv_arrow_sigma_right}, { exact pi_equiv_arrow_sigma_left}, { intro v, induction v with f p, fapply sigma_eq: esimp, { apply eq_of_homotopy, intro a, fapply sigma_eq: esimp, { exact (p a)⁻¹}, { apply inverseo, apply pathover_tr}}, { apply pi_pathover_constant, intro a, apply eq_pathover_constant_right, refine ap_compose (λf, f a) _ _ ⬝ph _, refine ap02 _ !compose_eq_of_homotopy ⬝ph _, refine !ap_eq_apd10 ⬝ph _, refine apd10 (right_inv apd10 _) a ⬝ph _, esimp, refine !sigma_eq_pr1 ⬝ph _, apply square_of_eq, exact !con.left_inv⁻¹}}, { intro a, reflexivity} end end pi attribute pi.is_trunc_pi [instance] [priority 1520] namespace pi /- pointed pi types -/ open pointed definition pointed_pi [instance] [constructor] {A : Type} (P : A → Type) [H : Πx, pointed (P x)] : pointed (Πx, P x) := pointed.mk (λx, pt) end pi
d335ff294927714d9c5db3ff49a5aa2c2df28ab6
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/types.lean
2eb362295c3690fe496189e8b1f42a3bc91c3c95
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
6,542
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 -/ import category_theory.functor_category import category_theory.fully_faithful import data.equiv.basic namespace category_theory universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation instance types : large_category (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } @[simp] lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl @[simp] lemma types_id (X : Type u) : 𝟙 X = id := rfl @[simp] lemma types_comp {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl namespace functor variables {J : Type u} [𝒥 : category.{v} J] include 𝒥 def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [𝒞 : category.{v} C] (F G H : C ⥤ Type w) {X Y Z : C} include 𝒞 variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp @[simp] lemma map_id (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl @[simp] lemma map_inv_map_hom_apply (f : X ≅ Y) (x : F.obj X) : F.map f.inv (F.map f.hom x) = x := congr_fun (F.map_iso f).hom_inv_id x @[simp] lemma map_hom_map_inv_apply (f : X ≅ Y) (y : F.obj Y) : F.map f.hom (F.map f.inv y) = y := congr_fun (F.map_iso f).inv_hom_id y end functor_to_types def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { injectivity' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { refine λ H, ⟨λ Z g h H₂, _⟩, ext z, replace H₂ := congr_fun H₂ z, exact H H₂ } end lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { intros H, let g : Y ⟶ ulift Prop := λ y, ⟨true⟩, let h : Y ⟶ ulift Prop := λ y, ⟨∃ x, f x = y⟩, suffices : f ≫ g = f ≫ h, { resetI, rw cancel_epi at this, intro y, replace this := congr_fun this y, replace this : true = ∃ x, f x = y := congr_arg ulift.down this, rw ←this, trivial }, ext x, change true ↔ ∃ x', f x' = f x, rw true_iff, exact ⟨x, rfl⟩ }, { intro H, constructor, intros Z g h H₂, apply funext, rw ←forall_iff_forall_surj H, intro x, exact (congr_fun H₂ x : _) } end section /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] : Type u ⥤ Type v := { obj := m, map := λα β, _root_.functor.map, map_id' := assume α, _root_.functor.map_id, map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ } variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] @[simp] lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl @[simp] lemma of_type_functor_map {α β} (f : α → β) : (of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Type u} def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv namespace category_theory.iso universe u variables {X Y : Type u} def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl end category_theory.iso universe u -- We prove `equiv_iso_iso` and then use that to sneakily construct `equiv_equiv_iso`. -- (In this order the proofs are handled by `obviously`.) /-- equivalences (between types in the same universe) are the same as (isomorphic to) isomorphisms of types -/ @[simps] def equiv_iso_iso {X Y : Type u} : (X ≃ Y) ≅ (X ≅ Y) := { hom := λ e, e.to_iso, inv := λ i, i.to_equiv, } /-- equivalences (between types in the same universe) are the same as (equivalent to) isomorphisms of types -/ -- We leave `X` and `Y` as explicit arguments here, because the coercions from `equiv` to a function won't fire without them. def equiv_equiv_iso (X Y : Type u) : (X ≃ Y) ≃ (X ≅ Y) := (equiv_iso_iso).to_equiv @[simp] lemma equiv_equiv_iso_hom {X Y : Type u} (e : X ≃ Y) : (equiv_equiv_iso X Y) e = e.to_iso := rfl @[simp] lemma equiv_equiv_iso_inv {X Y : Type u} (e : X ≅ Y) : (equiv_equiv_iso X Y).symm e = e.to_equiv := rfl
94814302968c6a305a0466724ac67c6b73d8c07e
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/finsupp/basic.lean
bf5f39a80e53ad0e0ad356f9d17ba4f53b52beaf
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
82,109
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, Scott Morrison -/ import algebra.group.pi import algebra.big_operators.order import algebra.module.basic import algebra.module.pi import group_theory.submonoid.basic import data.fintype.card import data.finset.preimage import data.multiset.antidiagonal import data.indicator_function /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## TODO * This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks; * Add the list of definitions and important lemmas to the module docstring. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## Notation This file defines `α →₀ β` as notation for `finsupp α β`. -/ noncomputable theory open_locale classical big_operators open finset variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance : has_coe_to_fun (α →₀ M) := ⟨λ _, α → M, to_fun⟩ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, (λ _, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = (λ _, (0:M)) := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin change f = g at h, subst h, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[ext] lemma ext {f g : α →₀ M} (h : ∀a, f a = g a) : f = g := coe_fn_injective (funext h) lemma ext_iff {f g : α →₀ M} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext_iff.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance finsupp.decidable_eq [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_supp (f : α →₀ M) : set.finite {a | f a ≠ 0} := ⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩ lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply : single a b a' = if a = a' then b else 0 := rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] @[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := ⟨λ H, by simpa only [h, single_eq_single_iff, and_false, or_false, eq_self_iff_true, and_true] using H, λ H, by rw [H]⟩ @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single (default α) x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single (default α) (x (default α)) := ext $ unique.forall_iff.2 single_eq_same.symm lemma unique_ext [unique α] {f g : α →₀ M} (h : f (default α) = g (default α)) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f (default α) = g (default α) := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] end single /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : (α →₀ P) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∑ a in f.support, g a (f a) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_monoid variables [add_monoid M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ M) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero, λ _ _, single_add⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ a : α, set.range (single a : M → α →₀ M)) = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_monoid N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_monoid N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [monoid N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [monoid N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_monoid N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] end add_monoid end finsupp @[to_additive] lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := h.map_sum _ _ lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp section nat_sub instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩ @[simp] lemma coe_nat_sub (g₁ g₂ : α →₀ ℕ) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma nat_sub_apply (g₁ g₂ : α →₀ ℕ) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma single_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ := begin ext f, by_cases h : (a = f), { rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] }, rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h] end -- These next two lemmas are used in developing -- the partial derivative on `mv_polynomial`. lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, }, { simp [h], } end lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, }, { simp [h], } end @[simp] lemma nat_zero_sub (f : α →₀ ℕ) : 0 - f = 0 := ext $ λ x, nat.zero_sub _ end nat_sub instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := { neg := map_range (has_neg.neg) neg_zero, sub := has_sub.sub, sub_eq_add_neg := λ x y, ext (λ i, sub_eq_add_neg _ _), add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } instance [add_comm_group G] : add_comm_group (α →₀ G) := { add_comm := add_comm, ..finsupp.add_group } lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group G] {f : α →₀ G} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (apply_add_hom a₂ : (β →₀ N) →+ _).map_sum _ _ lemma support_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (((monoid_hom.id G)⁻¹).map_prod _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib @[to_additive] lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a), from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a, have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a), from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a, have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a), from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a, by simp only [*, add_apply, prod_mul_distrib] @[simp] lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (f.support.sum_hom _).symm lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (f.support.sum_hom multiset.sum).symm section map_range variables [add_comm_monoid M] [add_comm_monoid N] (f : M →+ N) /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ def map_range.add_monoid_hom : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } lemma map_range_multiset_sum (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (m.sum_hom (map_range.add_monoid_hom f)).symm lemma map_range_finset_sum (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_support {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end comap_domain /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) : f.filter p a = if p a then f a else 0 := rfl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := rfl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h] @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h] end has_zero lemma filter_pos_add_filter_neg [add_monoid M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl instance subtype_domain.is_add_monoid_hom : is_add_monoid_hom (subtype_domain p : (α →₀ M) → subtype p →₀ M) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end monoid section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr rfl $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl end group end subtype_domain /-! ### Declarations relating `finsupp` to `multiset` -/ section multiset /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `add_equiv`. -/ def to_multiset : (α →₀ ℕ) ≃+ multiset α := { to_fun := λ f, f.sum (λa n, n •ℕ {a}), inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩, left_inv := λ f, ext $ λ a, suffices (if f a = 0 then 0 else f a) = f a, by simpa [finsupp.sum, multiset.count_sum', multiset.count_cons], by split_ifs with h; [rw h, refl], right_inv := λ s, by simp [finsupp.sum], map_add' := λ f g, sum_add_index (λ a, zero_nsmul _) (λ a, add_nsmul _) } lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := to_multiset.map_add m n lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n •ℕ {a}) := rfl @[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n •ℕ {a} := by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def] lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, is_add_monoid_hom.map_nsmul (multiset.map g)], refl } end @[simp] lemma prod_to_multiset [comm_monoid M] (f : M →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end @[simp] lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn, multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero], refl, refine disjoint.mono_left support_single_subset _, rwa [finset.singleton_disjoint] } end @[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (n •ℕ {x} : multiset α).count a) : (f.support.sum_hom $ multiset.count a).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul] ... = f.sum (λx n, n * (x ::ₘ 0 : multiset α).count a) : rfl ... = f a * (a ::ₘ 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ @[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) : i ∈ f.to_multiset ↔ i ∈ f.support := by rw [← multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff] end multiset /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section variables [group G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar : has_scalar G (α →₀ M) := { smul := λ g f, f.comap_domain (λ a, g⁻¹ • a) (λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) } local attribute [instance] comap_has_scalar /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by { ext, dsimp [(•)], simp, }, mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, } local attribute [instance] comap_mul_action /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, } /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self : distrib_mul_action G (G →₀ M) := @finsupp.comap_distrib_mul_action G M G _ (mul_action.regular G) _ @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := begin ext a', dsimp [(•)], by_cases h : g • a = a', { subst h, simp [←mul_smul], }, { simp [single_eq_of_ne h], rw [single_eq_of_ne], rintro rfl, simpa [←mul_smul] using h, } end @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := rfl end section instance [semiring R] [add_comm_monoid M] [semimodule R M] : has_scalar R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : semiring R} [add_comm_monoid M] [semimodule R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl variables (α M) instance [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, zero_smul := λ x, ext $ λ _, zero_smul _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } variables {α M} {R} lemma support_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by simp only [smul_apply, mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _) section variables {p : α → Prop} @[simp] lemma filter_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_smul {x | p x} b v end lemma map_domain_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] }, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {_ : semiring R} [add_comm_monoid M] [semimodule R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 instance [semiring R] [add_comm_monoid M] [semimodule R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section variables [semiring R] [semiring S] lemma sum_mul (b : S) (s : α →₀ R) {f : α → R → S} : (s.sum f) * b = s.sum (λ a c, (f a c) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum (b : S) (s : α →₀ R) {f : α → R → S} : b * (s.sum f) = s.sum (λ a c, b * (f a c)) := by simp only [finsupp.sum, finset.mul_sum] instance unique_of_right [subsingleton R] : unique (α →₀ R) := { uniq := λ l, ext $ λ i, subsingleton.elim _ _, .. finsupp.inhabited } end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M):= begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. -/ protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := map_domain e, inv_fun := map_domain e.symm, left_inv := begin assume v, simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply], exact map_domain_id end, right_inv := begin assume v, simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply], exact map_domain_id end, map_add' := λ a b, map_domain_add, } end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] end sigma end finsupp /-! ### Declarations relating `multiset` to `finsupp` -/ namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm @[simp] lemma to_finsupp_support (s : multiset α) : s.to_finsupp.support = s.to_finset := rfl @[simp] lemma to_finsupp_apply (s : multiset α) (a : α) : to_finsupp s a = s.count a := rfl lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _ lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := to_finsupp.map_add s t @[simp] lemma to_finsupp_singleton (a : α) : to_finsupp (a ::ₘ 0) = finsupp.single a 1 := finsupp.to_multiset.symm_apply_eq.2 $ by simp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := finsupp.to_multiset.apply_symm_apply s lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset := finsupp.to_multiset.symm_apply_eq end multiset @[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) : f.to_multiset.to_finsupp = f := finsupp.to_multiset.symm_apply_apply f /-! ### Declarations about order(ed) instances on `finsupp` -/ namespace finsupp instance [preorder M] [has_zero M] : preorder (α →₀ M) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order M] [has_zero M] : partial_order (α →₀ M) := { le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_cancel_add_comm_monoid M] : add_left_cancel_semigroup (α →₀ M) := { add_left_cancel := λ a b c h, ext $ λ s, by { rw ext_iff at h, exact add_left_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_add_comm_monoid M] : add_right_cancel_semigroup (α →₀ M) := { add_right_cancel := λ a b c h, ext $ λ s, by { rw ext_iff at h, exact add_right_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order, .. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup } lemma le_def [preorder M] [has_zero M] {f g : α →₀ M} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl lemma le_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ @[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] /-- `finsupp.to_multiset` as an order isomorphism. -/ def order_iso_multiset : (α →₀ ℕ) ≃o multiset α := { to_equiv := to_multiset.to_equiv, map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] } @[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset α) = to_multiset := rfl @[simp] lemma coe_order_iso_multiset_symm : ⇑(@order_iso_multiset α).symm = multiset.to_finsupp := rfl lemma to_multiset_strict_mono : strict_mono (@to_multiset α) := order_iso_multiset.strict_mono lemma sum_id_lt_of_lt (m n : α →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (α) /-- The order on `σ →₀ ℕ` is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (α →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf instance decidable_le : decidable_rel (@has_le.le (α →₀ ℕ) _) := λ m n, by rw le_iff; apply_instance variable {α} @[simp] lemma nat_add_sub_cancel (f g : α →₀ ℕ) : f + g - g = f := ext $ λ a, nat.add_sub_cancel _ _ @[simp] lemma nat_add_sub_cancel_left (f g : α →₀ ℕ) : f + g - f = g := ext $ λ a, nat.add_sub_cancel_left _ _ lemma nat_add_sub_of_le {f g : α →₀ ℕ} (h : f ≤ g) : f + (g - f) = g := ext $ λ a, nat.add_sub_of_le (h a) lemma nat_sub_add_cancel {f g : α →₀ ℕ} (h : f ≤ g) : g - f + f = g := ext $ λ a, nat.sub_add_cancel (h a) instance : canonically_ordered_add_monoid (α →₀ ℕ) := { bot := 0, bot_le := λ f s, zero_le (f s), le_iff_exists_add := λ f g, ⟨λ H, ⟨g - f, (nat_add_sub_of_le H).symm⟩, λ ⟨c, hc⟩, hc.symm ▸ λ x, by simp⟩, .. (infer_instance : ordered_add_comm_monoid (α →₀ ℕ)) } /-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal (f : α →₀ ℕ) : ((α →₀ ℕ) × (α →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp @[simp] lemma mem_antidiagonal_support {f : α →₀ ℕ} {p : (α →₀ ℕ) × (α →₀ ℕ)} : p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f := begin rcases p with ⟨p₁, p₂⟩, simp [antidiagonal, ← and.assoc, ← finsupp.to_multiset.apply_eq_iff_eq] end lemma swap_mem_antidiagonal_support {n : α →₀ ℕ} {f : (α →₀ ℕ) × (α →₀ ℕ)} : f.swap ∈ (antidiagonal n).support ↔ f ∈ (antidiagonal n).support := by simp only [mem_antidiagonal_support, add_comm, prod.swap] lemma antidiagonal_support_filter_fst_eq (f g : α →₀ ℕ) : (antidiagonal f).support.filter (λ p, p.1 = g) = if g ≤ f then {(g, f - g)} else ∅ := begin ext ⟨a, b⟩, suffices : a = g → (a + b = f ↔ g ≤ f ∧ b = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, @and.right_comm _ (a = _), and.congr_left_iff] }, rintro rfl, split, { rintro rfl, exact ⟨le_add_right le_rfl, (nat_add_sub_cancel_left _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact nat_add_sub_of_le h } end lemma antidiagonal_support_filter_snd_eq (f g : α →₀ ℕ) : (antidiagonal f).support.filter (λ p, p.2 = g) = if g ≤ f then {(f - g, g)} else ∅ := begin ext ⟨a, b⟩, suffices : b = g → (a + b = f ↔ g ≤ f ∧ a = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, and.congr_left_iff] }, rintro rfl, split, { rintro rfl, exact ⟨le_add_left le_rfl, (nat_add_sub_cancel _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact nat_sub_add_cancel h } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = single (0,0) 1 := by rw [← multiset.to_finsupp_singleton]; refl @[to_additive] lemma prod_antidiagonal_support_swap {M : Type*} [comm_monoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : ∏ p in (antidiagonal n).support, f p.1 p.2 = ∏ p in (antidiagonal n).support, f p.2 p.1 := finset.prod_bij (λ p hp, p.swap) (λ p, swap_mem_antidiagonal_support.2) (λ p hp, rfl) (λ p₁ p₂ _ _ h, prod.swap_injective h) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support.2 hp, p.swap_swap.symm⟩) /-- The set `{m : α →₀ ℕ | m ≤ n}` as a `finset`. -/ def Iic_finset (n : α →₀ ℕ) : finset (α →₀ ℕ) := (antidiagonal n).support.image prod.fst @[simp] lemma mem_Iic_finset {m n : α →₀ ℕ} : m ∈ Iic_finset n ↔ m ≤ n := by simp [Iic_finset, le_iff_exists_add, eq_comm] @[simp] lemma coe_Iic_finset (n : α →₀ ℕ) : ↑(Iic_finset n) = set.Iic n := by { ext, simp } /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, is a finite set. -/ lemma finite_le_nat (n : α →₀ ℕ) : set.finite {m | m ≤ n} := by simpa using (Iic_finset n).finite_to_set /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, but not equal to `n` everywhere, is a finite set. -/ lemma finite_lt_nat (n : α →₀ ℕ) : set.finite {m | m < n} := (finite_le_nat n).subset $ λ m, le_of_lt end finsupp namespace multiset lemma to_finsuppstrict_mono : strict_mono (@to_finsupp α) := finsupp.order_iso_multiset.symm.strict_mono end multiset
f3f3fd75b18c1bf9c9998b9a3eee57dae58f0c5d
5d95c8513fa8592ce314d1f40c23ad5eecfe1e34
/src/util/signature_inst.lean
31c64f2d3a5392a874142f93adef5f982e1524ff
[ "Apache-2.0" ]
permissive
solovay/lean-universal
6b792513ced2fe82218e7828400743375dd59e24
417ed5e1b030e547912cbfefe34df9d3d01c2b65
refs/heads/master
1,598,052,603,315
1,565,981,123,000
1,565,981,123,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,992
lean
import .default import .meta.default definition list.pure {α : Type*} (x : α) : list α := [x] namespace tactic meta def mk_list_expr (ty : expr) : list expr → tactic expr | [] := mk_app `list.nil [ty] | (e :: es) := mk_list_expr es >>= λ es, mk_app `list.cons [ty, e, es] meta def get_structure_fields (nm : name) : tactic (list name) := do { nm ← resolve_constant nm, env ← get_env, env.structure_fields nm } #print unification_hint.mk meta def add_structure_field_hints (d : declaration) : tactic unit := do { (ctx, typ) ← mk_local_pis d.type, val ← pure $ d.value.mk_app_beta ctx, let tnm := typ.get_app_fn.const_name, fns ← get_structure_fields tnm, dobj ← mk_app d.to_name ctx, gobj ← mk_local' `t binder_info.default typ, let ctx := ctx ++ [gobj], hcns ← mk_mapp `unification_constraint.mk [none, some gobj, some dobj], hcns ← infer_type hcns >>= λ t, mk_list_expr t [hcns], (fns.reverse.zip val.get_app_args.reverse).mfoldl (λ k ⟨fn, fv⟩, do { fe ← mk_mapp (tnm ++ fn) $ (typ.get_app_args ++ [gobj]).map option.some, hpat ← mk_mapp `unification_constraint.mk [none, some fe, some fv], hintv ← mk_mapp `unification_hint.mk [some hpat, some hcns], hintt ← infer_type hintv, let hintn : name := d.to_name ++ mk_sub_name `_hint (k+1), let hintt : expr := hintt.pis ctx, let hintv : expr := hintv.lambdas ctx, let hdecl := declaration.defn hintn hintt.collect_univ_params hintt hintv reducibility_hints.abbrev tt, add_decl hdecl, set_basic_attribute `unify hintn tt, pure (k+1) } <|> (pure k)) (0), skip } end tactic section signature_inst_attr open tactic @[user_attribute] meta def algebra.signature_inst_attr : user_attribute := { name := `signature_instance , descr := "declare an algebraic signature instance" , after_set := some $ λ nm _ _, do { decl ← resolve_constant nm >>= get_decl, add_structure_field_hints decl } } end signature_inst_attr
eea72083507d2d4aab25905201c21ed5a2edc0f4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/sums/basic.lean
56f891cf21bdc89ea28958319c2e1fd851d27eb6
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,372
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.eq_to_hom /-! # Binary disjoint unions of categories We define the category instance on `C ⊕ D` when `C` and `D` are categories. We define: * `inl_` : the functor `C ⥤ C ⊕ D` * `inr_` : the functor `D ⥤ C ⊕ D` * `swap` : the functor `C ⊕ D ⥤ D ⊕ C` (and the fact this is an equivalence) We further define sums of functors and natural transformations, written `F.sum G` and `α.sum β`. -/ namespace category_theory universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. open sum section variables (C : Type u₁) [category.{v₁} C] (D : Type u₁) [category.{v₁} D] /-- `sum C D` gives the direct sum of two categories. -/ instance sum : category.{v₁} (C ⊕ D) := { hom := λ X Y, match X, Y with | inl X, inl Y := X ⟶ Y | inl X, inr Y := pempty | inr X, inl Y := pempty | inr X, inr Y := X ⟶ Y end, id := λ X, match X with | inl X := 𝟙 X | inr X := 𝟙 X end, comp := λ X Y Z f g, match X, Y, Z, f, g with | inl X, inl Y, inl Z, f, g := f ≫ g | inr X, inr Y, inr Z, f, g := f ≫ g end } @[simp] lemma sum_comp_inl {P Q R : C} (f : (inl P : C ⊕ D) ⟶ inl Q) (g : inl Q ⟶ inl R) : f ≫ g = (f : P ⟶ Q) ≫ (g : Q ⟶ R) := rfl @[simp] lemma sum_comp_inr {P Q R : D} (f : (inr P : C ⊕ D) ⟶ inr Q) (g : inr Q ⟶ inr R) : f ≫ g = (f : P ⟶ Q) ≫ (g : Q ⟶ R) := rfl end namespace sum variables (C : Type u₁) [category.{v₁} C] (D : Type u₁) [category.{v₁} D] /-- `inl_` is the functor `X ↦ inl X`. -/ -- Unfortunate naming here, suggestions welcome. @[simps] def inl_ : C ⥤ C ⊕ D := { obj := λ X, inl X, map := λ X Y f, f } /-- `inr_` is the functor `X ↦ inr X`. -/ @[simps] def inr_ : D ⥤ C ⊕ D := { obj := λ X, inr X, map := λ X Y f, f } /-- The functor exchanging two direct summand categories. -/ def swap : C ⊕ D ⥤ D ⊕ C := { obj := λ X, match X with | inl X := inr X | inr X := inl X end, map := λ X Y f, match X, Y, f with | inl X, inl Y, f := f | inr X, inr Y, f := f end } @[simp] lemma swap_obj_inl (X : C) : (swap C D).obj (inl X) = inr X := rfl @[simp] lemma swap_obj_inr (X : D) : (swap C D).obj (inr X) = inl X := rfl @[simp] lemma swap_map_inl {X Y : C} {f : inl X ⟶ inl Y} : (swap C D).map f = f := rfl @[simp] lemma swap_map_inr {X Y : D} {f : inr X ⟶ inr Y} : (swap C D).map f = f := rfl namespace swap /-- `swap` gives an equivalence between `C ⊕ D` and `D ⊕ C`. -/ def equivalence : C ⊕ D ≌ D ⊕ C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (λ X, eq_to_iso (by { cases X; refl })) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by { cases X; refl })) (by tidy)) instance is_equivalence : is_equivalence (swap C D) := (by apply_instance : is_equivalence (equivalence C D).functor) /-- The double swap on `C ⊕ D` is naturally isomorphic to the identity functor. -/ def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C ⊕ D) := (equivalence C D).unit_iso.symm end swap end sum variables {A : Type u₁} [category.{v₁} A] {B : Type u₁} [category.{v₁} B] {C : Type u₁} [category.{v₁} C] {D : Type u₁} [category.{v₁} D] namespace functor /-- The sum of two functors. -/ def sum (F : A ⥤ B) (G : C ⥤ D) : A ⊕ C ⥤ B ⊕ D := { obj := λ X, match X with | inl X := inl (F.obj X) | inr X := inr (G.obj X) end, map := λ X Y f, match X, Y, f with | inl X, inl Y, f := F.map f | inr X, inr Y, f := G.map f end, map_id' := λ X, begin cases X; unfold_aux, erw F.map_id, refl, erw G.map_id, refl end, map_comp' := λ X Y Z f g, match X, Y, Z, f, g with | inl X, inl Y, inl Z, f, g := by { unfold_aux, erw F.map_comp, refl } | inr X, inr Y, inr Z, f, g := by { unfold_aux, erw G.map_comp, refl } end } @[simp] lemma sum_obj_inl (F : A ⥤ B) (G : C ⥤ D) (a : A) : (F.sum G).obj (inl a) = inl (F.obj a) := rfl @[simp] lemma sum_obj_inr (F : A ⥤ B) (G : C ⥤ D) (c : C) : (F.sum G).obj (inr c) = inr (G.obj c) := rfl @[simp] lemma sum_map_inl (F : A ⥤ B) (G : C ⥤ D) {a a' : A} (f : inl a ⟶ inl a') : (F.sum G).map f = F.map f := rfl @[simp] lemma sum_map_inr (F : A ⥤ B) (G : C ⥤ D) {c c' : C} (f : inr c ⟶ inr c') : (F.sum G).map f = G.map f := rfl end functor namespace nat_trans /-- The sum of two natural transformations. -/ def sum {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : F.sum H ⟶ G.sum I := { app := λ X, match X with | inl X := α.app X | inr X := β.app X end, naturality' := λ X Y f, match X, Y, f with | inl X, inl Y, f := begin unfold_aux, erw α.naturality, refl, end | inr X, inr Y, f := begin unfold_aux, erw β.naturality, refl, end end } @[simp] lemma sum_app_inl {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (a : A) : (sum α β).app (inl a) = α.app a := rfl @[simp] lemma sum_app_inr {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (c : C) : (sum α β).app (inr c) = β.app c := rfl end nat_trans end category_theory
292169f8d7435020611e0b5b412985d5638452ed
4727251e0cd73359b15b664c3170e5d754078599
/src/set_theory/ordinal/notation.lean
ffe759818abebd9c5f55a27ef2d747af30d44d77
[ "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
35,907
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import set_theory.ordinal.principal /-! # Ordinal notation Constructive ordinal arithmetic for ordinals below `ε₀`. We define a type `onote`, with constructors `0 : onote` and `onote.oadd e n a` representing `ω ^ e * n + a`. We say that `o` is in Cantor normal form - `onote.NF o` - if either `o = 0` or `o = ω ^ e * n + a` with `a < ω ^ e` and `a` in Cantor normal form. The type `nonote` is the type of ordinals below `ε₀` in Cantor normal form. Various operations (addition, subtraction, multiplication, power function) are defined on `onote` and `nonote`. -/ open ordinal open_locale ordinal -- get notation for `ω` /-- Recursive definition of an ordinal notation. `zero` denotes the ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`. For this to be valid Cantor normal form, we must have the exponents decrease to the right, but we can't state this condition until we've defined `repr`, so it is a separate definition `NF`. -/ @[derive decidable_eq] inductive onote : Type | zero : onote | oadd : onote → ℕ+ → onote → onote namespace onote /-- Notation for 0 -/ instance : has_zero onote := ⟨zero⟩ @[simp] theorem zero_def : zero = 0 := rfl instance : inhabited onote := ⟨0⟩ /-- Notation for 1 -/ instance : has_one onote := ⟨oadd 0 1 0⟩ /-- Notation for ω -/ def omega : onote := oadd 1 1 0 /-- The ordinal denoted by a notation -/ @[simp] noncomputable def repr : onote → ordinal.{0} | 0 := 0 | (oadd e n a) := ω ^ repr e * n + repr a /-- Auxiliary definition to print an ordinal notation -/ def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string := if e = 0 then _root_.to_string n else (if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++ if n = 1 then "" else "*" ++ _root_.to_string n /-- Print an ordinal notation -/ def to_string : onote → string | zero := "0" | (oadd e n 0) := to_string_aux1 e n (to_string e) | (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a /-- Print an ordinal notation -/ def repr' : onote → string | zero := "0" | (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:ℕ) ++ " " ++ repr' a ++ ")" instance : has_to_string onote := ⟨to_string⟩ instance : has_repr onote := ⟨repr'⟩ instance : preorder onote := { le := λ x y, repr x ≤ repr y, lt := λ x y, repr x < repr y, le_refl := λ a, @le_refl ordinal _ _, le_trans := λ a b c, @le_trans ordinal _ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ } theorem lt_def {x y : onote} : x < y ↔ repr x < repr y := iff.rfl theorem le_def {x y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl /-- Convert a `nat` into an ordinal -/ @[simp] def of_nat : ℕ → onote | 0 := 0 | (nat.succ n) := oadd 0 n.succ_pnat 0 @[simp] theorem of_nat_one : of_nat 1 = 1 := rfl @[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = n := by cases n; simp @[simp] theorem repr_one : repr 1 = 1 := by simpa using repr_of_nat 1 theorem omega_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) := begin unfold repr, refine le_trans _ (le_add_right _ _), simpa using (mul_le_mul_iff_left $ opow_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2) end theorem oadd_pos (e n a) : 0 < oadd e n a := @lt_of_lt_of_le _ _ _ _ _ (opow_pos _ omega_pos) (omega_le_oadd _ _ _) /-- Compare ordinal notations -/ def cmp : onote → onote → ordering | 0 0 := ordering.eq | _ 0 := ordering.gt | 0 _ := ordering.lt | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) := (cmp e₁ e₂).or_else $ (_root_.cmp (n₁:ℕ) n₂).or_else (cmp a₁ a₂) theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = ordering.eq → o₁ = o₂ | 0 0 h := rfl | (oadd e n a) 0 h := by injection h | 0 (oadd e n a) h := by injection h | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h := begin revert h, simp only [cmp], cases h₁ : cmp e₁ e₂; intro h; try {cases h}, obtain rfl := eq_of_cmp_eq h₁, revert h, cases h₂ : _root_.cmp (n₁:ℕ) n₂; intro h; try {cases h}, obtain rfl := eq_of_cmp_eq h, rw [_root_.cmp, cmp_using_eq_eq] at h₂, obtain rfl := subtype.eq (eq_of_incomp h₂), simp end theorem zero_lt_one : (0 : onote) < 1 := by rw [lt_def, repr, repr_one]; exact zero_lt_one /-- `NF_below o b` says that `o` is a normal form ordinal notation satisfying `repr o < ω ^ b`. -/ inductive NF_below : onote → ordinal.{0} → Prop | zero {b} : NF_below 0 b | oadd' {e n a eb b} : NF_below e eb → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b /-- A normal form ordinal notation has the form ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are also in normal form. We will essentially only be interested in normal form ordinal notations, but to avoid complicating the algorithms we define everything over general ordinal notations and only prove correctness with normal form as an invariant. -/ class NF (o : onote) : Prop := (out : Exists (NF_below o)) attribute [pp_nodot] NF instance NF.zero : NF 0 := ⟨⟨0, NF_below.zero⟩⟩ theorem NF_below.oadd {e n a b} : NF e → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b | ⟨⟨eb, h⟩⟩ := NF_below.oadd' h theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact ⟨⟨_, h₁⟩⟩ theorem NF.fst {e n a} : NF (oadd e n a) → NF e | ⟨⟨b, h⟩⟩ := h.fst theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₂ theorem NF.snd' {e n a} : NF (oadd e n a) → NF_below a (repr e) | ⟨⟨b, h⟩⟩ := h.snd theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a := ⟨⟨_, h.snd'⟩⟩ theorem NF.oadd {e a} (h₁ : NF e) (n) (h₂ : NF_below a (repr e)) : NF (oadd e n a) := ⟨⟨_, NF_below.oadd h₁ h₂ (ordinal.lt_succ_self _)⟩⟩ instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) := h.oadd _ NF_below.zero theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₃ theorem NF_below_zero : ∀ {o}, NF_below o 0 ↔ o = 0 | 0 := ⟨λ _, rfl, λ _, NF_below.zero⟩ | (oadd e n a) := ⟨λ h, (not_le_of_lt h.lt).elim (ordinal.zero_le _), λ e, e.symm ▸ NF_below.zero⟩ theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 := by simpa [e0, NF_below_zero] using h.snd' theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < ω ^ b := begin induction h with _ e n a eb b h₁ h₂ h₃ _ IH, { exact opow_pos _ omega_pos }, { rw repr, apply ((add_lt_add_iff_left _).2 IH).trans_le, rw ← mul_succ, apply (mul_le_mul_left' (ordinal.succ_le.2 (nat_lt_omega _)) _).trans, rw ← opow_succ, exact opow_le_opow_right omega_pos (ordinal.succ_le.2 h₃) } end theorem NF_below.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ := begin induction h with _ e n a eb b h₁ h₂ h₃ _ IH; constructor, exacts [h₁, h₂, lt_of_lt_of_le h₃ bb] end theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b | ⟨⟨b', h⟩⟩ := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact NF_below.oadd' h₁ h₂ H theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NF_below o b | 0 b H _ := NF_below.zero | (oadd e n a) b H h := h.below_of_lt $ (opow_lt_opow_iff_right one_lt_omega).1 $ (lt_of_le_of_lt (omega_le_oadd _ _ _) H) theorem NF_below_of_nat : ∀ n, NF_below (of_nat n) 1 | 0 := NF_below.zero | (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one instance NF_of_nat (n) : NF (of_nat n) := ⟨⟨_, NF_below_of_nat n⟩⟩ instance NF_one : NF 1 := by rw ← of_nat_one; apply_instance theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂} (h₁ : NF (oadd e₁ n₁ o₁)) (h : e₁ < e₂) : oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ := @lt_of_lt_of_le _ _ _ _ _ ((h₁.below_of_lt h).repr_lt) (omega_le_oadd _ _ _) theorem oadd_lt_oadd_2 {e o₁ o₂ : onote} {n₁ n₂ : ℕ+} (h₁ : NF (oadd e n₁ o₁)) (h : (n₁:ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ := begin simp [lt_def], refine lt_of_lt_of_le ((add_lt_add_iff_left _).2 h₁.snd'.repr_lt) (le_trans _ (le_add_right _ _)), rwa [← mul_succ, mul_le_mul_iff_left (opow_pos _ omega_pos), ordinal.succ_le, nat_cast_lt] end theorem oadd_lt_oadd_3 {e n a₁ a₂} (h : a₁ < a₂) : oadd e n a₁ < oadd e n a₂ := begin rw lt_def, unfold repr, exact add_lt_add_left h _ end theorem cmp_compares : ∀ (a b : onote) [NF a] [NF b], (cmp a b).compares a b | 0 0 h₁ h₂ := rfl | (oadd e n a) 0 h₁ h₂ := oadd_pos _ _ _ | 0 (oadd e n a) h₁ h₂ := oadd_pos _ _ _ | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h₁ h₂ := begin rw cmp, have IHe := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂, case ordering.lt { exact oadd_lt_oadd_1 h₁ IHe }, case ordering.gt { exact oadd_lt_oadd_1 h₂ IHe }, change e₁ = e₂ at IHe, subst IHe, unfold _root_.cmp, cases nh : cmp_using (<) (n₁:ℕ) n₂, case ordering.lt { rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 h₁ nh }, case ordering.gt { rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 h₂ nh }, rw cmp_using_eq_eq at nh, obtain rfl := subtype.eq (eq_of_incomp nh), have IHa := @cmp_compares _ _ h₁.snd h₂.snd, cases cmp a₁ a₂, case ordering.lt { exact oadd_lt_oadd_3 IHa }, case ordering.gt { exact oadd_lt_oadd_3 IHa }, change a₁ = a₂ at IHa, subst IHa, exact rfl end theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b := ⟨match cmp a b, cmp_compares a b with | ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim | ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim | ordering.eq, h, e := h end, congr_arg _⟩ theorem NF.of_dvd_omega_opow {b e n a} (h : NF (oadd e n a)) (d : ω ^ b ∣ repr (oadd e n a)) : b ≤ repr e ∧ ω ^ b ∣ repr a := begin have := mt repr_inj.1 (λ h, by injection h : oadd e n a ≠ 0), have L := le_of_not_lt (λ l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)), simp at d, exact ⟨L, (dvd_add_iff $ (opow_dvd_opow _ L).mul_right _).1 d⟩ end theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) : ω ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a := by rw [← opow_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega_opow /-- `top_below b o` asserts that the largest exponent in `o`, if it exists, is less than `b`. This is an auxiliary definition for decidability of `NF`. -/ def top_below (b) : onote → Prop | 0 := true | (oadd e n a) := cmp e b = ordering.lt instance decidable_top_below : decidable_rel top_below := by intros b o; cases o; delta top_below; apply_instance theorem NF_below_iff_top_below {b} [NF b] : ∀ {o}, NF_below o (repr b) ↔ NF o ∧ top_below b o | 0 := ⟨λ h, ⟨⟨⟨_, h⟩⟩, trivial⟩, λ _, NF_below.zero⟩ | (oadd e n a) := ⟨λ h, ⟨⟨⟨_, h⟩⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩, λ ⟨h₁, h₂⟩, h₁.below_of_lt $ (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩ instance decidable_NF : decidable_pred NF | 0 := is_true NF.zero | (oadd e n a) := begin have := decidable_NF e, have := decidable_NF a, resetI, apply decidable_of_iff (NF e ∧ NF a ∧ top_below e a), abstract { rw ← and_congr_right (λ h, @NF_below_iff_top_below _ h _), exact ⟨λ ⟨h₁, h₂⟩, NF.oadd h₁ n h₂, λ h, ⟨h.fst, h.snd'⟩⟩ }, end /-- Addition of ordinal notations (correct only for normal input) -/ def add : onote → onote → onote | 0 o := o | (oadd e n a) o := match add a o with | 0 := oadd e n 0 | o'@(oadd e' n' a') := match cmp e e' with | ordering.lt := o' | ordering.eq := oadd e (n + n') a' | ordering.gt := oadd e n o' end end instance : has_add onote := ⟨add⟩ @[simp] theorem zero_add (o : onote) : 0 + o = o := rfl theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl /-- Subtraction of ordinal notations (correct only for normal input) -/ def sub : onote → onote → onote | 0 o := 0 | o 0 := o | o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := match cmp e₁ e₂ with | ordering.lt := 0 | ordering.gt := o₁ | ordering.eq := match (n₁:ℕ) - n₂ with | 0 := if n₁ = n₂ then sub a₁ a₂ else 0 | (nat.succ k) := oadd e₁ k.succ_pnat a₁ end end instance : has_sub onote := ⟨sub⟩ theorem add_NF_below {b} : ∀ {o₁ o₂}, NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b | 0 o h₁ h₂ := h₂ | (oadd e n a) o h₁ h₂ := begin have h' := add_NF_below (h₁.snd.mono $ le_of_lt h₁.lt) h₂, simp [oadd_add], cases a + o with e' n' a', { exact NF_below.oadd h₁.fst NF_below.zero h₁.lt }, simp [add], have := @cmp_compares _ _ h₁.fst h'.fst, cases cmp e e'; simp [add], { exact h' }, { simp at this, subst e', exact NF_below.oadd h'.fst h'.snd h'.lt }, { exact NF_below.oadd h₁.fst (NF.below_of_lt this ⟨⟨_, h'⟩⟩) h₁.lt } end instance add_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂) | ⟨⟨b₁, h₁⟩⟩ ⟨⟨b₂, h₂⟩⟩ := ⟨(b₁.le_total b₂).elim (λ h, ⟨b₂, add_NF_below (h₁.mono h) h₂⟩) (λ h, ⟨b₁, add_NF_below h₁ (h₂.mono h)⟩)⟩ @[simp] theorem repr_add : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂ | 0 o h₁ h₂ := by simp | (oadd e n a) o h₁ h₂ := begin haveI := h₁.snd, have h' := repr_add a o, conv at h' in (_+o) {simp [(+)]}, have nf := onote.add_NF a o, conv at nf in (_+o) {simp [(+)]}, conv in (_+o) {simp [(+), add]}, cases add a o with e' n' a'; simp [add, h'.symm, add_assoc], have := h₁.fst, haveI := nf.fst, have ee := cmp_compares e e', cases cmp e e'; simp [add], { rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n':ℕ))], { have := (h₁.below_of_lt ee).repr_lt, unfold repr at this, exact lt_of_le_of_lt (le_add_right _ _) this }, { simpa using (mul_le_mul_iff_left $ opow_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } }, { change e = e' at ee, substI e', rw [← add_assoc, ← ordinal.mul_add, ← nat.cast_add] } end theorem sub_NF_below : ∀ {o₁ o₂ b}, NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b | 0 o b h₁ h₂ := by cases o; exact NF_below.zero | (oadd e n a) 0 b h₁ h₂ := h₁ | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) b h₁ h₂ := begin have h' := sub_NF_below h₁.snd h₂.snd, simp [has_sub.sub, sub] at h' ⊢, have := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂; simp [sub], { apply NF_below.zero }, { simp at this, subst e₂, cases mn : (n₁:ℕ) - n₂; simp [sub], { by_cases en : n₁ = n₂; simp [en], { exact h'.mono (le_of_lt h₁.lt) }, { exact NF_below.zero } }, { exact NF_below.oadd h₁.fst h₁.snd h₁.lt } }, { exact h₁ } end instance sub_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂) | ⟨⟨b₁, h₁⟩⟩ h₂ := ⟨⟨b₁, sub_NF_below h₁ h₂⟩⟩ @[simp] theorem repr_sub : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂ | 0 o h₁ h₂ := by cases o; exact (ordinal.zero_sub _).symm | (oadd e n a) 0 h₁ h₂ := (ordinal.sub_zero _).symm | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin haveI := h₁.snd, haveI := h₂.snd, have h' := repr_sub a₁ a₂, conv at h' in (a₁-a₂) {simp [has_sub.sub]}, have nf := onote.sub_NF a₁ a₂, conv at nf in (a₁-a₂) {simp [has_sub.sub]}, conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]}, have ee := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂, { rw [ordinal.sub_eq_zero_iff_le.2], {refl}, exact le_of_lt (oadd_lt_oadd_1 h₁ ee) }, { change e₁ = e₂ at ee, substI e₂, unfold sub._match_1, cases mn : (n₁:ℕ) - n₂; dsimp only [sub._match_2], { by_cases en : n₁ = n₂, { simp [en], rwa [add_sub_add_cancel] }, { simp [en, -repr], exact (ordinal.sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 h₁ $ lt_of_le_of_ne (tsub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } }, { simp [nat.succ_pnat, -nat.cast_succ], rw [(tsub_eq_iff_eq_add_of_le $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn, add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel], refine (ordinal.sub_eq_of_add_eq $ add_absorp h₂.snd'.repr_lt $ le_trans _ (le_add_right _ _)).symm, simpa using mul_le_mul_left' (nat_cast_le.2 $ nat.succ_pos _) _ } }, { exact (ordinal.sub_eq_of_add_eq $ add_absorp (h₂.below_of_lt ee).repr_lt $ omega_le_oadd _ _ _).symm } end /-- Multiplication of ordinal notations (correct only for normal input) -/ def mul : onote → onote → onote | 0 _ := 0 | _ 0 := 0 | o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (mul o₁ a₂) instance : has_mul onote := ⟨mul⟩ @[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl @[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ = if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl theorem oadd_mul_NF_below {e₁ n₁ a₁ b₁} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) : ∀ {o₂ b₂}, NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂) | 0 b₂ h₂ := NF_below.zero | (oadd e₂ n₂ a₂) b₂ h₂ := begin have IH := oadd_mul_NF_below h₂.snd, by_cases e0 : e₂ = 0; simp [e0, oadd_mul], { apply NF_below.oadd h₁.fst h₁.snd, simpa using (add_lt_add_iff_left (repr e₁)).2 (lt_of_le_of_lt (ordinal.zero_le _) h₂.lt) }, { haveI := h₁.fst, haveI := h₂.fst, apply NF_below.oadd, apply_instance, { rwa repr_add }, { rw [repr_add, add_lt_add_iff_left], exact h₂.lt } } end instance mul_NF : ∀ o₁ o₂ [NF o₁] [NF o₂], NF (o₁ * o₂) | 0 o h₁ h₂ := by cases o; exact NF.zero | (oadd e n a) o ⟨⟨b₁, hb₁⟩⟩ ⟨⟨b₂, hb₂⟩⟩ := ⟨⟨_, oadd_mul_NF_below hb₁ hb₂⟩⟩ @[simp] theorem repr_mul : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂ | 0 o h₁ h₂ := by cases o; exact (ordinal.zero_mul _).symm | (oadd e₁ n₁ a₁) 0 h₁ h₂ := (ordinal.mul_zero _).symm | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd, conv {to_lhs, simp [(*)]}, have ao : repr a₁ + ω ^ repr e₁ * (n₁:ℕ) = ω ^ repr e₁ * (n₁:ℕ), { apply add_absorp h₁.snd'.repr_lt, simpa using (mul_le_mul_iff_left $ opow_pos _ omega_pos).2 (nat_cast_le.2 n₁.2) }, by_cases e0 : e₂ = 0; simp [e0, mul], { cases nat.exists_eq_succ_of_ne_zero n₂.ne_zero with x xe, simp [h₂.zero_of_zero e0, xe, -nat.cast_succ], rw [← nat_cast_succ x, add_mul_succ _ ao, mul_assoc] }, { haveI := h₁.fst, haveI := h₂.fst, simp [IH, repr_add, opow_add, ordinal.mul_add], rw ← mul_assoc, congr' 2, have := mt repr_inj.1 e0, rw [add_mul_limit ao (opow_is_limit_left omega_is_limit this), mul_assoc, mul_omega_dvd (nat_cast_pos.2 n₁.pos) (nat_lt_omega _)], simpa using opow_dvd_opow ω (one_le_iff_ne_zero.2 this) }, end /-- Calculate division and remainder of `o` mod ω. `split' o = (a, n)` means `o = ω * a + n`. -/ def split' : onote → onote × ℕ | 0 := (0, 0) | (oadd e n a) := if e = 0 then (0, n) else let (a', m) := split' a in (oadd (e - 1) n a', m) /-- Calculate division and remainder of `o` mod ω. `split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/ def split : onote → onote × ℕ | 0 := (0, 0) | (oadd e n a) := if e = 0 then (0, n) else let (a', m) := split a in (oadd e n a', m) /-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/ def scale (x : onote) : onote → onote | 0 := 0 | (oadd e n a) := oadd (x + e) n (scale a) /-- `mul_nat o n` is the ordinal notation for `o * n`. -/ def mul_nat : onote → ℕ → onote | 0 m := 0 | _ 0 := 0 | (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a /-- Auxiliary definition to compute the ordinal notation for the ordinal exponentiation in `opow` -/ def opow_aux (e a0 a : onote) : ℕ → ℕ → onote | _ 0 := 0 | 0 (m+1) := oadd e m.succ_pnat 0 | (k+1) m := scale (e + mul_nat a0 k) a + opow_aux k m /-- `opow o₁ o₂` calculates the ordinal notation for the ordinal exponential `o₁ ^ o₂`. -/ def opow (o₁ o₂ : onote) : onote := match split o₁ with | (0, 0) := if o₂ = 0 then 1 else 0 | (0, 1) := 1 | (0, m+1) := let (b', k) := split' o₂ in oadd b' (@has_pow.pow ℕ+ _ _ m.succ_pnat k) 0 | (a@(oadd a0 _ _), m) := match split o₂ with | (b, 0) := oadd (a0 * b) 1 0 | (b, k+1) := let eb := a0*b in scale (eb + mul_nat a0 k) a + opow_aux eb a0 (mul_nat a m) k m end end instance : has_pow onote onote := ⟨opow⟩ theorem opow_def (o₁ o₂ : onote) : o₁ ^ o₂ = opow._match_1 o₂ (split o₁) := rfl theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m) | 0 o' m h p := by injection p; substs o' m; refl | (oadd e n a) o' m h p := begin by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢, { rcases p with ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ }, { revert p, cases h' : split' a with a' m', haveI := h.fst, haveI := h.snd, simp [split_eq_scale_split' h', split, split'], have : 1 + (e - 1) = e, { refine repr_inj.1 _, simp, have := mt repr_inj.1 e0, exact ordinal.add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) }, intros, substs o' m, simp [scale, this] } end theorem NF_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m | 0 o' m h p := by injection p; substs o' m; simp [NF.zero] | (oadd e n a) o' m h p := begin by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢, { rcases p with ⟨rfl, rfl⟩, simp [h.zero_of_zero e0, NF.zero] }, { revert p, cases h' : split' a with a' m', haveI := h.fst, haveI := h.snd, cases NF_repr_split' h' with IH₁ IH₂, simp [IH₂, split'], intros, substs o' m, have : ω ^ repr e = ω ^ (1 : ordinal.{0}) * ω ^ (repr e - 1), { have := mt repr_inj.1 e0, rw [← opow_add, ordinal.add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] }, refine ⟨NF.oadd (by apply_instance) _ _, _⟩, { simp at this ⊢, refine IH₁.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $ lt_of_le_of_lt (le_add_right _ m') _), rw [← this, ← IH₂], exact h.snd'.repr_lt }, { rw this, simp [ordinal.mul_add, mul_assoc, add_assoc] } } end theorem scale_eq_mul (x) [NF x] : ∀ o [NF o], scale x o = oadd x 1 0 * o | 0 h := rfl | (oadd e n a) h := begin simp [(*)], simp [mul, scale], haveI := h.snd, by_cases e0 : e = 0, { rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] }, { simp [e0, scale_eq_mul, (*)] } end instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) := by rw scale_eq_mul; apply_instance @[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o := by simp [scale_eq_mul] theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m := begin cases e : split' o with a n, cases NF_repr_split' e with s₁ s₂, resetI, rw split_eq_scale_split' e at h, injection h, substs o' n, simp [repr_scale, s₂.symm], apply_instance end theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' := begin cases e : split' o with a n, rw split_eq_scale_split' e at h, injection h, subst o', cases NF_repr_split' e, resetI, simp end theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e := begin cases NF_repr_split h with h₁ h₂, cases h₁.of_dvd_omega (split_dvd h) with e0 d, have := h₁.fst, have := h₁.snd, apply principal_add_omega_opow _ h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _), simpa using opow_le_opow_right omega_pos (one_le_iff_ne_zero.2 e0), end @[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n := by cases o; cases n; refl instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) := by simp; apply_instance instance NF_opow_aux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (opow_aux e a0 a k m) | k 0 := by cases k; exact NF.zero | 0 (m+1) := NF.oadd_zero _ _ | (k+1) (m+1) := by haveI := NF_opow_aux k; simp [opow_aux, nat.succ_ne_zero]; apply_instance instance NF_opow (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) := begin cases e₁ : split o₁ with a m, have na := (NF_repr_split e₁).1, cases e₂ : split' o₂ with b' k, haveI := (NF_repr_split' e₂).1, casesI a with a0 n a', { cases m with m, { by_cases o₂ = 0; simp [pow, opow, *]; apply_instance }, { by_cases m = 0, { simp only [pow, opow, *, zero_def], apply_instance }, { simp [pow, opow, *, - npow_eq_pow], apply_instance } } }, { simp [pow, opow, e₁, e₂, split_eq_scale_split' e₂], have := na.fst, cases k with k; simp [succ_eq_add_one, opow]; resetI; apply_instance } end theorem scale_opow_aux (e a0 a : onote) [NF e] [NF a0] [NF a] : ∀ k m, repr (opow_aux e a0 a k m) = ω ^ repr e * repr (opow_aux 0 a0 a k m) | 0 m := by cases m; simp [opow_aux] | (k+1) m := by by_cases m = 0; simp [h, opow_aux, ordinal.mul_add, opow_add, mul_assoc, scale_opow_aux] theorem repr_opow_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal} (e0 : repr e ≠ 0) (h : a' < ω ^ repr e) (aa : repr a = a') (n : ℕ+) : (ω ^ repr e * (n:ℕ) + a') ^ ω = (ω ^ repr e) ^ ω := begin subst aa, have No := Ne.oadd n (Na.below_of_lt' h), have := omega_le_oadd e n a, unfold repr at this, refine le_antisymm _ (opow_le_opow_left _ this), apply (opow_le_of_limit ((opow_pos _ omega_pos).trans_le this).ne' omega_is_limit).2, intros b l, have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this, apply (opow_le_opow_left b $ this.le).trans, rw [← opow_mul, ← opow_mul], apply opow_le_opow_right omega_pos, cases le_or_lt ω (repr e) with h h, { apply (mul_le_mul_left' (lt_succ_self _).le _).trans, rw [succ, add_mul_succ _ (one_add_of_omega_le h), ← succ, succ_le, mul_lt_mul_iff_left (ordinal.pos_iff_ne_zero.2 e0)], exact omega_is_limit.2 _ l }, { apply (principal_mul_omega (omega_is_limit.2 _ h) l).le.trans, simpa using mul_le_mul_right' (one_le_iff_ne_zero.2 e0) ω } end section local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow theorem repr_opow_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ) (d : ω ∣ repr a') (e0 : repr a0 ≠ 0) (h : repr a' + m < ω ^ repr a0) (n : ℕ+) (k : ℕ) : let R := repr (opow_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in (k ≠ 0 → R < (ω ^ repr a0) ^ succ k) ∧ (ω ^ repr a0) ^ k * (ω ^ repr a0 * (n:ℕ) + repr a') + R = (ω ^ repr a0 * (n:ℕ) + repr a' + m) ^ succ k := begin intro, haveI No : NF (oadd a0 n a') := N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h), induction k with k IH, {cases m; simp [opow_aux, R]}, rename R R', let R := repr (opow_aux 0 a0 (oadd a0 n a' * of_nat m) k m), let ω0 := ω ^ repr a0, let α' := ω0 * n + repr a', change (k ≠ 0 → R < ω0 ^ succ k) ∧ ω0 ^ k * α' + R = (α' + m) ^ succ k at IH, have RR : R' = ω0 ^ k * (α' * m) + R, { by_cases m = 0; simp [h, R', opow_aux, R, opow_mul], { cases k; simp [opow_aux] }, { refl } }, have α0 : 0 < α', {simpa [α', lt_def, repr] using oadd_pos a0 n a'}, have ω00 : 0 < ω0 ^ k := opow_pos _ (opow_pos _ omega_pos), have Rl : R < ω ^ (repr a0 * succ ↑k), { by_cases k0 : k = 0, { simp [k0], refine lt_of_lt_of_le _ (opow_le_opow_right omega_pos (one_le_iff_ne_zero.2 e0)), cases m with m; simp [k0, R, opow_aux, omega_pos], rw [← nat.cast_succ], apply nat_lt_omega }, { rw opow_mul, exact IH.1 k0 } }, refine ⟨λ_, _, _⟩, { rw [RR, ← opow_mul _ _ (succ k.succ)], have e0 := ordinal.pos_iff_ne_zero.2 e0, have rr0 := lt_of_lt_of_le e0 (le_add_left _ _), apply principal_add_omega_opow, { simp [opow_mul, ω0, opow_add, mul_assoc], rw [mul_lt_mul_iff_left ω00, ← ordinal.opow_add], have := (No.below_of_lt _).repr_lt, unfold repr at this, refine mul_lt_omega_opow rr0 this (nat_lt_omega _), simpa using (add_lt_add_iff_left (repr a0)).2 e0 }, { refine lt_of_lt_of_le Rl (opow_le_opow_right omega_pos $ mul_le_mul_left' (succ_le_succ.2 (nat_cast_le.2 (le_of_lt k.lt_succ_self))) _) } }, calc ω0 ^ k.succ * α' + R' = ω0 ^ succ k * α' + (ω0 ^ k * α' * m + R) : by rw [nat_cast_succ, RR, ← mul_assoc] ... = (ω0 ^ k * α' + R) * α' + (ω0 ^ k * α' + R) * m : _ ... = (α' + m) ^ succ k.succ : by rw [← ordinal.mul_add, ← nat_cast_succ, opow_succ, IH.2], congr' 1, { have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd_left (by simpa using opow_dvd_opow ω (one_le_iff_ne_zero.2 e0)) _) d, rw [ordinal.mul_add (ω0 ^ k), add_assoc, ← mul_assoc, ← opow_succ, add_mul_limit _ (is_limit_iff_omega_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc, @mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ αd], apply @add_absorp _ (repr a0 * succ k), { refine principal_add_omega_opow _ _ Rl, rw [opow_mul, opow_succ, mul_lt_mul_iff_left ω00], exact No.snd'.repr_lt }, { have := mul_le_mul_left' (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos) (ω0 ^ succ k), rw opow_mul, simpa [-opow_succ] } }, { cases m, { have : R = 0, {cases k; simp [R, opow_aux]}, simp [this] }, { rw [← nat_cast_succ, add_mul_succ], apply add_absorp Rl, rw [opow_mul, opow_succ], apply mul_le_mul_left', simpa [α', repr] using omega_le_oadd a0 n a' } } end end theorem repr_opow (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ := begin cases e₁ : split o₁ with a m, cases NF_repr_split e₁ with N₁ r₁, cases a with a0 n a', { cases m with m, { by_cases o₂ = 0; simp [opow_def, opow, e₁, h, r₁], have := mt repr_inj.1 h, rw zero_opow this }, { cases e₂ : split' o₂ with b' k, cases NF_repr_split' e₂ with _ r₂, by_cases m = 0; simp [opow_def, opow, e₁, h, r₁, e₂, r₂, -nat.cast_succ], rw [opow_add, opow_mul, opow_omega _ (nat_lt_omega _)], simpa using nat_cast_lt.2 (nat.succ_lt_succ $ pos_iff_ne_zero.2 h) } }, { haveI := N₁.fst, haveI := N₁.snd, cases N₁.of_dvd_omega (split_dvd e₁) with a00 ad, have al := split_add_lt e₁, have aa : repr (a' + of_nat m) = repr a' + m, {simp}, cases e₂ : split' o₂ with b' k, cases NF_repr_split' e₂ with _ r₂, simp [opow_def, opow, e₁, r₁, split_eq_scale_split' e₂], cases k with k; resetI, { simp [opow, r₂, opow_mul, repr_opow_aux₁ a00 al aa, add_assoc] }, { simp [succ_eq_add_one, opow, r₂, opow_add, opow_mul, mul_assoc, add_assoc], rw [repr_opow_aux₁ a00 al aa, scale_opow_aux], simp [opow_mul], rw [← ordinal.mul_add, ← add_assoc (ω ^ repr a0 * (n:ℕ))], congr' 1, rw [← opow_succ], exact (repr_opow_aux₂ _ ad a00 al _ _).2 } } end end onote /-- The type of normal ordinal notations. (It would have been nicer to define this right in the inductive type, but `NF o` requires `repr` which requires `onote`, so all these things would have to be defined at once, which messes up the VM representation.) -/ def nonote := {o : onote // o.NF} instance : decidable_eq nonote := by unfold nonote; apply_instance namespace nonote open onote instance NF (o : nonote) : NF o.1 := o.2 /-- Construct a `nonote` from an ordinal notation (and infer normality) -/ def mk (o : onote) [h : NF o] : nonote := ⟨o, h⟩ /-- The ordinal represented by an ordinal notation. (This function is noncomputable because ordinal arithmetic is noncomputable. In computational applications `nonote` can be used exclusively without reference to `ordinal`, but this function allows for correctness results to be stated.) -/ noncomputable def repr (o : nonote) : ordinal := o.1.repr instance : has_to_string nonote := ⟨λ x, x.1.to_string⟩ instance : has_repr nonote := ⟨λ x, x.1.repr'⟩ instance : preorder nonote := { le := λ x y, repr x ≤ repr y, lt := λ x y, repr x < repr y, le_refl := λ a, @le_refl ordinal _ _, le_trans := λ a b c, @le_trans ordinal _ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ } instance : has_zero nonote := ⟨⟨0, NF.zero⟩⟩ instance : inhabited nonote := ⟨0⟩ theorem wf : @well_founded nonote (<) := inv_image.wf repr ordinal.wf instance : has_well_founded nonote := ⟨(<), wf⟩ /-- Convert a natural number to an ordinal notation -/ def of_nat (n : ℕ) : nonote := ⟨of_nat n, ⟨⟨_, NF_below_of_nat _⟩⟩⟩ /-- Compare ordinal notations -/ def cmp (a b : nonote) : ordering := cmp a.1 b.1 theorem cmp_compares : ∀ a b : nonote, (cmp a b).compares a b | ⟨a, ha⟩ ⟨b, hb⟩ := begin resetI, dsimp [cmp], have := onote.cmp_compares a b, cases onote.cmp a b; try {exact this}, exact subtype.mk_eq_mk.2 this end instance : linear_order nonote := linear_order_of_compares cmp cmp_compares instance : is_well_order nonote (<) := ⟨wf⟩ /-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/ def below (a b : nonote) : Prop := NF_below a.1 (repr b) /-- The `oadd` pseudo-constructor for `nonote` -/ def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : below a e) : nonote := ⟨_, NF.oadd e.2 n h⟩ /-- This is a recursor-like theorem for `nonote` suggesting an inductive definition, which can't actually be defined this way due to conflicting dependencies. -/ @[elab_as_eliminator] def rec_on {C : nonote → Sort*} (o : nonote) (H0 : C 0) (H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o := begin cases o with o h, induction o with e n a IHe IHa, { exact H0 }, { exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) } end /-- Addition of ordinal notations -/ instance : has_add nonote := ⟨λ x y, mk (x.1 + y.1)⟩ theorem repr_add (a b) : repr (a + b) = repr a + repr b := onote.repr_add a.1 b.1 /-- Subtraction of ordinal notations -/ instance : has_sub nonote := ⟨λ x y, mk (x.1 - y.1)⟩ theorem repr_sub (a b) : repr (a - b) = repr a - repr b := onote.repr_sub a.1 b.1 /-- Multiplication of ordinal notations -/ instance : has_mul nonote := ⟨λ x y, mk (x.1 * y.1)⟩ theorem repr_mul (a b) : repr (a * b) = repr a * repr b := onote.repr_mul a.1 b.1 /-- Exponentiation of ordinal notations -/ def opow (x y : nonote) := mk (x.1.opow y.1) theorem repr_opow (a b) : repr (opow a b) = (repr a).opow (repr b) := onote.repr_opow a.1 b.1 end nonote
1a928b301c0169c4747add6cc822f0130639be2a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/finsupp_vector_space.lean
65d8906cc3aab85c654da82b88d2291fe1c7e0b4
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
8,546
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.mv_polynomial import linear_algebra.dimension import linear_algebra.direct_sum.finsupp import linear_algebra.finite_dimensional import linear_algebra.std_basis /-! # Linear structures on function with finite support `ι →₀ M` This file contains results on the `R`-module structure on functions of finite support from a type `ι` to an `R`-module `M`, in particular in the case that `R` is a field. Furthermore, it contains some facts about isomorphisms of vector spaces from equality of dimension as well as the cardinality of finite dimensional vector spaces. ## TODO Move the second half of this file to more appropriate other files. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule namespace finsupp section ring variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply (hf i).map h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end open linear_map submodule /-- The basis on `ι →₀ M` with basis vectors `λ ⟨i, x⟩, single i (b i x)`. -/ protected def basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) : basis (Σ i, φ i) R (ι →₀ M) := basis.of_repr { to_fun := λ g, { to_fun := λ ix, (b ix.1).repr (g ix.1) ix.2, support := g.support.sigma (λ i, ((b i).repr (g i)).support), mem_support_to_fun := λ ix, by { simp only [finset.mem_sigma, mem_support_iff, and_iff_right_iff_imp, ne.def], intros b hg, simpa [hg] using b } }, inv_fun := λ g, { to_fun := λ i, (b i).repr.symm (g.comap_domain _ (set.inj_on_of_injective sigma_mk_injective _)), support := g.support.image sigma.fst, mem_support_to_fun := λ i, by { rw [ne.def, ← (b i).repr.injective.eq_iff, (b i).repr.apply_symm_apply, ext_iff], simp only [exists_prop, linear_equiv.map_zero, comap_domain_apply, zero_apply, exists_and_distrib_right, mem_support_iff, exists_eq_right, sigma.exists, finset.mem_image, not_forall] } }, left_inv := λ g, by { ext i, rw ← (b i).repr.injective.eq_iff, ext x, simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] }, right_inv := λ g, by { ext ⟨i, x⟩, simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] }, map_add' := λ g h, by { ext ⟨i, x⟩, simp only [coe_mk, add_apply, linear_equiv.map_add] }, map_smul' := λ c h, by { ext ⟨i, x⟩, simp only [coe_mk, smul_apply, linear_equiv.map_smul] } } @[simp] lemma basis_repr {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) (g : ι →₀ M) (ix) : (finsupp.basis b).repr g ix = (b ix.1).repr (g ix.1) ix.2 := rfl @[simp] lemma coe_basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) : ⇑(finsupp.basis b) = λ (ix : Σ i, φ i), single ix.1 (b ix.1 ix.2) := funext $ λ ⟨i, x⟩, basis.apply_eq_iff.mpr $ begin ext ⟨j, y⟩, by_cases h : i = j, { cases h, simp only [basis_repr, single_eq_same, basis.repr_self, basis.finsupp.single_apply_left sigma_mk_injective] }, simp only [basis_repr, single_apply, h, false_and, if_false, linear_equiv.map_zero, zero_apply] end /-- The basis on `ι →₀ M` with basis vectors `λ i, single i 1`. -/ @[simps] protected def basis_single_one : basis ι R (ι →₀ R) := basis.of_repr (linear_equiv.refl _ _) @[simp] lemma coe_basis_single_one : (finsupp.basis_single_one : ι → (ι →₀ R)) = λ i, finsupp.single i 1 := funext $ λ i, basis.apply_eq_iff.mpr rfl end ring section comm_ring variables {R : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*} variables [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] /-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/ def basis.tensor_product (b : basis ι R M) (c : basis κ R N) : basis (ι × κ) R (tensor_product R M N) := finsupp.basis_single_one.map ((tensor_product.congr b.repr c.repr).trans $ (finsupp_tensor_finsupp _ _ _ _ _).trans $ lcongr (equiv.refl _) (tensor_product.lid R R)).symm end comm_ring section dim universes u v variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [module K V] lemma dim_eq : module.rank K (ι →₀ V) = cardinal.mk ι * module.rank K V := begin let bs := basis.of_vector_space K V, rw [← cardinal.lift_inj, cardinal.lift_mul, ← bs.mk_eq_dim, ← (finsupp.basis (λa:ι, bs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (single_injective.{u u} _), cardinal.sum_const] } end end dim end finsupp section module /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₁] [module K V₁] variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V'] [module K V'] open module lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (module.rank K V) = cardinal.lift.{w v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', let m := basis.of_vector_space K V, let m' := basis.of_vector_space K V', rw [←cardinal.lift_inj.1 m.mk_eq_dim, ←cardinal.lift_inj.1 m'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨(m.repr.trans (finsupp.dom_lcongr e)).trans m'.repr.symm⟩ end /-- Two `K`-vector spaces are equivalent if their dimension is the same. -/ def equiv_of_dim_eq_dim (h : module.rank K V₁ = module.rank K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end /-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/ def fin_dim_vectorspace_equiv (n : ℕ) (hn : (module.rank K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end end module section module universes u open module variables (K V : Type u) [field K] [add_comm_group V] [module K V] lemma cardinal_mk_eq_cardinal_mk_field_pow_dim [finite_dimensional K V] : cardinal.mk V = cardinal.mk K ^ module.rank K V := begin let s := basis.of_vector_space_index K V, let hs := basis.of_vector_space K V, calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨hs.repr.to_equiv⟩ ... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_finite_dimensional [fintype K] [finite_dimensional K V] : cardinal.mk V < cardinal.omega := begin rw cardinal_mk_eq_cardinal_mk_field_pow_dim K V, exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) (is_noetherian.dim_lt_omega K V), end end module
bffabb2a920684cd586bcf6547b58b84534b49d0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/tensor_algebra_auto.lean
3609839dda6494f0641fe1d9b2b5f8d715a65cc3
[]
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
7,457
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Adam Topaz. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.free_algebra import Mathlib.algebra.ring_quot import Mathlib.algebra.triv_sq_zero_ext import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # 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. -/ namespace tensor_algebra /-- An inductively defined relation on `pre R M` used to force the initial algebra structure on the associated quotient. -/ -- force `ι` to be linear inductive rel (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M] [semimodule R M] : free_algebra R M → free_algebra R M → Prop where | add : ∀ {a b : M}, rel R M (free_algebra.ι R (a + b)) (free_algebra.ι R a + free_algebra.ι R b) | smul : ∀ {r : R} {a : M}, rel R M (free_algebra.ι R (r • a)) (coe_fn (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`. -/ def tensor_algebra (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M] [semimodule R M] := ring_quot sorry namespace tensor_algebra protected instance ring (M : Type u_2) [add_comm_monoid M] {S : Type u_1} [comm_ring S] [semimodule S M] : ring (tensor_algebra S M) := ring_quot.ring (rel S M) /-- The canonical linear map `M →ₗ[R] tensor_algebra R M`. -/ def ι (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : linear_map R M (tensor_algebra R M) := linear_map.mk (fun (m : M) => coe_fn (ring_quot.mk_alg_hom R (rel R M)) (free_algebra.ι R m)) sorry sorry theorem ring_quot_mk_alg_hom_free_algebra_ι_eq_ι (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] (m : M) : coe_fn (ring_quot.mk_alg_hom R (rel R M)) (free_algebra.ι R m) = coe_fn (ι 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`. -/ def lift (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] : linear_map R M A ≃ alg_hom R (tensor_algebra R M) A := equiv.mk (⇑(ring_quot.lift_alg_hom R) ∘ fun (f : linear_map R M A) => { val := coe_fn (free_algebra.lift R) ⇑f, property := sorry }) (fun (F : alg_hom R (tensor_algebra R M) A) => linear_map.comp (alg_hom.to_linear_map F) (ι R)) sorry sorry @[simp] theorem ι_comp_lift {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A) : linear_map.comp (alg_hom.to_linear_map (coe_fn (lift R) f)) (ι R) = f := equiv.symm_apply_apply (lift R) f @[simp] theorem lift_ι_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A) (x : M) : coe_fn (coe_fn (lift R) f) (coe_fn (ι R) x) = coe_fn f x := id (Eq.refl (coe_fn f x)) @[simp] theorem lift_unique {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A) (g : alg_hom R (tensor_algebra R M) A) : linear_map.comp (alg_hom.to_linear_map g) (ι R) = f ↔ g = coe_fn (lift R) f := equiv.symm_apply_eq (lift R) -- 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. @[simp] theorem lift_comp_ι {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (g : alg_hom R (tensor_algebra R M) A) : coe_fn (lift R) (linear_map.comp (alg_hom.to_linear_map g) (ι R)) = g := sorry /-- See note [partially-applied ext lemmas]. -/ theorem hom_ext {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] {f : alg_hom R (tensor_algebra R M) A} {g : alg_hom R (tensor_algebra R M) A} (w : linear_map.comp (alg_hom.to_linear_map f) (ι R) = linear_map.comp (alg_hom.to_linear_map g) (ι R)) : f = g := sorry /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : alg_hom R (tensor_algebra R M) R := coe_fn (lift R) 0 theorem algebra_map_left_inverse {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : function.left_inverse ⇑algebra_map_inv ⇑(algebra_map R (tensor_algebra R M)) := sorry /-- The left-inverse of `ι`. As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable algebra structure. -/ def ι_inv {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : linear_map R (tensor_algebra R M) M := linear_map.comp (triv_sq_zero_ext.snd_hom R M) (alg_hom.to_linear_map (coe_fn (lift R) (triv_sq_zero_ext.inr_hom R M))) theorem ι_left_inverse {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : function.left_inverse ⇑ι_inv ⇑(ι R) := sorry end tensor_algebra namespace free_algebra /-- 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 {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : alg_hom R (free_algebra R M) (tensor_algebra R M) := coe_fn (lift R) ⇑(tensor_algebra.ι R) @[simp] theorem to_tensor_ι {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] (m : M) : coe_fn to_tensor (ι R m) = coe_fn (tensor_algebra.ι R) m := sorry end Mathlib
ceba584a003d1c473ecbfdff4a7a3aff4d297cdc
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/ac_expr.lean
ce702ccf28697ae4eb91a800cc77a658bbd85135
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
5,286
lean
import Std inductive Expr where | var (i : Nat) | op (lhs rhs : Expr) deriving Inhabited, Repr def List.getIdx : List α → Nat → α → α | [], i, u => u | a::as, 0, u => a | a::as, i+1, u => getIdx as i u structure Context (α : Type u) where op : α → α → α assoc : (a b c : α) → op (op a b) c = op a (op b c) comm : (a b : α) → op a b = op b a vars : List α someVal : α theorem Context.left_comm (ctx : Context α) (a b c : α) : ctx.op a (ctx.op b c) = ctx.op b (ctx.op a c) := by rw [← ctx.assoc, ctx.comm a b, ctx.assoc] def Expr.denote (ctx : Context α) : Expr → α | Expr.op a b => ctx.op (denote ctx a) (denote ctx b) | Expr.var i => ctx.vars.getIdx i ctx.someVal theorem Expr.denote_op (ctx : Context α) (a b : Expr) : denote ctx (Expr.op a b) = ctx.op (denote ctx a) (denote ctx b) := rfl def Expr.concat : Expr → Expr → Expr | Expr.op a b, c => Expr.op a (concat b c) | Expr.var i, c => Expr.op (Expr.var i) c theorem Expr.denote_concat (ctx : Context α) (a b : Expr) : denote ctx (concat a b) = denote ctx (Expr.op a b) := by induction a with | var i => rfl | op _ _ _ ih => simp [denote, ih, ctx.assoc] def Expr.flat : Expr → Expr | Expr.op a b => concat (flat a) (flat b) | Expr.var i => Expr.var i theorem Expr.denote_flat (ctx : Context α) (e : Expr) : denote ctx (flat e) = denote ctx e := by induction e with | var i => rfl | op a b ih₁ ih₂ => simp [flat, denote, denote_concat, ih₁, ih₂] theorem Expr.eq_of_flat (ctx : Context α) (a b : Expr) (h : flat a = flat b) : denote ctx a = denote ctx b := by have h := congrArg (denote ctx) h simp [denote_flat] at h assumption def Expr.length : Expr → Nat | op a b => 1 + b.length | _ => 1 def Expr.sort (e : Expr) : Expr := loop e.length e where loop : Nat → Expr → Expr | fuel+1, Expr.op a e => let (e₁, e₂) := swap a e Expr.op e₁ (loop fuel e₂) | _, e => e swap : Expr → Expr → Expr × Expr | Expr.var i, Expr.op (Expr.var j) e => if i > j then let (e₁, e₂) := swap (Expr.var j) e (e₁, Expr.op (Expr.var i) e₂) else let (e₁, e₂) := swap (Expr.var i) e (e₁, Expr.op (Expr.var j) e₂) | Expr.var i, Expr.var j => if i > j then (Expr.var j, Expr.var i) else (Expr.var i, Expr.var j) | e₁, e₂ => (e₁, e₂) theorem Expr.denote_sort (ctx : Context α) (e : Expr) : denote ctx (sort e) = denote ctx e := by apply denote_loop where denote_loop (n : Nat) (e : Expr) : denote ctx (sort.loop n e) = denote ctx e := by induction n generalizing e with | zero => rfl | succ n ih => match e with | var _ => rfl | op a b => simp [denote, sort.loop] match h:sort.swap a b with | (r₁, r₂) => have hs := denote_swap a b rw [h] at hs simp [denote] at hs simp [denote, ih] assumption denote_swap (e₁ e₂ : Expr) : denote ctx (Expr.op (sort.swap e₁ e₂).1 (sort.swap e₁ e₂).2) = denote ctx (Expr.op e₁ e₂) := by induction e₂ generalizing e₁ with | op a b ih' ih => clear ih' cases e₁ with | var i => cases a with | var j => byCases h : i > j focus simp [sort.swap, h] match h:sort.swap (var j) b with | (r₁, r₂) => simp; rw [denote_op (a := var i), ← ih]; simp [h, denote]; rw [Context.left_comm] focus simp [sort.swap, h] match h:sort.swap (var i) b with | (r₁, r₂) => simp rw [denote_op (a := var i), denote_op (a := var j), Context.left_comm, ← denote_op (a := var i), ← ih] simp [h, denote] rw [Context.left_comm] | _ => rfl | _ => rfl | var j => cases e₁ with | var i => byCases h : i > j focus simp [sort.swap, h, denote, Context.comm] focus simp [sort.swap, h] | _ => rfl theorem Expr.eq_of_sort_flat (ctx : Context α) (a b : Expr) (h : sort (flat a) = sort (flat b)) : denote ctx a = denote ctx b := by have h := congrArg (denote ctx) h simp [denote_flat, denote_sort] at h assumption theorem ex₁ (x₁ x₂ x₃ x₄ : Nat) : (x₁ + x₂) + (x₃ + x₄) = x₁ + x₂ + x₃ + x₄ := Expr.eq_of_flat { op := Nat.add assoc := Nat.add_assoc comm := Nat.add_comm vars := [x₁, x₂, x₃, x₄], someVal := x₁ } (Expr.op (Expr.op (Expr.var 0) (Expr.var 1)) (Expr.op (Expr.var 2) (Expr.var 3))) (Expr.op (Expr.op (Expr.op (Expr.var 0) (Expr.var 1)) (Expr.var 2)) (Expr.var 3)) rfl theorem ex₂ (x₁ x₂ x₃ x₄ : Nat) : (x₁ + x₂) + (x₃ + x₄) = x₃ + x₁ + x₂ + x₄ := Expr.eq_of_sort_flat { op := Nat.add assoc := Nat.add_assoc comm := Nat.add_comm vars := [x₁, x₂, x₃, x₄], someVal := x₁ } (Expr.op (Expr.op (Expr.var 0) (Expr.var 1)) (Expr.op (Expr.var 2) (Expr.var 3))) (Expr.op (Expr.op (Expr.op (Expr.var 2) (Expr.var 0)) (Expr.var 1)) (Expr.var 3)) rfl #print ex₂
3f4ee1d0bd269c76f1677c4c91b00fd7ee64f9fa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/lint_simp_nf.lean
e6bb48a4347c19de4b8f5e99140480d8a34014cd
[ "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
933
lean
import tactic.lint def f : ℕ → ℕ := default def c : ℕ := default def d : ℕ := default @[simp] lemma c_eq_d : c = d := rfl -- The following lemma never applies when using simp, because c is first rewritten to d @[simp] lemma f_c : f c = 0 := rfl example : f c = 0 := begin simp, guard_target f d = 0, -- does not apply f_c refl end open tactic run_cmd do decl ← get_decl ``f_c, res ← linter.simp_nf.test decl, -- linter complains guard $ res.is_some -- also works with `coe_to_fun` structure morphism := (f : ℕ → ℕ) instance : has_coe_to_fun morphism (λ _, ℕ → ℕ):= ⟨morphism.f⟩ def h : morphism := ⟨default⟩ -- Also never applies @[simp] lemma h_c : h c = 0 := rfl example : h c = 0 := begin simp, guard_target h d = 0, -- does not apply h_c refl end open tactic run_cmd do decl ← get_decl ``h_c, res ← linter.simp_nf.test decl, -- linter complains guard $ res.is_some
b8b8e6e10b3291f23281fb5ee5ed912f3b1251ad
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/category_theory/isomorphism.lean
deb0fb3ffc56d83861a7c818e28e5779057c31c1
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
6,917
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 import category_theory.functor universes u v namespace category_theory structure iso {C : Type u} [category.{u v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) -- We restate the hom_inv_id' and inv_hom_id' lemmas below. infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 variables {X Y Z : C} namespace iso instance : has_coe (iso.{u v} X Y) (X ⟶ Y) := { coe := iso.hom } @[extensionality] lemma ext (α β : X ≅ Y) (w : α.hom = β.hom) : α = β := begin induction α with f g wα1 wα2, induction β with h k wβ1 wβ2, dsimp at *, have p : g = k, begin induction w, rw [← category.id_comp C k, ←wα2, category.assoc, wβ1, category.comp_id] end, induction p, induction w, refl end @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } -- These are the restated lemmas for iso.hom_inv_id' and iso.inv_hom_id' @[simp] lemma hom_inv_id (α : X ≅ Y) : (α : X ⟶ Y) ≫ (α.symm : Y ⟶ X) = 𝟙 X := begin unfold_coes, unfold symm, have p := α.hom_inv_id', dsimp at p, rw p end @[simp] lemma inv_hom_id (α : X ≅ Y) : (α.symm : Y ⟶ X) ≫ (α : X ⟶ Y) = 𝟙 Y := begin unfold_coes, unfold symm, have p := iso.inv_hom_id', dsimp at p, rw p end -- We rewrite the projections `.hom` and `.inv` into coercions. @[simp] lemma hom_eq_coe (α : X ≅ Y) : α.hom = (α : X ⟶ Y) := rfl @[simp] lemma inv_eq_coe (α : X ≅ Y) : α.inv = (α.symm : Y ⟶ X) := rfl @[refl] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } @[simp] lemma refl_coe (X : C) : ((iso.refl X) : X ⟶ X) = 𝟙 X := rfl @[simp] lemma refl_symm_coe (X : C) : ((iso.refl X).symm : X ⟶ X) = 𝟙 X := rfl @[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := (α : X ⟶ Y) ≫ (β : Y ⟶ Z), inv := (β.symm : Z ⟶ Y) ≫ (α.symm : Y ⟶ X), hom_inv_id' := begin /- `obviously'` says: -/ erw [category.assoc], conv { to_lhs, congr, skip, rw ← category.assoc }, rw iso.hom_inv_id, rw category.id_comp, rw iso.hom_inv_id end, inv_hom_id' := begin /- `obviously'` says: -/ erw [category.assoc], conv { to_lhs, congr, skip, rw ← category.assoc }, rw iso.inv_hom_id, rw category.id_comp, rw iso.inv_hom_id end } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_coe (α : X ≅ Y) (β : Y ≅ Z) : ((α ≪≫ β) : X ⟶ Z) = (α : X ⟶ Y) ≫ (β : Y ⟶ Z) := rfl @[simp] lemma trans_symm_coe (α : X ≅ Y) (β : Y ≅ Z) : ((α ≪≫ β).symm : Z ⟶ X) = (β.symm : Z ⟶ Y) ≫ (α.symm : Y ⟶ X) := rfl @[simp] lemma refl_symm (X : C) : ((iso.refl X).symm : X ⟶ X) = 𝟙 X := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : ((α ≪≫ β).symm : Z ⟶ X) = (β.symm : Z ⟶ Y) ≫ (α.symm : Y ⟶ X) := rfl end iso /-- `is_iso` typeclass expressing that a morphism is invertible. This contains the data of the inverse, but is a subsingleton type. -/ class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id' : f ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ f = 𝟙 Y . obviously) def inv (f : X ⟶ Y) [is_iso f] := is_iso.inv f namespace is_iso instance (f : X ⟶ Y) : subsingleton (is_iso f) := ⟨ λ a b, begin cases a, cases b, dsimp at *, congr, rw [← category.id_comp _ a_inv, ← b_inv_hom_id', category.assoc, a_hom_inv_id', category.comp_id] end ⟩ @[simp] def hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ inv f = 𝟙 X := is_iso.hom_inv_id' f @[simp] def inv_hom_id (f : X ⟶ Y) [is_iso f] : inv f ≫ f = 𝟙 Y := is_iso.inv_hom_id' f instance (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X } instance of_iso (f : X ≅ Y) : is_iso (f : X ⟶ Y) := { inv := (f.symm : Y ⟶ X) } instance of_iso_inverse (f : X ≅ Y) : is_iso (f.symm : Y ⟶ X) := { inv := (f : X ⟶ Y) } end is_iso namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [𝒟 : category.{u₂ v₂} D] include 𝒟 def on_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F X) ≅ (F Y) := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by erw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by erw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma on_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : ((F.on_iso i) : F X ⟶ F Y) = F.map (i : X ⟶ Y) := rfl @[simp] lemma on_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : ((F.on_iso i).symm : F Y ⟶ F X) = F.map (i.symm : Y ⟶ X) := rfl instance (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := { inv := F.map (inv f), hom_inv_id' := begin rw ← F.map_comp, erw is_iso.hom_inv_id, rw map_id, end, inv_hom_id' := begin rw ← F.map_comp, erw is_iso.inv_hom_id, rw map_id, end } end functor instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := begin -- This is an interesting test case for better rewrite automation. intros, rw [←category.id_comp C g, ←category.id_comp C h], rw [← is_iso.inv_hom_id f], erw [category.assoc, w, category.assoc], end } instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := begin intros, rw [←category.comp_id C g, ←category.comp_id C h], rw [← is_iso.hom_inv_id f], erw [←category.assoc, w, ←category.assoc] end } def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y := by rw p @[simp] lemma eq_to_iso_refl (X : C) (p : X = X) : eq_to_iso p = (iso.refl X) := rfl @[simp] lemma eq_to_iso_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : (eq_to_iso p) ≪≫ (eq_to_iso q) = eq_to_iso (p.trans q) := begin /- obviously' says: -/ ext, induction q, induction p, dsimp at *, simp at * end namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 @[simp] lemma eq_to_iso (F : C ⥤ D) {X Y : C} (p : X = Y) : F.on_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) := begin /- obviously says: -/ ext1, induction p, dsimp at *, simp at * end end functor def Aut (X : C) := X ≅ X attribute [extensionality Aut] iso.ext instance {X : C} : group (Aut X) := by refine { one := iso.refl X, inv := iso.symm, mul := iso.trans, .. } ; obviously end category_theory
5910d159f09a024a405a49b0d8c56352612d79d0
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/atomic2.lean
e994136f210a9e4c532850977651fd26dd04b3a6
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
84
lean
notation `foo` := Type.{1} constant f : Type* → Type* check foo → f foo → foo
a2c4ab3f8c7524cec1766d4850f153443044c3fd
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/ScopedEnvExtension.lean
f1ad4da4dbbf0086c3dc8734bf307cad6f42891f
[ "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
8,208
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.Environment import Lean.Data.NameTrie import Lean.Attributes namespace Lean namespace ScopedEnvExtension inductive Entry (α : Type) where | global : α → Entry α | «scoped» : Name → α → Entry α structure State (σ : Type) where state : σ activeScopes : NameSet := {} structure ScopedEntries (β : Type) where map : SMap Name (Std.PArray β) := {} deriving Inhabited structure StateStack (α : Type) (β : Type) (σ : Type) where stateStack : List (State σ) := {} scopedEntries : ScopedEntries β := {} newEntries : List (Entry α) := [] deriving Inhabited structure Descr (α : Type) (β : Type) (σ : Type) where name : Name mkInitial : IO σ ofOLeanEntry : σ → α → ImportM β toOLeanEntry : β → α addEntry : σ → β → σ finalizeImport : σ → σ := id instance [Inhabited α] : Inhabited (Descr α β σ) where default := { name := arbitrary mkInitial := arbitrary ofOLeanEntry := arbitrary toOLeanEntry := arbitrary addEntry := fun s _ => s } def mkInitial (descr : Descr α β σ) : IO (StateStack α β σ) := return { stateStack := [ { state := (← descr.mkInitial ) } ] } def ScopedEntries.insert (scopedEntries : ScopedEntries β) (ns : Name) (b : β) : ScopedEntries β := match scopedEntries.map.find? ns with | none => { map := scopedEntries.map.insert ns <| ({} : Std.PArray β).push b } | some bs => { map := scopedEntries.map.insert ns <| bs.push b } def addImportedFn (descr : Descr α β σ) (as : Array (Array (Entry α))) : ImportM (StateStack α β σ) := do let mut s ← descr.mkInitial let mut scopedEntries : ScopedEntries β := {} for a in as do for e in a do match e with | Entry.global a => let b ← descr.ofOLeanEntry s a s := descr.addEntry s b | Entry.scoped ns a => let b ← descr.ofOLeanEntry s a scopedEntries := scopedEntries.insert ns b s := descr.finalizeImport s return { stateStack := [ { state := s } ], scopedEntries := scopedEntries } def addEntryFn (descr : Descr α β σ) (s : StateStack α β σ) (e : Entry β) : StateStack α β σ := match s with | { stateStack := stateStack, scopedEntries := scopedEntries, newEntries := newEntries } => match e with | Entry.global b => { scopedEntries := scopedEntries newEntries := (Entry.global (descr.toOLeanEntry b)) :: newEntries stateStack := stateStack.map fun s => { s with state := descr.addEntry s.state b } } | Entry.«scoped» ns b => { scopedEntries := scopedEntries.insert ns b newEntries := (Entry.«scoped» ns (descr.toOLeanEntry b)) :: newEntries stateStack := stateStack.map fun s => if s.activeScopes.contains ns then { s with state := descr.addEntry s.state b } else s } def exportEntriesFn (s : StateStack α β σ) : Array (Entry α) := s.newEntries.toArray.reverse end ScopedEnvExtension open ScopedEnvExtension structure ScopedEnvExtension (α : Type) (β : Type) (σ : Type) where descr : Descr α β σ ext : PersistentEnvExtension (Entry α) (Entry β) (StateStack α β σ) deriving Inhabited builtin_initialize scopedEnvExtensionsRef : IO.Ref (Array (ScopedEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] unsafe def registerScopedEnvExtensionUnsafe (descr : Descr α β σ) : IO (ScopedEnvExtension α β σ) := do let ext ← registerPersistentEnvExtension { name := descr.name mkInitial := mkInitial descr addImportedFn := addImportedFn descr addEntryFn := addEntryFn descr exportEntriesFn := exportEntriesFn statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length } let ext := { descr := descr, ext := ext : ScopedEnvExtension α β σ } scopedEnvExtensionsRef.modify fun exts => exts.push (unsafeCast ext) return ext @[implementedBy registerScopedEnvExtensionUnsafe] constant registerScopedEnvExtension (descr : Descr α β σ) : IO (ScopedEnvExtension α β σ) def ScopedEnvExtension.pushScope (ext : ScopedEnvExtension α β σ) (env : Environment) : Environment := let s := ext.ext.getState env match s.stateStack with | [] => env | state :: stack => ext.ext.setState env { s with stateStack := state :: state :: stack } def ScopedEnvExtension.popScope (ext : ScopedEnvExtension α β σ) (env : Environment) : Environment := let s := ext.ext.getState env match s.stateStack with | state₁ :: state₂ :: stack => ext.ext.setState env { s with stateStack := state₂ :: stack } | _ => env def ScopedEnvExtension.addEntry (ext : ScopedEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.ext.addEntry env (Entry.global b) def ScopedEnvExtension.addScopedEntry (ext : ScopedEnvExtension α β σ) (env : Environment) (namespaceName : Name) (b : β) : Environment := ext.ext.addEntry env (Entry.«scoped» namespaceName b) def ScopedEnvExtension.addLocalEntry (ext : ScopedEnvExtension α β σ) (env : Environment) (b : β) : Environment := let s := ext.ext.getState env match s.stateStack with | [] => env | top :: states => let top := { top with state := ext.descr.addEntry top.state b } ext.ext.setState env { s with stateStack := top :: states } def ScopedEnvExtension.add [Monad m] [MonadResolveName m] [MonadEnv m] (ext : ScopedEnvExtension α β σ) (b : β) (kind := AttributeKind.global) : m Unit := do match kind with | AttributeKind.global => modifyEnv (ext.addEntry · b) | AttributeKind.local => modifyEnv (ext.addLocalEntry · b) | AttributeKind.scoped => modifyEnv (ext.addScopedEntry · (← getCurrNamespace) b) def ScopedEnvExtension.getState [Inhabited σ] (ext : ScopedEnvExtension α β σ) (env : Environment) : σ := match ext.ext.getState env |>.stateStack with | top :: _ => top.state | _ => unreachable! def ScopedEnvExtension.activateScoped (ext : ScopedEnvExtension α β σ) (env : Environment) (namespaceName : Name) : Environment := let s := ext.ext.getState env match s.stateStack with | top :: stack => if top.activeScopes.contains namespaceName then env else let activeScopes := top.activeScopes.insert namespaceName let top := match s.scopedEntries.map.find? namespaceName with | none => { top with activeScopes := activeScopes } | some bs => do let mut state := top.state for b in bs do state := ext.descr.addEntry state b { state := state, activeScopes := activeScopes } ext.ext.setState env { s with stateStack := top :: stack } | _ => env def pushScope [Monad m] [MonadEnv m] [MonadLiftT (ST IO.RealWorld) m] : m Unit := do for ext in (← scopedEnvExtensionsRef.get) do modifyEnv ext.pushScope def popScope [Monad m] [MonadEnv m] [MonadLiftT (ST IO.RealWorld) m] : m Unit := do for ext in (← scopedEnvExtensionsRef.get) do modifyEnv ext.popScope def activateScoped [Monad m] [MonadEnv m] [MonadLiftT (ST IO.RealWorld) m] (namespaceName : Name) : m Unit := do for ext in (← scopedEnvExtensionsRef.get) do modifyEnv (ext.activateScoped · namespaceName) abbrev SimpleScopedEnvExtension (α : Type) (σ : Type) := ScopedEnvExtension α α σ structure SimpleScopedEnvExtension.Descr (α : Type) (σ : Type) where name : Name addEntry : σ → α → σ initial : σ finalizeImport : σ → σ := id def registerSimpleScopedEnvExtension (descr : SimpleScopedEnvExtension.Descr α σ) : IO (SimpleScopedEnvExtension α σ) := do registerScopedEnvExtension { name := descr.name mkInitial := return descr.initial addEntry := descr.addEntry toOLeanEntry := id ofOLeanEntry := fun s a => return a finalizeImport := descr.finalizeImport } end Lean
4a0a806837b6942888f8b1352581fa96b0b40c2a
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/inner_product_space/pi_L2.lean
179a9d4ef836a39e8de99948bb32897fc17e0a5e
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,663
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth -/ import analysis.inner_product_space.projection import analysis.normed_space.pi_Lp /-! # `L²` inner product space structure on finite products of inner product spaces The `L²` norm on a finite product of inner product spaces is compatible with an inner product $$ \langle x, y\rangle = \sum \langle x_i, y_i \rangle. $$ This is recorded in this file as an inner product space instance on `pi_Lp 2`. ## Main definitions - `euclidean_space 𝕜 n`: defined to be `pi_Lp 2 _ (n → 𝕜)` for any `fintype n`, i.e., the space from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably that it is a finite-dimensional inner product space). - `basis.isometry_euclidean_of_orthonormal`: provides the isometry to Euclidean space from a given finite-dimensional inner product space, induced by a basis of the space. - `linear_isometry_equiv.of_inner_product_space`: provides an arbitrary isometry to Euclidean space from a given finite-dimensional inner product space, induced by choosing an arbitrary basis. - `complex.isometry_euclidean`: standard isometry from `ℂ` to `euclidean_space ℝ (fin 2)` -/ open real set filter is_R_or_C open_locale big_operators uniformity topological_space nnreal ennreal noncomputable theory variables {ι : Type*} variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ j (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw conj.map_sum, apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } @[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 one_le_two f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ := rfl lemma pi_Lp.norm_eq_of_L2 {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x : pi_Lp 2 one_le_two f) : ∥x∥ = sqrt (∑ (i : ι), ∥x i∥ ^ 2) := by { rw [pi_Lp.norm_eq_of_nat 2]; simp [sqrt_eq_rpow] } /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜) lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ (i : n), ∥x i∥ ^ 2) := pi_Lp.norm_eq_of_L2 x section local attribute [reducible] pi_Lp variables [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma finrank_euclidean_space : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma finrank_euclidean_space_fin {n : ℕ} : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp /-- An orthonormal basis on a fintype `ι` for an inner product space induces an isometry with `euclidean_space 𝕜 ι`. -/ def basis.isometry_euclidean_of_orthonormal (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 ι) := v.equiv_fun.isometry_of_inner begin intros x y, let p : euclidean_space 𝕜 ι := v.equiv_fun x, let q : euclidean_space 𝕜 ι := v.equiv_fun y, have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫, { simp [sum_inner, inner_smul_left, hv.inner_right_fintype] }, convert key, { rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] }, { rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] } end end /-- `ℂ` is isometric to `ℝ²` with the Euclidean inner product. -/ def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) := complex.basis_one_I.isometry_euclidean_of_orthonormal begin rw orthonormal_iff_ite, intros i, fin_cases i; intros j; fin_cases j; simp [real_inner_eq_re_inner] end @[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) : complex.isometry_euclidean.symm x = (x 0) + (x 1) * I := begin convert complex.basis_one_I.equiv_fun_symm_apply x, { simpa }, { simp }, end lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) : ↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z := by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z), complex.isometry_euclidean.symm_apply_apply z] @[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) : complex.isometry_euclidean z 0 = z.re := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } @[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) : complex.isometry_euclidean z 1 = z.im := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } open finite_dimensional /-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space, there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.of_inner_product_space [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := (fin_orthonormal_basis hn).isometry_euclidean_of_orthonormal (fin_orthonormal_basis_orthonormal hn) local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product space, there exists an isometry from the orthogonal complement of a nonzero singleton to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.from_orthogonal_span_singleton (n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : (𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := linear_isometry_equiv.of_inner_product_space (finrank_orthogonal_span_singleton hv)
62f97549c3ebad50a04f8abe8c3b0fc324b3303f
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/tactic/norm_num.lean
d57278a583c8dbcdb7ae696330fb4aa25c1fd372
[ "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
18,354
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro Evaluating arithmetic expressions including *, +, -, ^, ≤ -/ import algebra.group_power data.rat tactic.interactive data.nat.prime universes u v w namespace expr protected meta def to_pos_rat : expr → option ℚ | `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, some (rat.mk m n) | e := do n ← e.to_nat, return (rat.of_int n) protected meta def to_rat : expr → option ℚ | `(has_neg.neg %%e) := do q ← e.to_pos_rat, some (-q) | e := e.to_pos_rat protected meta def 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] end expr namespace tactic meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace norm_num variable {α : Type u} theorem bit0_zero [add_group α] : bit0 (0 : α) = 0 := add_zero _ theorem bit1_zero [add_group α] [has_one α] : bit1 (0 : α) = 1 := by rw [bit1, bit0_zero, zero_add] lemma pow_bit0_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit0 b = t * t := by simp [pow_bit0, h] lemma pow_bit1_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit1 b = t * t * a := by simp [pow_bit1, h] lemma lt_add_of_pos_helper [ordered_cancel_comm_monoid α] (a b c : α) (h : a + b = c) (h₂ : 0 < b) : a < c := h ▸ (lt_add_iff_pos_right _).2 h₂ lemma nat_div_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a / b = q := by rw [← h, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a % b = r := by rw [← h, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] meta def eval_pow (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := match m with | `(nat.has_pow) := mk_app ``nat.pow [e₁, e₂] >>= eval_pow | `(@monoid.has_pow %%α %%m) := mk_app ``monoid.pow [e₁, e₂] >>= eval_pow | _ := failed end | `(monoid.pow %%e₁ 0) := do p ← mk_app ``pow_zero [e₁], a ← infer_type e₁, o ← mk_app ``has_one.one [a], return (o, p) | `(monoid.pow %%e₁ 1) := do p ← mk_app ``pow_one [e₁], return (e₁, p) | `(monoid.pow %%e₁ (bit0 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit0_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e'), return (e'', p') | `(monoid.pow %%e₁ (bit1 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit1_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e' * %%e₁), return (e'', p') | `(nat.pow %%e₁ %%e₂) := do p₁ ← mk_app ``nat.pow_eq_pow [e₁, e₂], e ← mk_app ``monoid.pow [e₁, e₂], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := failed meta def prove_pos : instance_cache → expr → tactic (instance_cache × expr) | c `(has_one.one _) := do (c, p) ← c.mk_app ``zero_lt_one [], return (c, p) | c `(bit0 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit0_pos [e, p], return (c, p) | c `(bit1 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit1_pos' [e, p], return (c, p) | c `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos c e₁, (c, p₂) ← prove_pos c e₂, (c, p) ← c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂], return (c, p) | c e := failed meta def prove_lt (simp : expr → tactic (expr × expr)) : instance_cache → expr → expr → tactic (instance_cache × expr) | c `(- %%e₁) `(- %%e₂) := do (c, p) ← prove_lt c e₁ e₂, (c, p) ← c.mk_app ``neg_lt_neg [e₁, e₂, p], return (c, p) | c `(- %%e₁) `(has_zero.zero _) := do (c, p) ← prove_pos c e₁, (c, p) ← c.mk_app ``neg_neg_of_pos [e₁, p], return (c, p) | c `(- %%e₁) e₂ := do (c, p₁) ← prove_pos c e₁, (c, me₁) ← c.mk_app ``has_neg.neg [e₁], (c, p₁) ← c.mk_app ``neg_neg_of_pos [e₁, p₁], (c, p₂) ← prove_pos c e₂, (c, z) ← c.mk_app ``has_zero.zero [], (c, p) ← c.mk_app ``lt_trans [me₁, z, e₂, p₁, p₂], return (c, p) | c `(has_zero.zero _) e₂ := prove_pos c e₂ | c e₁ e₂ := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, d ← expr.of_rat c.α (n₂ - n₁), (c, e₃) ← c.mk_app ``has_add.add [e₁, d], (e₂', p) ← norm_num e₃, guard (e₂' =ₐ e₂), (c, p') ← prove_pos c d, (c, p) ← c.mk_app ``norm_num.lt_add_of_pos_helper [e₁, d, e₂, p, p'], return (c, p) private meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `true <*> mk_app ``eq_true_intro [p] private meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `false <*> mk_app ``eq_false_intro [p] meta def eval_ineq (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt simp c e₁ e₂, true_intro p else do (c, p) ← if n₁ = n₂ then c.mk_app ``lt_irrefl [e₁] else (do (c, p') ← prove_lt simp c e₂ e₁, c.mk_app ``not_lt_of_gt [e₁, e₂, p']), false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (c, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else (do (c, p') ← prove_lt simp c e₁ e₂, c.mk_app ``le_of_lt [e₁, e₂, p']), true_intro p else do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (c, p) ← prove_lt simp c e₁ e₂, (c, p) ← c.mk_app ``ne_of_lt [e₁, e₂, p], false_intro p else if n₂ < n₁ then do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``ne_of_gt [e₁, e₂, p], false_intro p else mk_eq_refl e₁ >>= true_intro | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= simp | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= simp | `(%%e₁ ≠ %%e₂) := do e ← mk_app ``eq [e₁, e₂], mk_app ``not [e] >>= simp | _ := failed meta def eval_div_ext (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(has_inv.inv %%e) := do c ← infer_type e >>= mk_instance_cache, (c, p₁) ← c.mk_app ``inv_eq_one_div [e], (c, o) ← c.mk_app ``has_one.one [], (c, e') ← c.mk_app ``has_div.div [o, e], (do (e'', p₂) ← simp e', p ← mk_eq_trans p₁ p₂, return (e'', p)) <|> return (e', p₁) | `(%%e₁ / %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_div_helper [e₁, e₂, q, r, p, p'], return (q, p) | `(int) := match e₂ with | `(- %%e₂') := do (c, p₁) ← c.mk_app ``int.div_neg [e₁, e₂'], (c, e) ← c.mk_app ``has_div.div [e₁, e₂'], (c, e) ← c.mk_app ``has_neg.neg [e], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_div_helper [e₁, e₂, q, r, p, p₁, p₂], return (q, p) end | _ := failed end | `(%%e₁ % %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_mod_helper [e₁, e₂, q, r, p, p'], return (r, p) | `(int) := match e₂ with | `(- %%e₂') := do let p₁ := (expr.const ``int.mod_neg []).mk_app [e₁, e₂'], (c, e) ← c.mk_app ``has_mod.mod [e₁, e₂'], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_mod_helper [e₁, e₂, q, r, p, p₁, p₂], return (r, p) end | _ := failed end | `(%%e₁ ∣ %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, n ← match α with | `(nat) := return ``nat.dvd_iff_mod_eq_zero | `(int) := return ``int.dvd_iff_mod_eq_zero | _ := failed end, p₁ ← mk_app ``propext [@expr.const tt n [] e₁ e₂], (e', p₂) ← simp `(%%e₂ % %%e₁ = 0), p' ← mk_eq_trans p₁ p₂, return (e', p') | _ := failed lemma not_prime_helper (a b n : ℕ) (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ nat.prime n := by rw ← h; exact nat.not_prime_mul h₁ h₂ lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := nat.pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) dec_trivial lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' : ℕ) (e : k + 1 = k') (nd : bit1 k ∣ bit1 n = false) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw [eq_false, ← e₁] at nd, exact nd (nat.min_fac_dvd _) end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 k ∣ bit1 n = true) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw eq_true at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end meta def prove_non_prime (simp : expr → tactic (expr × expr)) (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (e', p) ← mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, guard (e' =ₐ e), (c, p₂) ← prove_lt simp c `(1) e₂, return $ (expr.const ``not_prime_helper []).mk_app [e₁, e₂, e, p, p₁, p₂] meta def prove_min_fac (simp : expr → tactic (expr × expr)) (e₁ : expr) (n1 : ℕ) : expr → expr → tactic (expr × expr) | e₂ p := do k ← e₂.to_nat, let k1 := bit1 k, e₁1 ← mk_app ``bit1 [e₁], e₂1 ← mk_app ``bit1 [e₂], if n1 < k1*k1 then do c ← mk_instance_cache `(nat), (c, e') ← c.mk_app ``has_mul.mul [e₂1, e₂1], (e', p₁) ← norm_num e', (c, p₂) ← prove_lt simp c e₁1 e', p' ← mk_app ``min_fac_helper_5 [e₁, e₂, e', p₁, p₂, p], return (e₁1, p') else let d := k1.min_fac in if to_bool (d < k1) then do (e', p₁) ← norm_num `(%%e₂ + 1), p₂ ← prove_non_prime simp e₂1 k1 d, mk_app ``min_fac_helper_2 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' else do (_, p₂) ← simp `((%%e₂1 : ℕ) ∣ %%e₁1), if k1 ∣ n1 then do p' ← mk_app ``min_fac_helper_4 [e₁, e₂, p₂, p], return (e₂1, p') else do (e', p₁) ← norm_num `(%%e₂ + 1), mk_app ``min_fac_helper_3 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' meta def eval_prime (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime simp e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, (e₁, p) ← simp `(nat.min_fac %%e), true_intro $ (expr.const ``is_prime_helper []).mk_app [e, p₁, p] end | `(nat.min_fac 0) := refl_conv (reflect (0:ℕ)) | `(nat.min_fac 1) := refl_conv (reflect (1:ℕ)) | `(nat.min_fac (bit0 %%e)) := prod.mk `(2) <$> mk_app ``min_fac_bit0 [e] | `(nat.min_fac (bit1 %%e)) := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, mk_app ``min_fac_helper_0 [e, p] >>= prove_min_fac simp e (bit1 n) `(1) | _ := failed meta def derive1 (simp : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := norm_num e <|> eval_div_ext simp e <|> eval_pow simp e <|> eval_ineq simp e <|> eval_prime simp e meta def derive : expr → tactic (expr × expr) | e := do (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← derive1 derive e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) end norm_num namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at derive ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` `<` `≤` over ordered fields (or other appropriate classes), as well as `-` `/` `%` over `ℤ` and `ℕ`. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := let t := orelse' (norm_num1 l) $ simp_core {} (norm_num1 (loc.ns [none])) ff hs [] l in t >> repeat t meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ end tactic.interactive
9ef7f1fc4737200ec72cff83662a4af78446348a
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Elab/PatternVar.lean
965ee9ec66d536246ff561132542161e3da6e02d
[ "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
13,762
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.MatchPatternAttr import Lean.Elab.Arg import Lean.Elab.MatchAltView namespace Lean.Elab.Term open Meta inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array (Name × BinderInfo) -- parameters names and binder information paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) return Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.2.isExplicit else false private def getNextParam (ctx : Context) : (Name × BinderInfo) × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" if (← get).found.contains id then throwError "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } return idStx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax private def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do nameToPattern (← resolveGlobalConstNoOverloadWithInfo stx[2]) partial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do let k := stx.getKind if k == identKind then processId stx else if k == ``Lean.Parser.Term.app then processCtorApp stx else if k == ``Lean.Parser.Term.anonymousCtor then let elems ← stx[1].getArgs.mapSepElemsM collect return stx.setArg 1 <| mkNullNode elems else if k == ``Lean.Parser.Term.structInst then /- ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := stx[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← stx[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- leading_parser structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field return stx.setArg 2 <| mkNullNode fields else if k == ``Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r } return r else if k == ``Lean.Parser.Term.paren then let arg := stx[1] if arg.isNone then return stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t return stx.setArg 1 arg else return stx else if k == ``Lean.Parser.Term.explicitUniv then processCtor stx[0] else if k == ``Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> trailing_parser "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == ``Lean.Parser.Term.binop then let lhs ← collect stx[2] let rhs ← collect stx[3] return stx.setArg 2 lhs |>.setArg 3 rhs else if k == ``Lean.Parser.Term.inaccessible then return stx else if k == strLitKind then return stx else if k == numLitKind then return stx else if k == scientificLitKind then return stx else if k == charLitKind then return stx else if k == ``Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == ``Lean.Parser.Term.doubleQuotedName then /- Similar to previous case -/ doubleQuotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern where processCtorApp (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← expandApp stx true processCtorAppCore f namedArgs args ellipsis processCtor (stx : Syntax) : M Syntax := do processCtorAppCore stx #[] #[] false /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ processId (stx : Syntax) : M Syntax := do match (← resolveId? stx "pattern" (withInfo := true)) with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => processCtor stx | some _ => if hasMatchPatternAttribute (← getEnv) fName then processCtor stx else processVar stx | none => throwCtorExpected | _ => processVar stx pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do match arg with | Arg.stx stx => let stx ← if accessible then collect stx else pure stx return { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do match ctx.args with | [] => if ctx.ellipsis then pushNewArg accessible ctx (Arg.stx (← `(_))) else throwError "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => pushNewArg accessible { ctx with args := args } arg processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do if ctx.explicit then processExplicitArg accessible ctx else pushNewArg accessible ctx (Arg.stx (← `(_))) processCtorAppContext (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg accessible ctx arg.val processCtorAppContext ctx | none => let ctx ← match d.2 with | BinderInfo.implicit => processImplicitArg accessible ctx | BinderInfo.instImplicit => processImplicitArg accessible ctx | _ => processExplicitArg accessible ctx processCtorAppContext ctx processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" (withInfo := true) | throwCtorExpected let fInfo ← getConstInfo fName let paramDecls ← forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do let d ← getFVarLocalDecl x return (d.userName, d.binderInfo) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => if hasMatchPatternAttribute (← getEnv) fName then processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match] "collecting variables at pattern: {p}" collect p return { alt with patterns := patterns } end CollectPatternVars def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} return (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used by the main `match` elaborator, but in the precheck hook and other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM <| expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} return s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern) let (_, s) ← collect.run {} return s.vars def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none end Lean.Elab.Term
1958695ccb622f71b791cccde9570613c678c050
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Elab/Do.lean
cd50c5ad16204261cdb4c6ae47750660542a5d3b
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
69,581
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.Elab.Term import Lean.Elab.Binders import Lean.Elab.Match import Lean.Elab.Quotation.Util import Lean.Parser.Do namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Lean.Parser.Term.do || k == ``Lean.Parser.Term.doSeqIndent || k == ``Lean.Parser.Term.doSeqBracketed || k == ``Lean.Parser.Term.termReturn || k == ``Lean.Parser.Term.termUnless || k == ``Lean.Parser.Term.termTry || k == ``Lean.Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Lean.Parser.Term.letPatDecl then false else if k == ``Lean.Parser.Term.letEqnsDecl then true else if k == ``Lean.Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts || k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Lean.Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Lean.Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Lean.Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr hasBindInst : Expr expectedType : Expr private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst `Id [u] let idBindVal := Lean.mkConst `Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do match type with | Expr.app m α _ => try let bindInstType ← mkAppM `Bind #[m] let bindInstVal ← Meta.synthInstance bindInstType return some { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType } catch _ => return none | _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => mkIdBindFor expectedType namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ @[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec @[specialize] loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref g ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => ``(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == `Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == `Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType ref arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == `Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] ``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref genParam discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM @[inline] def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x def checkNotShadowingMutable (xs : Array Name) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x then throwInvalidShadowing x @[inline] def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then return stx else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then Macro.throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1] let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet || kind == `Lean.Parser.Term.doLetRec || kind == `Lean.Parser.Term.doHave || kind == `Lean.Parser.Term.doReassign || kind == `Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then let y := decl[0].getId checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == `Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys ``(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let discrs := doMatch[2] let optType := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == `Lean.Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x.getId] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular ``(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _) if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == `Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == `Lean.Parser.Term.doHave then let var := getDoHaveVar doElem checkNotShadowingMutable #[var] mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == `Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == `Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == `Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == `Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == `Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == `Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == `Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == `Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == `Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == `Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn end Lean.Elab.Term
54e32e49680cb2d747fe2eacfe191da3058a29c4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/list/pairwise.lean
9cea9816c895feec06b282fab2640503debf87ff
[ "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
14,249
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic open nat function universes u v variables {α : Type u} {β : Type v} namespace list /- pairwise relation (generalized no duplicate) -/ mk_iff_of_inductive_prop list.pairwise list.pairwise_iff variable {R : α → α → Prop} theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left s.subset i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end lemma forall_of_pairwise (H : symmetric R) {l : list α} (hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) := forall_of_forall_of_pairwise (λ a b h hne, H (h hne.symm)) (λ _ _ h, (h rfl).elim) (pairwise.imp (λ _ _ h _, h) hl) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_append_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_append_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ sl₁.subset $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /- pairwise reduct -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := (pw_filter_sublist _).subset theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end list
a00ffed467387d46dd164b1fa11b30da632f4a42
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/topology/bases.lean
9e3567ed0eb5d4c27c01d214232e34c2dfe46ed8
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
13,366
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 Bases of topologies. Countability axioms. -/ import topology.constructions import topology.continuous_on open set filter classical open_locale topological_space filter noncomputable theory namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b, ie.symm ▸ ⟨_, h⟩⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact ⟨a, mem_univ a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (le_generate_from $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)) (le_generate_from $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s.nonempty, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa sInter_singleton⟩, sInter_singleton s⟩)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial is_open_univ in ⟨u, h₁, h₂⟩, le_antisymm (le_generate_from h_open) (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.2.2, nhds_generate_from, binfi_sets_eq], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) lemma exists_dense_seq [separable_space α] [nonempty α] : ∃ u : ℕ → α, closure (range u) = univ := begin obtain ⟨s : set α, hs, s_dense⟩ := @separable_space.exists_countable_closure_eq_univ α _ _, cases countable_iff_exists_surjective.mp hs with u hu, use u, apply eq_univ_of_univ_subset, simpa [s_dense] using closure_mono hu end /-- A sequence dense in a non-empty separable topological space. -/ def dense_seq [separable_space α] [nonempty α] : ℕ → α := classical.some (exists_dense_seq α) lemma dense_seq_dense [separable_space α] [nonempty α] : closure (range $ dense_seq α) = univ := classical.some_spec (exists_dense_seq α) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated) namespace first_countable_topology variable {α} lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α} (hx : map_cluster_pt x at_top u) : ∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) := (nhds_generated_countable x).subseq_tendsto hx end first_countable_topology variables {α} lemma is_countably_generated_nhds [first_countable_topology α] (x : α) : is_countably_generated (𝓝 x) := first_countable_topology.nhds_generated_countable x lemma is_countably_generated_nhds_within [first_countable_topology α] (x : α) (s : set α) : is_countably_generated (𝓝[s] x) := (is_countably_generated_nhds x).inf_principal s variable (α) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable [] : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨begin intros, rw [eq, nhds_generate_from], exact is_countably_generated_binfi_principal (hb.mono (assume x, and.right)), end⟩ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in ⟨b', ((countable_set_of_finite_subset hb₁).mono (by { simp only [← and_assoc], apply inter_subset_left })).image _, assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp), is_topological_basis_of_subbasis hb₂⟩ /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (ha₁.bUnion $ assume u hu, hb₁.bUnion $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable.image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1 with f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := begin rcases is_open_generated_countable_inter α with ⟨b, hbc, hbne, hb, hbU, eq⟩, set S : α → set (set α) := λ a, {s : set α | a ∈ s ∧ s ∈ b}, have nhds_eq : ∀a, 𝓝 a = (⨅ s ∈ S a, 𝓟 s), { intro a, rw [eq, nhds_generate_from] }, have : ∀ s ∈ b, set.nonempty s := assume s hs, ne_empty_iff_nonempty.1 $ λ eq, absurd hs (eq.symm ▸ hbne), choose f hf, refine ⟨⟨⋃ s ∈ b, {f s ‹_›}, hbc.bUnion (λ _ _, countable_singleton _), _⟩⟩, refine eq_univ_of_forall (λ a, _), suffices : (⨅ s ∈ S a, 𝓟 (s ∩ ⋃ t ∈ b, {f t ‹_›})).ne_bot, { obtain ⟨t, htb, hta⟩ : a ∈ ⋃₀ b, { simp only [hbU] }, have A : ∃ s, s ∈ S a := ⟨t, hta, htb⟩, simpa only [← inf_principal, mem_closure_iff_cluster_pt, cluster_pt, nhds_eq, binfi_inf A] using this }, rw [infi_subtype'], haveI : nonempty α := ⟨a⟩, refine infi_ne_bot_of_directed _ _, { rintros ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, obtain ⟨t, htb, hta, ht⟩ : ∃ t ∈ b, a ∈ t ∧ t ⊆ s₁ ∩ s₂, from hb _ hs₁ _ hs₂ a ⟨has₁, has₂⟩, refine ⟨⟨t, hta, htb⟩, _⟩, simp only [subset_inter_iff] at ht, simp only [principal_mono, subtype.coe_mk, (≥)], exact ⟨inter_subset_inter_left _ ht.1, inter_subset_inter_left _ ht.2⟩ }, rintros ⟨s, hsa, hsb⟩, suffices : (s ∩ ⋃ t ∈ b, {f t ‹_›}).nonempty, { simpa [principal_ne_bot_iff] }, refine ⟨_, hf _ hsb, _⟩, simp only [mem_Union], exact ⟨s, hsb, rfl⟩ end variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (cB.mono (sep_subset _ _)).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, cT.image _, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space
6f61ae1558be752eb2e668aef0a4148d81bb7b42
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/trace.lean
b5f2b676173b2581db4f10f1c93f17ac0d04592e
[ "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,508
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.matrix.to_lin import linear_algebra.matrix.trace /-! # Trace of a linear map This file defines the trace of a linear map. See also `linear_algebra/matrix/trace.lean` for the trace of a matrix. ## Tags linear_map, trace, diagonal -/ noncomputable theory universes u v w namespace linear_map open_locale big_operators open_locale matrix variables (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] variables {ι : Type w} [decidable_eq ι] [fintype ι] variables {κ : Type*} [decidable_eq κ] [fintype κ] variables (b : basis ι R M) (c : basis κ R M) /-- The trace of an endomorphism given a basis. -/ def trace_aux : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace ι R R) ∘ₗ ↑(linear_map.to_matrix b b) -- Can't be `simp` because it would cause a loop. lemma trace_aux_def (b : basis ι R M) (f : M →ₗ[R] M) : trace_aux R b f = matrix.trace ι R R (linear_map.to_matrix b b f) := rfl theorem trace_aux_eq : trace_aux R b = trace_aux R c := linear_map.ext $ λ f, calc matrix.trace ι R R (linear_map.to_matrix b b f) = matrix.trace ι R R (linear_map.to_matrix b b ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace ι R R (linear_map.to_matrix c b linear_map.id ⬝ linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id) : by rw [linear_map.to_matrix_comp _ c, linear_map.to_matrix_comp _ c] ... = matrix.trace κ R R (linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id ⬝ linear_map.to_matrix c b linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace κ R R (linear_map.to_matrix c c ((f.comp linear_map.id).comp linear_map.id)) : by rw [linear_map.to_matrix_comp _ b, linear_map.to_matrix_comp _ c] ... = matrix.trace κ R R (linear_map.to_matrix c c f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical variables (R) (M) /-- Trace of an endomorphism independent of basis. -/ def trace : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ (s : finset M), nonempty (basis s R M) then trace_aux R H.some_spec.some else 0 variables (R) {M} /-- Auxiliary lemma for `trace_eq_matrix_trace`. -/ theorem trace_eq_matrix_trace_of_finset {s : finset M} (b : basis s R M) (f : M →ₗ[R] M) : trace R M f = matrix.trace s R R (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s R M), from ⟨s, ⟨b⟩⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_eq_matrix_trace (f : M →ₗ[R] M) : trace R M f = matrix.trace ι R R (linear_map.to_matrix b b f) := if hR : nontrivial R then by haveI := hR; rw [trace_eq_matrix_trace_of_finset R b.reindex_finset_range, ← trace_aux_def, ← trace_aux_def, trace_aux_eq R b] else @subsingleton.elim _ (not_nontrivial_iff_subsingleton.mp hR) _ _ theorem trace_mul_comm (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ (s : finset M), nonempty (basis s R M) then let ⟨s, ⟨b⟩⟩ := H in by { simp_rw [trace_eq_matrix_trace R b, linear_map.to_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] end linear_map
14bd3c464a07a7341d88fb676720d4802b55f4dc
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/projection.lean
485cfa222065c166a0db98623f30a35829a35fef
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,094
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 linear_algebra.basic import linear_algebra.prod /-! # Projection to a subspace In this file we define * `linear_proj_of_is_compl (p q : submodule R E) (h : is_compl p q)`: the projection of a module `E` to a submodule `p` along its complement `q`; it is the unique linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. * `is_compl_equiv_proj p`: equivalence between submodules `q` such that `is_compl p q` and projections `f : E → p`, `∀ x ∈ p, f x = x`. We also provide some lemmas justifying correctness of our definitions. ## Tags projection, complement subspace -/ variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {G : Type*} [add_comm_group G] [module R G] (p q : submodule R E) noncomputable theory namespace linear_map variable {p} open submodule lemma ker_id_sub_eq_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) : ker (id - p.subtype.comp f) = p := begin ext x, simp only [comp_apply, mem_ker, subtype_apply, sub_apply, id_apply, sub_eq_zero], exact ⟨λ h, h.symm ▸ submodule.coe_mem _, λ hx, by erw [hf ⟨x, hx⟩, subtype.coe_mk]⟩ end lemma range_eq_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) : range f = ⊤ := range_eq_top.2 $ λ x, ⟨x, hf x⟩ lemma is_compl_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) : is_compl p f.ker := begin split, { rintros x ⟨hpx, hfx⟩, erw [set_like.mem_coe, mem_ker, hf ⟨x, hpx⟩, mk_eq_zero] at hfx, simp only [hfx, set_like.mem_coe, zero_mem] }, { intros x hx, rw [mem_sup'], refine ⟨f x, ⟨x - f x, _⟩, add_sub_cancel'_right _ _⟩, rw [mem_ker, linear_map.map_sub, hf, sub_self] } end end linear_map namespace submodule open linear_map /-- If `q` is a complement of `p`, then `M/p ≃ q`. -/ def quotient_equiv_of_is_compl (h : is_compl p q) : p.quotient ≃ₗ[R] q := linear_equiv.symm $ linear_equiv.of_bijective (p.mkq.comp q.subtype) (by simp only [← ker_eq_bot, ker_comp, ker_mkq, disjoint_iff_comap_eq_bot.1 h.symm.disjoint]) (by simp only [← range_eq_top, range_comp, range_subtype, map_mkq_eq_top, h.sup_eq_top]) @[simp] lemma quotient_equiv_of_is_compl_symm_apply (h : is_compl p q) (x : q) : (quotient_equiv_of_is_compl p q h).symm x = quotient.mk x := rfl @[simp] lemma quotient_equiv_of_is_compl_apply_mk_coe (h : is_compl p q) (x : q) : quotient_equiv_of_is_compl p q h (quotient.mk x) = x := (quotient_equiv_of_is_compl p q h).apply_symm_apply x @[simp] lemma mk_quotient_equiv_of_is_compl_apply (h : is_compl p q) (x : p.quotient) : (quotient.mk (quotient_equiv_of_is_compl p q h x) : p.quotient) = x := (quotient_equiv_of_is_compl p q h).symm_apply_apply x /-- If `q` is a complement of `p`, then `p × q` is isomorphic to `E`. It is the unique linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. -/ def prod_equiv_of_is_compl (h : is_compl p q) : (p × q) ≃ₗ[R] E := begin apply linear_equiv.of_bijective (p.subtype.coprod q.subtype), { simp only [←ker_eq_bot, ker_eq_bot', prod.forall, subtype_apply, prod.mk_eq_zero, coprod_apply], -- TODO: if I add `submodule.forall`, it unfolds the outer `∀` but not the inner one. rintros ⟨x, hx⟩ ⟨y, hy⟩, simp only [coe_mk, mk_eq_zero, ← eq_neg_iff_add_eq_zero], rintro rfl, rw [neg_mem_iff] at hx, simp [disjoint_def.1 h.disjoint y hx hy] }, { rw [← range_eq_top, ← sup_eq_range, h.sup_eq_top] } end @[simp] lemma coe_prod_equiv_of_is_compl (h : is_compl p q) : (prod_equiv_of_is_compl p q h : (p × q) →ₗ[R] E) = p.subtype.coprod q.subtype := rfl @[simp] lemma coe_prod_equiv_of_is_compl' (h : is_compl p q) (x : p × q) : prod_equiv_of_is_compl p q h x = x.1 + x.2 := rfl @[simp] lemma prod_equiv_of_is_compl_symm_apply_left (h : is_compl p q) (x : p) : (prod_equiv_of_is_compl p q h).symm x = (x, 0) := (prod_equiv_of_is_compl p q h).symm_apply_eq.2 $ by simp @[simp] lemma prod_equiv_of_is_compl_symm_apply_right (h : is_compl p q) (x : q) : (prod_equiv_of_is_compl p q h).symm x = (0, x) := (prod_equiv_of_is_compl p q h).symm_apply_eq.2 $ by simp @[simp] lemma prod_equiv_of_is_compl_symm_apply_fst_eq_zero (h : is_compl p q) {x : E} : ((prod_equiv_of_is_compl p q h).symm x).1 = 0 ↔ x ∈ q := begin conv_rhs { rw [← (prod_equiv_of_is_compl p q h).apply_symm_apply x] }, rw [coe_prod_equiv_of_is_compl', submodule.add_mem_iff_left _ (submodule.coe_mem _), mem_right_iff_eq_zero_of_disjoint h.disjoint] end @[simp] lemma prod_equiv_of_is_compl_symm_apply_snd_eq_zero (h : is_compl p q) {x : E} : ((prod_equiv_of_is_compl p q h).symm x).2 = 0 ↔ x ∈ p := begin conv_rhs { rw [← (prod_equiv_of_is_compl p q h).apply_symm_apply x] }, rw [coe_prod_equiv_of_is_compl', submodule.add_mem_iff_right _ (submodule.coe_mem _), mem_left_iff_eq_zero_of_disjoint h.disjoint] end /-- Projection to a submodule along its complement. -/ def linear_proj_of_is_compl (h : is_compl p q) : E →ₗ[R] p := (linear_map.fst R p q) ∘ₗ ↑(prod_equiv_of_is_compl p q h).symm variables {p q} @[simp] lemma linear_proj_of_is_compl_apply_left (h : is_compl p q) (x : p) : linear_proj_of_is_compl p q h x = x := by simp [linear_proj_of_is_compl] @[simp] lemma linear_proj_of_is_compl_range (h : is_compl p q) : (linear_proj_of_is_compl p q h).range = ⊤ := range_eq_of_proj (linear_proj_of_is_compl_apply_left h) @[simp] lemma linear_proj_of_is_compl_apply_eq_zero_iff (h : is_compl p q) {x : E} : linear_proj_of_is_compl p q h x = 0 ↔ x ∈ q:= by simp [linear_proj_of_is_compl] lemma linear_proj_of_is_compl_apply_right' (h : is_compl p q) (x : E) (hx : x ∈ q) : linear_proj_of_is_compl p q h x = 0 := (linear_proj_of_is_compl_apply_eq_zero_iff h).2 hx @[simp] lemma linear_proj_of_is_compl_apply_right (h : is_compl p q) (x : q) : linear_proj_of_is_compl p q h x = 0 := linear_proj_of_is_compl_apply_right' h x x.2 @[simp] lemma linear_proj_of_is_compl_ker (h : is_compl p q) : (linear_proj_of_is_compl p q h).ker = q := ext $ λ x, mem_ker.trans (linear_proj_of_is_compl_apply_eq_zero_iff h) lemma linear_proj_of_is_compl_comp_subtype (h : is_compl p q) : (linear_proj_of_is_compl p q h).comp p.subtype = id := linear_map.ext $ linear_proj_of_is_compl_apply_left h lemma linear_proj_of_is_compl_idempotent (h : is_compl p q) (x : E) : linear_proj_of_is_compl p q h (linear_proj_of_is_compl p q h x) = linear_proj_of_is_compl p q h x := linear_proj_of_is_compl_apply_left h _ lemma exists_unique_add_of_is_compl_prod (hc : is_compl p q) (x : E) : ∃! (u : p × q), (u.fst : E) + u.snd = x := (prod_equiv_of_is_compl _ _ hc).to_equiv.bijective.exists_unique _ lemma exists_unique_add_of_is_compl (hc : is_compl p q) (x : E) : ∃ (u : p) (v : q), ((u : E) + v = x ∧ ∀ (r : p) (s : q), (r : E) + s = x → r = u ∧ s = v) := let ⟨u, hu₁, hu₂⟩ := exists_unique_add_of_is_compl_prod hc x in ⟨u.1, u.2, hu₁, λ r s hrs, prod.eq_iff_fst_eq_snd_eq.1 (hu₂ ⟨r, s⟩ hrs)⟩ end submodule namespace linear_map open submodule /-- Given linear maps `φ` and `ψ` from complement submodules, `of_is_compl` is the induced linear map over the entire module. -/ def of_is_compl {p q : submodule R E} (h : is_compl p q) (φ : p →ₗ[R] F) (ψ : q →ₗ[R] F) : E →ₗ[R] F := (linear_map.coprod φ ψ) ∘ₗ ↑(submodule.prod_equiv_of_is_compl _ _ h).symm variables {p q} @[simp] lemma of_is_compl_left_apply (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (u : p) : of_is_compl h φ ψ (u : E) = φ u := by simp [of_is_compl] @[simp] lemma of_is_compl_right_apply (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (v : q) : of_is_compl h φ ψ (v : E) = ψ v := by simp [of_is_compl] lemma of_is_compl_eq (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} {χ : E →ₗ[R] F} (hφ : ∀ u, φ u = χ u) (hψ : ∀ u, ψ u = χ u) : of_is_compl h φ ψ = χ := begin ext x, obtain ⟨_, _, rfl, _⟩ := exists_unique_add_of_is_compl h x, simp [of_is_compl, hφ, hψ] end lemma of_is_compl_eq' (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} {χ : E →ₗ[R] F} (hφ : φ = χ.comp p.subtype) (hψ : ψ = χ.comp q.subtype) : of_is_compl h φ ψ = χ := of_is_compl_eq h (λ _, hφ.symm ▸ rfl) (λ _, hψ.symm ▸ rfl) @[simp] lemma of_is_compl_zero (h : is_compl p q) : (of_is_compl h 0 0 : E →ₗ[R] F) = 0 := of_is_compl_eq _ (λ _, rfl) (λ _, rfl) @[simp] lemma of_is_compl_add (h : is_compl p q) {φ₁ φ₂ : p →ₗ[R] F} {ψ₁ ψ₂ : q →ₗ[R] F} : of_is_compl h (φ₁ + φ₂) (ψ₁ + ψ₂) = of_is_compl h φ₁ ψ₁ + of_is_compl h φ₂ ψ₂ := of_is_compl_eq _ (by simp) (by simp) @[simp] lemma of_is_compl_smul {R : Type*} [comm_ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {p q : submodule R E} (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (c : R) : of_is_compl h (c • φ) (c • ψ) = c • of_is_compl h φ ψ := of_is_compl_eq _ (by simp) (by simp) section variables {R₁ : Type*} [comm_ring R₁] [module R₁ E] [module R₁ F] /-- The linear map from `(p →ₗ[R₁] F) × (q →ₗ[R₁] F)` to `E →ₗ[R₁] F`. -/ def of_is_compl_prod {p q : submodule R₁ E} (h : is_compl p q) : ((p →ₗ[R₁] F) × (q →ₗ[R₁] F)) →ₗ[R₁] (E →ₗ[R₁] F) := { to_fun := λ φ, of_is_compl h φ.1 φ.2, map_add' := by { intros φ ψ, rw [prod.snd_add, prod.fst_add, of_is_compl_add] }, map_smul' := by { intros c φ, rw [prod.smul_snd, prod.smul_fst, of_is_compl_smul] } } @[simp] lemma of_is_compl_prod_apply {p q : submodule R₁ E} (h : is_compl p q) (φ : (p →ₗ[R₁] F) × (q →ₗ[R₁] F)) : of_is_compl_prod h φ = of_is_compl h φ.1 φ.2 := rfl /-- The natural linear equivalence between `(p →ₗ[R₁] F) × (q →ₗ[R₁] F)` and `E →ₗ[R₁] F`. -/ def of_is_compl_prod_equiv {p q : submodule R₁ E} (h : is_compl p q) : ((p →ₗ[R₁] F) × (q →ₗ[R₁] F)) ≃ₗ[R₁] (E →ₗ[R₁] F) := { inv_fun := λ φ, ⟨φ.dom_restrict p, φ.dom_restrict q⟩, left_inv := begin intros φ, ext, { exact of_is_compl_left_apply h x }, { exact of_is_compl_right_apply h x } end, right_inv := begin intro φ, ext, obtain ⟨a, b, hab, _⟩ := exists_unique_add_of_is_compl h x, rw [← hab], simp, end, .. of_is_compl_prod h } end @[simp] lemma linear_proj_of_is_compl_of_proj (f : E →ₗ[R] p) (hf : ∀ x : p, f x = x) : p.linear_proj_of_is_compl f.ker (is_compl_of_proj hf) = f := begin ext x, have : x ∈ p ⊔ f.ker, { simp only [(is_compl_of_proj hf).sup_eq_top, mem_top] }, rcases mem_sup'.1 this with ⟨x, y, rfl⟩, simp [hf] end /-- If `f : E →ₗ[R] F` and `g : E →ₗ[R] G` are two surjective linear maps and their kernels are complement of each other, then `x ↦ (f x, g x)` defines a linear equivalence `E ≃ₗ[R] F × G`. -/ def equiv_prod_of_surjective_of_is_compl (f : E →ₗ[R] F) (g : E →ₗ[R] G) (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : E ≃ₗ[R] F × G := linear_equiv.of_bijective (f.prod g) (by simp [← ker_eq_bot, hfg.inf_eq_bot]) (by simp [← range_eq_top, range_prod_eq hfg.sup_eq_top, *]) @[simp] lemma coe_equiv_prod_of_surjective_of_is_compl {f : E →ₗ[R] F} {g : E →ₗ[R] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : (equiv_prod_of_surjective_of_is_compl f g hf hg hfg : E →ₗ[R] F × G) = f.prod g := rfl @[simp] lemma equiv_prod_of_surjective_of_is_compl_apply {f : E →ₗ[R] F} {g : E →ₗ[R] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) (x : E): equiv_prod_of_surjective_of_is_compl f g hf hg hfg x = (f x, g x) := rfl end linear_map namespace submodule open linear_map /-- Equivalence between submodules `q` such that `is_compl p q` and linear maps `f : E →ₗ[R] p` such that `∀ x : p, f x = x`. -/ def is_compl_equiv_proj : {q // is_compl p q} ≃ {f : E →ₗ[R] p // ∀ x : p, f x = x} := { to_fun := λ q, ⟨linear_proj_of_is_compl p q q.2, linear_proj_of_is_compl_apply_left q.2⟩, inv_fun := λ f, ⟨(f : E →ₗ[R] p).ker, is_compl_of_proj f.2⟩, left_inv := λ ⟨q, hq⟩, by simp only [linear_proj_of_is_compl_ker, subtype.coe_mk], right_inv := λ ⟨f, hf⟩, subtype.eq $ f.linear_proj_of_is_compl_of_proj hf } @[simp] lemma coe_is_compl_equiv_proj_apply (q : {q // is_compl p q}) : (p.is_compl_equiv_proj q : E →ₗ[R] p) = linear_proj_of_is_compl p q q.2 := rfl @[simp] lemma coe_is_compl_equiv_proj_symm_apply (f : {f : E →ₗ[R] p // ∀ x : p, f x = x}) : (p.is_compl_equiv_proj.symm f : submodule R E) = (f : E →ₗ[R] p).ker := rfl end submodule
d06f0293bcd06727c1e19c4a99b0ad2d4a016335
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/subsemiring/basic.lean
4794203c5798cdc45da5e733d7d20b38d2bcd1b4
[ "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
47,979
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 algebra.module.basic import algebra.ring.equiv import algebra.ring.prod import algebra.order.ring.inj_surj import algebra.group_ring_action.subobjects import data.set.finite import group_theory.submonoid.centralizer import group_theory.submonoid.membership /-! # Bundled subsemirings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define bundled subsemirings and some standard constructions: `complete_lattice` structure, `subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of a `ring_hom` etc. -/ open_locale big_operators universes u v w section add_submonoid_with_one_class /-- `add_submonoid_with_one_class S R` says `S` is a type of subsets `s ≤ R` that contain `0`, `1`, and are closed under `(+)` -/ class add_submonoid_with_one_class (S : Type*) (R : Type*) [add_monoid_with_one R] [set_like S R] extends add_submonoid_class S R, one_mem_class S R : Prop variables {S R : Type*} [add_monoid_with_one R] [set_like S R] (s : S) lemma nat_cast_mem [add_submonoid_with_one_class S R] (n : ℕ) : (n : R) ∈ s := by induction n; simp [zero_mem, add_mem, one_mem, *] @[priority 74] instance add_submonoid_with_one_class.to_add_monoid_with_one [add_submonoid_with_one_class S R] : add_monoid_with_one s := { one := ⟨_, one_mem s⟩, nat_cast := λ n, ⟨n, nat_cast_mem s n⟩, nat_cast_zero := subtype.ext nat.cast_zero, nat_cast_succ := λ n, subtype.ext (nat.cast_succ _), .. add_submonoid_class.to_add_monoid s } end add_submonoid_with_one_class variables {R : Type u} {S : Type v} {T : Type w} [non_assoc_semiring R] (M : submonoid R) section subsemiring_class /-- `subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that are both a multiplicative and an additive submonoid. -/ class subsemiring_class (S : Type*) (R : Type u) [non_assoc_semiring R] [set_like S R] extends submonoid_class S R, add_submonoid_class S R : Prop @[priority 100] -- See note [lower instance priority] instance subsemiring_class.add_submonoid_with_one_class (S : Type*) (R : Type u) [non_assoc_semiring R] [set_like S R] [h : subsemiring_class S R] : add_submonoid_with_one_class S R := { .. h } variables [set_like S R] [hSR : subsemiring_class S R] (s : S) include hSR lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s := by { rw ← nsmul_one, exact nsmul_mem (one_mem _) _ } namespace subsemiring_class /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ @[priority 75] -- Prefer subclasses of `non_assoc_semiring` over subclasses of `subsemiring_class`. instance to_non_assoc_semiring : non_assoc_semiring s := subtype.coe_injective.non_assoc_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. submonoid_class.subtype s, .. add_submonoid_class.subtype s } @[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl omit hSR /-- A subsemiring of a `semiring` is a `semiring`. -/ @[priority 75] -- Prefer subclasses of `semiring` over subclasses of `subsemiring_class`. instance to_semiring {R} [semiring R] [set_like S R] [subsemiring_class S R] : semiring s := subtype.coe_injective.semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) @[simp, norm_cast] lemma coe_pow {R} [semiring R] [set_like S R] [subsemiring_class S R] (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] [set_like S R] [subsemiring_class S R] : comm_semiring s := subtype.coe_injective.comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] [set_like S R] [subsemiring_class S R] : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `strict_ordered_semiring` is an `strict_ordered_semiring`. -/ instance to_strict_ordered_semiring {R} [strict_ordered_semiring R] [set_like S R] [subsemiring_class S R] : strict_ordered_semiring s := subtype.coe_injective.strict_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] [set_like S R] [subsemiring_class S R] : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `strict_ordered_comm_semiring` is an `strict_ordered_comm_semiring`. -/ instance to_strict_ordered_comm_semiring {R} [strict_ordered_comm_semiring R] [set_like S R] [subsemiring_class S R] : strict_ordered_comm_semiring s := subtype.coe_injective.strict_ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] [set_like S R] [subsemiring_class S R] : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_comm_semiring` is a `linear_ordered_comm_semiring`. -/ instance to_linear_ordered_comm_semiring {R} [linear_ordered_comm_semiring R] [set_like S R] [subsemiring_class S R] : linear_ordered_comm_semiring s := subtype.coe_injective.linear_ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end subsemiring_class end subsemiring_class variables [non_assoc_semiring S] [non_assoc_semiring T] set_option old_structure_cmd true /-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive submonoid. -/ structure subsemiring (R : Type u) [non_assoc_semiring R] extends submonoid R, add_submonoid R /-- Reinterpret a `subsemiring` as a `submonoid`. -/ add_decl_doc subsemiring.to_submonoid /-- Reinterpret a `subsemiring` as an `add_submonoid`. -/ add_decl_doc subsemiring.to_add_submonoid namespace subsemiring instance : set_like (subsemiring R) R := { coe := subsemiring.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : subsemiring_class (subsemiring R) R := { zero_mem := zero_mem', add_mem := add_mem', one_mem := one_mem', mul_mem := mul_mem' } @[simp] lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two subsemirings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R := { carrier := s, ..S.to_add_submonoid.copy s hs, ..S.to_submonoid.copy s hs } @[simp] lemma coe_copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : (S.copy s hs : set R) = s := rfl lemma copy_eq (S : subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) := λ _ _, id @[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) := to_submonoid_strict_mono.monotone lemma to_add_submonoid_injective : function.injective (to_add_submonoid : subsemiring R → add_submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) := to_add_submonoid_strict_mono.monotone /-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s) (sa : add_submonoid R) (ha : ↑sa = s) : subsemiring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) {x : R} : x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha).to_submonoid = sm := set_like.coe_injective hm.symm @[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa =s) : (subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa := set_like.coe_injective ha.symm end subsemiring namespace subsemiring variables (s : subsemiring R) /-- A subsemiring contains the semiring's 1. -/ protected theorem one_mem : (1 : R) ∈ s := one_mem s /-- A subsemiring contains the semiring's 0. -/ protected theorem zero_mem : (0 : R) ∈ s := zero_mem s /-- A subsemiring is closed under multiplication. -/ protected theorem mul_mem {x y : R} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem /-- A subsemiring is closed under addition. -/ protected theorem add_mem {x y : R} : x ∈ s → y ∈ s → x + y ∈ s := add_mem /-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/ lemma list_prod_mem {R : Type*} [semiring R] (s : subsemiring R) {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := list_prod_mem /-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/ protected lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem /-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring` is in the `subsemiring`. -/ protected lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := multiset_prod_mem m /-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is in the `add_subsemiring`. -/ protected lemma multiset_sum_mem (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := multiset_sum_mem m /-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the subsemiring. -/ protected lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := prod_mem h /-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset` is in the `add_subsemiring`. -/ protected lemma sum_mem (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := sum_mem h /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ instance to_non_assoc_semiring : non_assoc_semiring s := { mul_zero := λ x, subtype.eq $ mul_zero x, zero_mul := λ x, subtype.eq $ zero_mul x, right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, nat_cast := λ n, ⟨n, coe_nat_mem s n⟩, nat_cast_zero := by simp [nat.cast]; refl, nat_cast_succ := λ _, by simp [nat.cast]; refl, .. s.to_submonoid.to_mul_one_class, .. s.to_add_submonoid.to_add_comm_monoid } @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl @[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) protected lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := pow_mem hx n instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- A subsemiring of a `semiring` is a `semiring`. -/ instance to_semiring {R} [semiring R] (s : subsemiring R) : semiring s := { ..s.to_non_assoc_semiring, ..s.to_submonoid.to_monoid } @[simp, norm_cast] lemma coe_pow {R} [semiring R] (s : subsemiring R) (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring} /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of a `strict_ordered_semiring` is a `strict_ordered_semiring`. -/ instance to_strict_ordered_semiring {R} [strict_ordered_semiring R] (s : subsemiring R) : strict_ordered_semiring s := subtype.coe_injective.strict_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of a `strict_ordered_comm_semiring` is a `strict_ordered_comm_semiring`. -/ instance to_strict_ordered_comm_semiring {R} [strict_ordered_comm_semiring R] (s : subsemiring R) : strict_ordered_comm_semiring s := subtype.coe_injective.strict_ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_comm_semiring` is a `linear_ordered_comm_semiring`. -/ instance to_linear_ordered_comm_semiring {R} [linear_ordered_comm_semiring R] (s : subsemiring R) : linear_ordered_comm_semiring s := subtype.coe_injective.linear_ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) protected lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) : n • x ∈ s := nsmul_mem hx n @[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl /-- The subsemiring `R` of the semiring `R`. -/ instance : has_top (subsemiring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl /-- The ring equiv between the top element of `subsemiring R` and `R`. -/ @[simps] def top_equiv : (⊤ : subsemiring R) ≃+* R := { to_fun := λ r, r, inv_fun := λ r, ⟨r, subsemiring.mem_top r⟩, left_inv := λ r, set_like.eta r _, right_inv := λ r, set_like.coe_mk r _, map_mul' := (⊤ : subsemiring R).coe_mul, map_add' := (⊤ : subsemiring R).coe_add, } /-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/ def comap (f : R →+* S) (s : subsemiring S) : subsemiring R := { carrier := f ⁻¹' s, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/ def map (f : R →+* S) (s : subsemiring R) : subsemiring S := { carrier := f '' s, .. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A subsemiring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : R →+* S) (hf : function.injective f) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), map_add' := λ _ _, subtype.ext (f.map_add _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : R →+* S) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end subsemiring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/ def srange : subsemiring S := ((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl @[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f := by { ext, simp } lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange := mem_srange.mpr ⟨x, rfl⟩ lemma map_srange : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f /-- The range of a morphism of semirings is a fintype, if the domain is a fintype. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype S`.-/ instance fintype_srange [fintype R] [decidable_eq S] (f : R →+* S) : fintype (srange f) := set.fintype_range f end ring_hom namespace subsemiring instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩ instance : inhabited (subsemiring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) := (nat.cast_ring_hom R).coe_srange lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange /-- The inf of two subsemirings is their intersection. -/ instance : has_inf (subsemiring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩ @[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subsemiring R) := ⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp) (⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) : ((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) : (Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t := mk'_to_add_submonoid _ _ /-- Subsemirings of a semiring form a complete lattice. -/ instance : complete_lattice (subsemiring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ coe_nat_mem s n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subsemiring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ section center /-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/ def center (R) [semiring R] : subsemiring R := { carrier := set.center R, zero_mem' := set.zero_mem_center R, add_mem' := λ a b, set.add_mem_center, .. submonoid.center R } lemma coe_center (R) [semiring R] : ↑(center R) = set.center R := rfl @[simp] lemma center_to_submonoid (R) [semiring R] : (center R).to_submonoid = submonoid.center R := rfl lemma mem_center_iff {R} [semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center {R} [semiring R] [decidable_eq R] [fintype R] : decidable_pred (∈ center R) := λ _, decidable_of_iff' _ mem_center_iff @[simp] lemma center_eq_top (R) [comm_semiring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance {R} [semiring R] : comm_semiring (center R) := { ..submonoid.center.comm_monoid, ..(center R).to_semiring} end center section centralizer /-- The centralizer of a set as subsemiring. -/ def centralizer {R} [semiring R] (s : set R) : subsemiring R := { carrier := s.centralizer, zero_mem' := set.zero_mem_centralizer _, add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy, ..submonoid.centralizer s } @[simp, norm_cast] lemma coe_centralizer {R} [semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl lemma centralizer_to_submonoid {R} [semiring R] (s : set R) : (centralizer s).to_submonoid = submonoid.centralizer s := rfl lemma mem_centralizer_iff {R} [semiring R] {s : set R} {z : R} : z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma center_le_centralizer {R} [semiring R] (s) : center R ≤ centralizer s := s.center_subset_centralizer lemma centralizer_le {R} [semiring R] (s t : set R) (h : s ⊆ t) : centralizer t ≤ centralizer s := set.centralizer_subset h @[simp] lemma centralizer_eq_top_iff_subset {R} [semiring R] {s : set R} : centralizer s = ⊤ ↔ s ⊆ center R := set_like.ext'_iff.trans set.centralizer_eq_top_iff_subset @[simp] lemma centralizer_univ {R} [semiring R] : centralizer set.univ = center R := set_like.ext' (set.centralizer_univ R) end centralizer /-- The `subsemiring` generated by a set. -/ def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S := mem_Inf /-- The subsemiring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) /-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ lemma mem_map_equiv {f : R ≃+* S} {K : subsemiring R} {x : S} : x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subsemiring R) : K.map (f : R →+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subsemiring S) : K.comap (f : R →+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end subsemiring namespace submonoid /-- The additive closure of a submonoid is a subsemiring. -/ def subsemiring_closure (M : submonoid R) : subsemiring R := { one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem), mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure, ..add_submonoid.closure (M : set R)} lemma subsemiring_closure_coe : (M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl lemma subsemiring_closure_to_add_submonoid : M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl /-- The `subsemiring` generated by a multiplicative submonoid coincides with the `subsemiring.closure` of the submonoid itself . -/ lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) := begin ext, refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩; rintros - ⟨H1, rfl⟩; rintros - ⟨H2, rfl⟩, { exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 }, { exact H2 sM } end end submonoid namespace subsemiring @[simp] lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s := le_antisymm (closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure)) (closure_mono (submonoid.subset_closure)) /-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure of a multiplicative submonoid `M`. -/ lemma coe_closure_eq (s : set R) : (closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) := by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure] lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) := set.ext_iff.mp (coe_closure_eq s) x @[simp] lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s := begin ext x, refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩, rintros - ⟨H, rfl⟩, rintros - ⟨J, rfl⟩, refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _), refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _), exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw), end /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, H0⟩).2 Hs h /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator] lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (H0_left : ∀ x, p 0 x) (H0_right : ∀ x, p x 0) (H1_left : ∀ x, p 1 x) (H1_right : ∀ x, p x 1) (Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p x y := closure_induction hx (λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (H1_right x₁) (Hadd_right x₁) (Hmul_right x₁)) (H0_left y) (H1_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y) lemma mem_closure_iff_exists_list {R} [semiring R] {s : set R} {x} : x ∈ closure s ↔ ∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x := ⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx) (λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x, from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1, by rw [list.map_singleton, list.sum_singleton, ht2]⟩, submonoid.closure_induction hx (λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩, by rw [list.prod_append, ht2, hu2]⟩)) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩, by rw [list.map_append, list.sum_append, HL2, HM2]⟩), λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩ variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subsemiring `S` equals `S`. -/ lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subsemiring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subsemiring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subsemiring.gi R).gc.l_Sup lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t` as a subsemiring of `R × S`. -/ def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) := { carrier := s ×ˢ t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid} @[norm_cast] lemma coe_prod (s : subsemiring R) (t : subsemiring S) : (s.prod t : set (R × S)) = s ×ˢ t := rfl lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subsemiring R) : s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subsemiring S) : (⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subsemirings is isomorphic to their product as monoids. -/ def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) : ((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subsemiring namespace ring_hom variables [non_assoc_semiring T] {s : subsemiring R} variables {σR σS : Type*} variables [set_like σR R] [set_like σS S] [subsemiring_class σR R] [subsemiring_class σS S] open subsemiring /-- Restriction of a ring homomorphism to a subsemiring of the domain. -/ def dom_restrict (f : R →+* S) (s : σR) : s →+* S := f.comp $ subsemiring_class.subtype s @[simp] lemma restrict_apply (f : R →+* S) {s : σR} (x : s) : f.dom_restrict s x = f x := rfl /-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/ def cod_restrict (f : R →+* S) (s : σS) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ n, ⟨f n, h n⟩, .. (f : R →* S).cod_restrict s h, .. (f : R →+ S).cod_restrict s h } /-- The ring homomorphism from the preimage of `s` to `s`. -/ def restrict (f : R →+* S) (s' : σR) (s : σS) (h : ∀ x ∈ s', f x ∈ s) : s' →+* s := (f.dom_restrict s').cod_restrict s (λ x, h x x.2) @[simp] lemma coe_restrict_apply (f : R →+* S) (s' : σR) (s : σS) (h : ∀ x ∈ s', f x ∈ s) (x : s') : (f.restrict s' s h x : S) = f x := rfl @[simp] lemma comp_restrict (f : R →+* S) (s' : σR) (s : σS) (h : ∀ x ∈ s', f x ∈ s) : (subsemiring_class.subtype s).comp (f.restrict s' s h) = f.comp (subsemiring_class.subtype s') := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def srange_restrict (f : R →+* S) : R →+* f.srange := f.cod_restrict f.srange f.mem_srange_self @[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) : (f.srange_restrict x : S) = f x := rfl lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩ lemma srange_top_iff_surjective {f : R →+* S} : f.srange = (⊤ : subsemiring S) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.srange = (⊤ : subsemiring S) := srange_top_iff_surjective.2 hf /-- The subsemiring of elements `x : R` such that `f x = g x` -/ def eq_slocus (f g : R →+* S) : subsemiring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g } @[simp] lemma eq_slocus_same (f : R →+* S) : f.eq_slocus f = ⊤ := set_like.ext $ λ _, eq_self_iff_true _ /-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/ lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_slocus g, from closure_le.2 h lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h lemma sclosure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subsemiring generated by a set equals the subsemiring generated by the image of the set. -/ lemma map_sclosure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (sclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subsemiring open ring_hom /-- The ring homomorphism associated to an inclusion of subsemirings. -/ def inclusion {S T : subsemiring R} (h : S ≤ T) : S →+* T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩) end subsemiring namespace ring_equiv variables {s t : subsemiring R} /-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative monoid are equal. -/ def subsemiring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.srange`. -/ def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.srange := { to_fun := λ x, f.srange_restrict x, inv_fun := λ x, (g ∘ f.srange.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.srange_restrict } @[simp] lemma sof_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(sof_left_inverse h x) = f x := rfl @[simp] lemma sof_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) : (sof_left_inverse h).symm x = g x := rfl /-- Given an equivalence `e : R ≃+* S` of semirings and a subsemiring `s` of `R`, `subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/ @[simps] def subsemiring_map (e : R ≃+* S) (s : subsemiring R) : s ≃+* s.map e.to_ring_hom := { ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid, ..e.to_mul_equiv.submonoid_map s.to_submonoid } end ring_equiv /-! ### Actions by `subsemiring`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. The only new result is `subsemiring.module`. When `R` is commutative, `algebra.of_subsemiring` provides a stronger result than those found in this file, which uses the same scalar action. -/ section actions namespace subsemiring variables {R' α β : Type*} section non_assoc_semiring variables [non_assoc_semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_smul R' α] (S : subsemiring R') : has_smul S α := S.to_submonoid.has_smul lemma smul_def [has_smul R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl instance smul_comm_class_left [has_smul R' β] [has_smul α β] [smul_comm_class R' α β] (S : subsemiring R') : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left instance smul_comm_class_right [has_smul α β] [has_smul R' β] [smul_comm_class α R' β] (S : subsemiring R') : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance [has_smul α β] [has_smul R' α] [has_smul R' β] [is_scalar_tower R' α β] (S : subsemiring R') : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [has_smul R' α] [has_faithful_smul R' α] (S : subsemiring R') : has_faithful_smul S α := S.to_submonoid.has_faithful_smul /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_zero α] [smul_with_zero R' α] (S : subsemiring R') : smul_with_zero S α := smul_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom.to_zero_hom end non_assoc_semiring variables [semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [mul_action R' α] (S : subsemiring R') : mul_action S α := S.to_submonoid.mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_monoid α] [distrib_mul_action R' α] (S : subsemiring R') : distrib_mul_action S α := S.to_submonoid.distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [monoid α] [mul_distrib_mul_action R' α] (S : subsemiring R') : mul_distrib_mul_action S α := S.to_submonoid.mul_distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_zero α] [mul_action_with_zero R' α] (S : subsemiring R') : mul_action_with_zero S α := mul_action_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α := { smul := (•), .. module.comp_hom _ S.subtype } /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [semiring α] [mul_semiring_action R' α] (S : subsemiring R') : mul_semiring_action S α := S.to_submonoid.mul_semiring_action /-- The center of a semiring acts commutatively on that semiring. -/ instance center.smul_comm_class_left : smul_comm_class (center R') R' R' := submonoid.center.smul_comm_class_left /-- The center of a semiring acts commutatively on that semiring. -/ instance center.smul_comm_class_right : smul_comm_class R' (center R') R' := submonoid.center.smul_comm_class_right /-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/ def closure_comm_semiring_of_comm {s : set R'} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) : comm_semiring (closure s) := { mul_comm := λ x y, begin ext, simp only [subsemiring.coe_mul], refine closure_induction₂ x.prop y.prop hcomm (λ x, by simp only [zero_mul, mul_zero]) (λ x, by simp only [zero_mul, mul_zero]) (λ x, by simp only [one_mul, mul_one]) (λ x, by simp only [one_mul, mul_one]) (λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x y z h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc, h₁, mul_assoc]) (λ x y z h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc]) end, ..(closure s).to_semiring } end subsemiring end actions -- While this definition is not about `subsemiring`s, this is the earliest we have -- both `strict_ordered_semiring` and `submonoid` available. /-- Submonoid of positive elements of an ordered semiring. -/ def pos_submonoid (R : Type*) [strict_ordered_semiring R] : submonoid R := { carrier := {x | 0 < x}, one_mem' := show (0 : R) < 1, from zero_lt_one, mul_mem' := λ x y (hx : 0 < x) (hy : 0 < y), mul_pos hx hy } @[simp] lemma mem_pos_monoid {R : Type*} [strict_ordered_semiring R] (u : Rˣ) : ↑u ∈ pos_submonoid R ↔ (0 : R) < u := iff.rfl
a8d6dc2b6f0405f2fec67d0391803d554aac2715
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/monad/writer_auto.lean
be9bf524d1c637bfa116bd5c6435b36e35df27a5
[]
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
8,920
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon The writer monad transformer for passing immutable state. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.monad.basic import Mathlib.algebra.group.basic import Mathlib.PostPort universes u v l u_1 u_2 u_3 u₀ u₁ v₀ v₁ namespace Mathlib structure writer_t (ω : Type u) (m : Type u → Type v) (α : Type u) where run : m (α × ω) def writer (ω : Type u) (α : Type u) := writer_t ω id namespace writer_t protected theorem ext {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (x : writer_t ω m α) (x' : writer_t ω m α) (h : run x = run x') : x = x' := sorry protected def tell {ω : Type u} {m : Type u → Type v} [Monad m] (w : ω) : writer_t ω m PUnit := mk (pure (PUnit.unit, w)) protected def listen {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : writer_t ω m α → writer_t ω m (α × ω) := sorry protected def pass {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : writer_t ω m (α × (ω → ω)) → writer_t ω m α := sorry protected def pure {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} [HasOne ω] (a : α) : writer_t ω m α := mk (pure (a, 1)) protected def bind {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} [Mul ω] (x : writer_t ω m α) (f : α → writer_t ω m β) : writer_t ω m β := mk (do let x ← run x let x' ← run (f (prod.fst x)) pure (prod.fst x', prod.snd x * prod.snd x')) protected instance monad {ω : Type u} {m : Type u → Type v} [Monad m] [HasOne ω] [Mul ω] : Monad (writer_t ω m) := sorry protected instance is_lawful_monad {ω : Type u} {m : Type u → Type v} [Monad m] [monoid ω] [is_lawful_monad m] : is_lawful_monad (writer_t ω m) := sorry protected def lift {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} [HasOne ω] (a : m α) : writer_t ω m α := mk (flip Prod.mk 1 <$> a) protected instance has_monad_lift {ω : Type u} (m : Type u → Type u_1) [Monad m] [HasOne ω] : has_monad_lift m (writer_t ω m) := has_monad_lift.mk fun (α : Type u) => writer_t.lift protected def monad_map {ω : Type u} {m : Type u → Type u_1} {m' : Type u → Type u_2} [Monad m] [Monad m'] {α : Type u} (f : {α : Type u} → m α → m' α) : writer_t ω m α → writer_t ω m' α := fun (x : writer_t ω m α) => mk (f (run x)) protected instance monad_functor {ω : Type u} (m : Type u → Type u_1) (m' : Type u → Type u_1) [Monad m] [Monad m'] : monad_functor m m' (writer_t ω m) (writer_t ω m') := monad_functor.mk writer_t.monad_map protected def adapt {ω : Type u} {m : Type u → Type v} [Monad m] {ω' : Type u} {α : Type u} (f : ω → ω') : writer_t ω m α → writer_t ω' m α := fun (x : writer_t ω m α) => mk (prod.map id f <$> run x) protected instance monad_except {ω : Type u} {m : Type u → Type v} [Monad m] (ε : outParam (Type u_1)) [HasOne ω] [Monad m] [monad_except ε m] : monad_except ε (writer_t ω m) := monad_except.mk (fun (α : Type u) => writer_t.lift ∘ throw) fun (α : Type u) (x : writer_t ω m α) (c : ε → writer_t ω m α) => mk (catch (run x) fun (e : ε) => run (c e)) end writer_t /-- An implementation of [MonadReader]( https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this function cannot be lifted using `monad_lift`. Instead, the `monad_reader_adapter` class provides the more general `adapt_reader` function. Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_reader (ρ : out_param (Type u)) (n : Type u → Type u) := (lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α) → n α) ``` -/ class monad_writer (ω : outParam (Type u)) (m : Type u → Type v) where tell : ω → m PUnit listen : {α : Type u} → m α → m (α × ω) pass : {α : Type u} → m (α × (ω → ω)) → m α protected instance writer_t.monad_writer {ω : Type u} {m : Type u → Type v} [Monad m] : monad_writer ω (writer_t ω m) := monad_writer.mk writer_t.tell (fun (α : Type u) => writer_t.listen) fun (α : Type u) => writer_t.pass protected instance reader_t.monad_writer {ω : Type u} {ρ : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (reader_t ρ m) := monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : reader_t ρ m α) => sorry) fun (α : Type u) (_x : reader_t ρ m (α × (ω → ω))) => sorry def swap_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} : (α × β) × γ → (α × γ) × β := sorry protected instance state_t.monad_writer {ω : Type u} {σ : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (state_t σ m) := monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : state_t σ m α) => sorry) fun (α : Type u) (_x : state_t σ m (α × (ω → ω))) => sorry def except_t.pass_aux {ε : Type u_1} {α : Type u_2} {ω : Type u_3} : except ε (α × (ω → ω)) → except ε α × (ω → ω) := sorry protected instance except_t.monad_writer {ω : Type u} {ε : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (except_t ε m) := monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : except_t ε m α) => sorry) fun (α : Type u) (_x : except_t ε m (α × (ω → ω))) => sorry def option_t.pass_aux {α : Type u_1} {ω : Type u_2} : Option (α × (ω → ω)) → Option α × (ω → ω) := sorry protected instance option_t.monad_writer {ω : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (option_t m) := monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : option_t m α) => sorry) fun (α : Type u) (_x : option_t m (α × (ω → ω))) => sorry /-- Adapt a monad stack, changing the type of its top-most environment. This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `monad_functor`. Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_reader_functor (ρ ρ' : out_param (Type u)) (n n' : Type u → Type u) := (map {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α → reader_t ρ' m α) → n α → n' α) ``` -/ class monad_writer_adapter (ω : outParam (Type u)) (ω' : outParam (Type u)) (m : Type u → Type v) (m' : Type u → Type v) where adapt_writer : {α : Type u} → (ω → ω') → m α → m' α /-- Transitivity. This instance generates the type-class problem with a metavariable argument (which is why this is marked as `[nolint dangerous_instance]`). Currently that is not a problem, as there are almost no instances of `monad_functor` or `monad_writer_adapter`. see Note [lower instance priority] -/ protected instance monad_writer_adapter_trans {ω : Type u} {ω' : Type u} {m : Type u → Type v} {m' : Type u → Type v} {n : Type u → Type v} {n' : Type u → Type v} [monad_writer_adapter ω ω' m m'] [monad_functor m m' n n'] : monad_writer_adapter ω ω' n n' := monad_writer_adapter.mk fun (α : Type u) (f : ω → ω') => monad_map fun (α : Type u) => adapt_writer f protected instance writer_t.monad_writer_adapter {ω : Type u} {ω' : Type u} {m : Type u → Type v} [Monad m] : monad_writer_adapter ω ω' (writer_t ω m) (writer_t ω' m) := monad_writer_adapter.mk fun (α : Type u) => writer_t.adapt protected instance writer_t.monad_run (ω : Type u) (m : Type u → Type (max u u_1)) (out : outParam (Type u → Type (max u u_1))) [monad_run out m] : monad_run (fun (α : Type u) => out (α × ω)) (writer_t ω m) := monad_run.mk fun (α : Type u) (x : writer_t ω m α) => run (writer_t.run x) /-- reduce the equivalence between two writer monads to the equivalence between their underlying monad -/ def writer_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {ω₁ : Type u₀} {α₂ : Type u₁} {ω₂ : Type u₁} (F : m₁ (α₁ × ω₁) ≃ m₂ (α₂ × ω₂)) : writer_t ω₁ m₁ α₁ ≃ writer_t ω₂ m₂ α₂ := equiv.mk (fun (_x : writer_t ω₁ m₁ α₁) => sorry) (fun (_x : writer_t ω₂ m₂ α₂) => sorry) sorry sorry end Mathlib
9d63876f65f99c54da1e1671243878617d226572
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/modular.lean
01ee6d1c547dbb464ae08164b30a406ac64fa983
[ "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
23,831
lean
/- Copyright (c) 2021 Alex Kontorovich and Heather Macbeth and Marc Masdeu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Kontorovich, Heather Macbeth, Marc Masdeu -/ import analysis.complex.upper_half_plane.basic import analysis.normed_space.finite_dimension import linear_algebra.general_linear_group import linear_algebra.matrix.general_linear_group /-! # The action of the modular group SL(2, ℤ) on the upper half-plane > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the action of `SL(2,ℤ)` on `ℍ` (via restriction of the `SL(2,ℝ)` action in `analysis.complex.upper_half_plane`). We then define the standard fundamental domain (`modular_group.fd`, `𝒟`) for this action and show (`modular_group.exists_smul_mem_fd`) that any point in `ℍ` can be moved inside `𝒟`. ## Main definitions The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ`, denoted `𝒟`: `fd := {z | 1 ≤ (z : ℂ).norm_sq ∧ |z.re| ≤ (1 : ℝ) / 2}` The standard open fundamental domain of the action of `SL(2,ℤ)` on `ℍ`, denoted `𝒟ᵒ`: `fdo := {z | 1 < (z : ℂ).norm_sq ∧ |z.re| < (1 : ℝ) / 2}` These notations are localized in the `modular` locale and can be enabled via `open_locale modular`. ## Main results Any `z : ℍ` can be moved to `𝒟` by an element of `SL(2,ℤ)`: `exists_smul_mem_fd (z : ℍ) : ∃ g : SL(2,ℤ), g • z ∈ 𝒟` If both `z` and `γ • z` are in the open domain `𝒟ᵒ` then `z = γ • z`: `eq_smul_self_of_mem_fdo_mem_fdo {z : ℍ} {g : SL(2,ℤ)} (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : z = g • z` # Discussion Standard proofs make use of the identity `g • z = a / c - 1 / (c (cz + d))` for `g = [[a, b], [c, d]]` in `SL(2)`, but this requires separate handling of whether `c = 0`. Instead, our proof makes use of the following perhaps novel identity (see `modular_group.smul_eq_lc_row0_add`): `g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))` where there is no issue of division by zero. Another feature is that we delay until the very end the consideration of special matrices `T=[[1,1],[0,1]]` (see `modular_group.T`) and `S=[[0,-1],[1,0]]` (see `modular_group.S`), by instead using abstract theory on the properness of certain maps (phrased in terms of the filters `filter.cocompact`, `filter.cofinite`, etc) to deduce existence theorems, first to prove the existence of `g` maximizing `(g•z).im` (see `modular_group.exists_max_im`), and then among those, to minimize `|(g•z).re|` (see `modular_group.exists_row_one_eq_and_min_re`). -/ /- Disable these instances as they are not the simp-normal form, and having them disabled ensures we state lemmas in this file without spurious `coe_fn` terms. -/ local attribute [-instance] matrix.special_linear_group.has_coe_to_fun local attribute [-instance] matrix.general_linear_group.has_coe_to_fun open complex (hiding abs_two) open matrix (hiding mul_smul) matrix.special_linear_group upper_half_plane noncomputable theory local notation `SL(` n `, ` R `)`:= special_linear_group (fin n) R local prefix `↑ₘ`:1024 := @coe _ (matrix (fin 2) (fin 2) ℤ) _ open_locale upper_half_plane complex_conjugate local attribute [instance] fintype.card_fin_even namespace modular_group variables {g : SL(2, ℤ)} (z : ℍ) section bottom_row /-- The two numbers `c`, `d` in the "bottom_row" of `g=[[*,*],[c,d]]` in `SL(2, ℤ)` are coprime. -/ lemma bottom_row_coprime {R : Type*} [comm_ring R] (g : SL(2, R)) : is_coprime ((↑g : matrix (fin 2) (fin 2) R) 1 0) ((↑g : matrix (fin 2) (fin 2) R) 1 1) := begin use [- (↑g : matrix (fin 2) (fin 2) R) 0 1, (↑g : matrix (fin 2) (fin 2) R) 0 0], rw [add_comm, neg_mul, ←sub_eq_add_neg, ←det_fin_two], exact g.det_coe, end /-- Every pair `![c, d]` of coprime integers is the "bottom_row" of some element `g=[[*,*],[c,d]]` of `SL(2,ℤ)`. -/ lemma bottom_row_surj {R : Type*} [comm_ring R] : set.surj_on (λ g : SL(2, R), @coe _ (matrix (fin 2) (fin 2) R) _ g 1) set.univ {cd | is_coprime (cd 0) (cd 1)} := begin rintros cd ⟨b₀, a, gcd_eqn⟩, let A := of ![![a, -b₀], cd], have det_A_1 : det A = 1, { convert gcd_eqn, simp [A, det_fin_two, (by ring : a * (cd 1) + b₀ * (cd 0) = b₀ * (cd 0) + a * (cd 1))] }, refine ⟨⟨A, det_A_1⟩, set.mem_univ _, _⟩, ext; simp [A] end end bottom_row section tendsto_lemmas open filter continuous_linear_map local attribute [simp] coe_smul /-- The function `(c,d) → |cz+d|^2` is proper, that is, preimages of bounded-above sets are finite. -/ lemma tendsto_norm_sq_coprime_pair : filter.tendsto (λ p : fin 2 → ℤ, ((p 0 : ℂ) * z + p 1).norm_sq) cofinite at_top := begin -- using this instance rather than the automatic `function.module` makes unification issues in -- `linear_equiv.closed_embedding_of_injective` less bad later in the proof. letI : module ℝ (fin 2 → ℝ) := normed_space.to_module, let π₀ : (fin 2 → ℝ) →ₗ[ℝ] ℝ := linear_map.proj 0, let π₁ : (fin 2 → ℝ) →ₗ[ℝ] ℝ := linear_map.proj 1, let f : (fin 2 → ℝ) →ₗ[ℝ] ℂ := π₀.smul_right (z:ℂ) + π₁.smul_right 1, have f_def : ⇑f = λ (p : fin 2 → ℝ), (p 0 : ℂ) * ↑z + p 1, { ext1, dsimp only [linear_map.coe_proj, real_smul, linear_map.coe_smul_right, linear_map.add_apply], rw mul_one, }, have : (λ (p : fin 2 → ℤ), norm_sq ((p 0 : ℂ) * ↑z + ↑(p 1))) = norm_sq ∘ f ∘ (λ p : fin 2 → ℤ, (coe : ℤ → ℝ) ∘ p), { ext1, rw f_def, dsimp only [function.comp], rw [of_real_int_cast, of_real_int_cast], }, rw this, have hf : f.ker = ⊥, { let g : ℂ →ₗ[ℝ] (fin 2 → ℝ) := linear_map.pi ![im_lm, im_lm.comp ((z:ℂ) • ((conj_ae : ℂ →ₐ[ℝ] ℂ) : ℂ →ₗ[ℝ] ℂ))], suffices : ((z:ℂ).im⁻¹ • g).comp f = linear_map.id, { exact linear_map.ker_eq_bot_of_inverse this }, apply linear_map.ext, intros c, have hz : (z:ℂ).im ≠ 0 := z.2.ne', rw [linear_map.comp_apply, linear_map.smul_apply, linear_map.id_apply], ext i, dsimp only [g, pi.smul_apply, linear_map.pi_apply, smul_eq_mul], fin_cases i, { show ((z : ℂ).im)⁻¹ * (f c).im = c 0, rw [f_def, add_im, of_real_mul_im, of_real_im, add_zero, mul_left_comm, inv_mul_cancel hz, mul_one], }, { show ((z : ℂ).im)⁻¹ * ((z : ℂ) * conj (f c)).im = c 1, rw [f_def, ring_hom.map_add, ring_hom.map_mul, mul_add, mul_left_comm, mul_conj, conj_of_real, conj_of_real, ← of_real_mul, add_im, of_real_im, zero_add, inv_mul_eq_iff_eq_mul₀ hz], simp only [of_real_im, of_real_re, mul_im, zero_add, mul_zero] } }, have hf' : closed_embedding f, { -- for some reason we get a timeout if we try and apply this lemma in a more sensible way have := @linear_equiv.closed_embedding_of_injective ℝ _ (fin 2 → ℝ) _ (id _) ℂ _ _ _ _, rotate 2, exact f, exact this hf }, have h₂ : tendsto (λ p : fin 2 → ℤ, (coe : ℤ → ℝ) ∘ p) cofinite (cocompact _), { convert tendsto.pi_map_Coprod (λ i, int.tendsto_coe_cofinite), { rw Coprod_cofinite }, { rw Coprod_cocompact } }, exact tendsto_norm_sq_cocompact_at_top.comp (hf'.tendsto_cocompact.comp h₂), end /-- Given `coprime_pair` `p=(c,d)`, the matrix `[[a,b],[*,*]]` is sent to `a*c+b*d`. This is the linear map version of this operation. -/ def lc_row0 (p : fin 2 → ℤ) : (matrix (fin 2) (fin 2) ℝ) →ₗ[ℝ] ℝ := ((p 0:ℝ) • linear_map.proj 0 + (p 1:ℝ) • linear_map.proj 1 : (fin 2 → ℝ) →ₗ[ℝ] ℝ).comp (linear_map.proj 0) @[simp] lemma lc_row0_apply (p : fin 2 → ℤ) (g : matrix (fin 2) (fin 2) ℝ) : lc_row0 p g = p 0 * g 0 0 + p 1 * g 0 1 := rfl /-- Linear map sending the matrix [a, b; c, d] to the matrix [ac₀ + bd₀, - ad₀ + bc₀; c, d], for some fixed `(c₀, d₀)`. -/ @[simps] def lc_row0_extend {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : (matrix (fin 2) (fin 2) ℝ) ≃ₗ[ℝ] matrix (fin 2) (fin 2) ℝ := linear_equiv.Pi_congr_right ![begin refine linear_map.general_linear_group.general_linear_equiv ℝ (fin 2 → ℝ) (general_linear_group.to_linear (plane_conformal_matrix (cd 0 : ℝ) (-(cd 1 : ℝ)) _)), norm_cast, rw neg_sq, exact hcd.sq_add_sq_ne_zero end, linear_equiv.refl ℝ (fin 2 → ℝ)] /-- The map `lc_row0` is proper, that is, preimages of cocompact sets are finite in `[[* , *], [c, d]]`.-/ theorem tendsto_lc_row0 {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : tendsto (λ g : {g : SL(2, ℤ) // ↑ₘg 1 = cd}, lc_row0 cd ↑(↑g : SL(2, ℝ))) cofinite (cocompact ℝ) := begin let mB : ℝ → (matrix (fin 2) (fin 2) ℝ) := λ t, of ![![t, (-(1:ℤ):ℝ)], coe ∘ cd], have hmB : continuous mB, { refine continuous_matrix _, simp only [fin.forall_fin_two, mB, continuous_const, continuous_id', of_apply, cons_val_zero, cons_val_one, and_self ] }, refine filter.tendsto.of_tendsto_comp _ (comap_cocompact_le hmB), let f₁ : SL(2, ℤ) → matrix (fin 2) (fin 2) ℝ := λ g, matrix.map (↑g : matrix _ _ ℤ) (coe : ℤ → ℝ), have cocompact_ℝ_to_cofinite_ℤ_matrix : tendsto (λ m : matrix (fin 2) (fin 2) ℤ, matrix.map m (coe : ℤ → ℝ)) cofinite (cocompact _), { simpa only [Coprod_cofinite, Coprod_cocompact] using tendsto.pi_map_Coprod (λ i : fin 2, tendsto.pi_map_Coprod (λ j : fin 2, int.tendsto_coe_cofinite)) }, have hf₁ : tendsto f₁ cofinite (cocompact _) := cocompact_ℝ_to_cofinite_ℤ_matrix.comp subtype.coe_injective.tendsto_cofinite, have hf₂ : closed_embedding (lc_row0_extend hcd) := (lc_row0_extend hcd).to_continuous_linear_equiv.to_homeomorph.closed_embedding, convert hf₂.tendsto_cocompact.comp (hf₁.comp subtype.coe_injective.tendsto_cofinite) using 1, ext ⟨g, rfl⟩ i j : 3, fin_cases i; [fin_cases j, skip], -- the following are proved by `simp`, but it is replaced by `simp only` to avoid timeouts. { simp only [mB, mul_vec, dot_product, fin.sum_univ_two, _root_.coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, lc_row0_apply, function.comp_app, cons_val_zero, lc_row0_extend_apply, linear_map.general_linear_group.coe_fn_general_linear_equiv, general_linear_group.to_linear_apply, coe_plane_conformal_matrix, neg_neg, mul_vec_lin_apply, cons_val_one, head_cons, of_apply] }, { convert congr_arg (λ n : ℤ, (-n:ℝ)) g.det_coe.symm using 1, simp only [f₁, mul_vec, dot_product, fin.sum_univ_two, matrix.det_fin_two, function.comp_app, subtype.coe_mk, lc_row0_extend_apply, cons_val_zero, linear_map.general_linear_group.coe_fn_general_linear_equiv, general_linear_group.to_linear_apply, coe_plane_conformal_matrix, mul_vec_lin_apply, cons_val_one, head_cons, map_apply, neg_mul, int.cast_sub, int.cast_mul, neg_sub, of_apply], ring }, { refl } end /-- This replaces `(g•z).re = a/c + *` in the standard theory with the following novel identity: `g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))` which does not need to be decomposed depending on whether `c = 0`. -/ lemma smul_eq_lc_row0_add {p : fin 2 → ℤ} (hp : is_coprime (p 0) (p 1)) (hg : ↑ₘg 1 = p) : ↑(g • z) = ((lc_row0 p ↑(g : SL(2, ℝ))) : ℂ) / (p 0 ^ 2 + p 1 ^ 2) + ((p 1 : ℂ) * z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1)) := begin have nonZ1 : (p 0 : ℂ) ^ 2 + (p 1) ^ 2 ≠ 0 := by exact_mod_cast hp.sq_add_sq_ne_zero, have : (coe : ℤ → ℝ) ∘ p ≠ 0 := λ h, hp.ne_zero (by ext i; simpa using congr_fun h i), have nonZ2 : (p 0 : ℂ) * z + p 1 ≠ 0 := by simpa using linear_ne_zero _ z this, field_simp [nonZ1, nonZ2, denom_ne_zero, -upper_half_plane.denom, -denom_apply], rw (by simp : (p 1 : ℂ) * z - p 0 = ((p 1) * z - p 0) * ↑(det (↑g : matrix (fin 2) (fin 2) ℤ))), rw [←hg, det_fin_two], simp only [int.coe_cast_ring_hom, coe_matrix_coe, int.cast_mul, of_real_int_cast, map_apply, denom, int.cast_sub, _root_.coe_coe,coe_GL_pos_coe_GL_coe_matrix], ring, end lemma tendsto_abs_re_smul {p : fin 2 → ℤ} (hp : is_coprime (p 0) (p 1)) : tendsto (λ g : {g : SL(2, ℤ) // ↑ₘg 1 = p}, |((g : SL(2, ℤ)) • z).re|) cofinite at_top := begin suffices : tendsto (λ g : (λ g : SL(2, ℤ), ↑ₘg 1) ⁻¹' {p}, (((g : SL(2, ℤ)) • z).re)) cofinite (cocompact ℝ), { exact tendsto_norm_cocompact_at_top.comp this }, have : ((p 0 : ℝ) ^ 2 + p 1 ^ 2)⁻¹ ≠ 0, { apply inv_ne_zero, exact_mod_cast hp.sq_add_sq_ne_zero }, let f := homeomorph.mul_right₀ _ this, let ff := homeomorph.add_right (((p 1:ℂ)* z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1))).re, convert ((f.trans ff).closed_embedding.tendsto_cocompact).comp (tendsto_lc_row0 hp), ext g, change ((g : SL(2, ℤ)) • z).re = (lc_row0 p ↑(↑g : SL(2, ℝ))) / (p 0 ^ 2 + p 1 ^ 2) + (((p 1:ℂ )* z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1))).re, exact_mod_cast (congr_arg complex.re (smul_eq_lc_row0_add z hp g.2)) end end tendsto_lemmas section fundamental_domain local attribute [simp] coe_smul re_smul /-- For `z : ℍ`, there is a `g : SL(2,ℤ)` maximizing `(g•z).im` -/ lemma exists_max_im : ∃ g : SL(2, ℤ), ∀ g' : SL(2, ℤ), (g' • z).im ≤ (g • z).im := begin classical, let s : set (fin 2 → ℤ) := {cd | is_coprime (cd 0) (cd 1)}, have hs : s.nonempty := ⟨![1, 1], is_coprime_one_left⟩, obtain ⟨p, hp_coprime, hp⟩ := filter.tendsto.exists_within_forall_le hs (tendsto_norm_sq_coprime_pair z), obtain ⟨g, -, hg⟩ := bottom_row_surj hp_coprime, refine ⟨g, λ g', _⟩, rw [special_linear_group.im_smul_eq_div_norm_sq, special_linear_group.im_smul_eq_div_norm_sq, div_le_div_left], { simpa [← hg] using hp (↑ₘg' 1) (bottom_row_coprime g') }, { exact z.im_pos }, { exact norm_sq_denom_pos g' z }, { exact norm_sq_denom_pos g z }, end /-- Given `z : ℍ` and a bottom row `(c,d)`, among the `g : SL(2,ℤ)` with this bottom row, minimize `|(g•z).re|`. -/ lemma exists_row_one_eq_and_min_re {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : ∃ g : SL(2,ℤ), ↑ₘg 1 = cd ∧ (∀ g' : SL(2,ℤ), ↑ₘg 1 = ↑ₘg' 1 → |(g • z).re| ≤ |(g' • z).re|) := begin haveI : nonempty {g : SL(2, ℤ) // ↑ₘg 1 = cd} := let ⟨x, hx⟩ := bottom_row_surj hcd in ⟨⟨x, hx.2⟩⟩, obtain ⟨g, hg⟩ := filter.tendsto.exists_forall_le (tendsto_abs_re_smul z hcd), refine ⟨g, g.2, _⟩, { intros g1 hg1, have : g1 ∈ ((λ g : SL(2, ℤ), ↑ₘg 1) ⁻¹' {cd}), { rw [set.mem_preimage, set.mem_singleton_iff], exact eq.trans hg1.symm (set.mem_singleton_iff.mp (set.mem_preimage.mp g.2)) }, exact hg ⟨g1, this⟩ }, end lemma coe_T_zpow_smul_eq {n : ℤ} : (↑((T^n) • z) : ℂ) = z + n := by simp [coe_T_zpow] lemma re_T_zpow_smul (n : ℤ) : ((T^n) • z).re = z.re + n := by rw [←coe_re, coe_T_zpow_smul_eq, add_re, int_cast_re, coe_re] lemma im_T_zpow_smul (n : ℤ) : ((T^n) • z).im = z.im := by rw [←coe_im, coe_T_zpow_smul_eq, add_im, int_cast_im, add_zero, coe_im] lemma re_T_smul : (T • z).re = z.re + 1 := by simpa using re_T_zpow_smul z 1 lemma im_T_smul : (T • z).im = z.im := by simpa using im_T_zpow_smul z 1 lemma re_T_inv_smul : (T⁻¹ • z).re = z.re - 1 := by simpa using re_T_zpow_smul z (-1) lemma im_T_inv_smul : (T⁻¹ • z).im = z.im := by simpa using im_T_zpow_smul z (-1) variables {z} -- If instead we had `g` and `T` of type `PSL(2, ℤ)`, then we could simply state `g = T^n`. lemma exists_eq_T_zpow_of_c_eq_zero (hc : ↑ₘg 1 0 = 0) : ∃ (n : ℤ), ∀ (z : ℍ), g • z = T^n • z := begin have had := g.det_coe, replace had : ↑ₘg 0 0 * ↑ₘg 1 1 = 1, { rw [det_fin_two, hc] at had, linarith, }, rcases int.eq_one_or_neg_one_of_mul_eq_one' had with ⟨ha, hd⟩ | ⟨ha, hd⟩, { use ↑ₘg 0 1, suffices : g = T^(↑ₘg 0 1), { intros z, conv_lhs { rw this, }, }, ext i j, fin_cases i; fin_cases j; simp [ha, hc, hd, coe_T_zpow], }, { use -↑ₘg 0 1, suffices : g = -T^(-↑ₘg 0 1), { intros z, conv_lhs { rw [this, SL_neg_smul], }, }, ext i j, fin_cases i; fin_cases j; simp [ha, hc, hd, coe_T_zpow], }, end /- If `c = 1`, then `g` factorises into a product terms involving only `T` and `S`. -/ lemma g_eq_of_c_eq_one (hc : ↑ₘg 1 0 = 1) : g = T^(↑ₘg 0 0) * S * T^(↑ₘg 1 1) := begin have hg := g.det_coe.symm, replace hg : ↑ₘg 0 1 = ↑ₘg 0 0 * ↑ₘg 1 1 - 1, { rw [det_fin_two, hc] at hg, linarith, }, refine subtype.ext _, conv_lhs { rw matrix.eta_fin_two ↑ₘg }, rw [hc, hg], simp only [coe_mul, coe_T_zpow, coe_S, mul_fin_two], congrm !![_, _; _, _]; ring end /-- If `1 < |z|`, then `|S • z| < 1`. -/ lemma norm_sq_S_smul_lt_one (h: 1 < norm_sq z) : norm_sq ↑(S • z) < 1 := by simpa [coe_S] using (inv_lt_inv z.norm_sq_pos zero_lt_one).mpr h /-- If `|z| < 1`, then applying `S` strictly decreases `im`. -/ lemma im_lt_im_S_smul (h: norm_sq z < 1) : z.im < (S • z).im := begin have : z.im < z.im / norm_sq (z:ℂ), { have imz : 0 < z.im := im_pos z, apply (lt_div_iff z.norm_sq_pos).mpr, nlinarith }, convert this, simp only [special_linear_group.im_smul_eq_div_norm_sq], field_simp [norm_sq_denom_ne_zero, norm_sq_ne_zero, S] end /-- The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ`. -/ def fd : set ℍ := {z | 1 ≤ (z : ℂ).norm_sq ∧ |z.re| ≤ (1 : ℝ) / 2} /-- The standard open fundamental domain of the action of `SL(2,ℤ)` on `ℍ`. -/ def fdo : set ℍ := {z | 1 < (z : ℂ).norm_sq ∧ |z.re| < (1 : ℝ) / 2} localized "notation (name := modular_group.fd) `𝒟` := modular_group.fd" in modular localized "notation (name := modular_group.fdo) `𝒟ᵒ` := modular_group.fdo" in modular lemma abs_two_mul_re_lt_one_of_mem_fdo (h : z ∈ 𝒟ᵒ) : |2 * z.re| < 1 := begin rw [abs_mul, abs_two, ← lt_div_iff' (zero_lt_two' ℝ)], exact h.2, end lemma three_lt_four_mul_im_sq_of_mem_fdo (h : z ∈ 𝒟ᵒ) : 3 < 4 * z.im^2 := begin have : 1 < z.re * z.re + z.im * z.im := by simpa [complex.norm_sq_apply] using h.1, have := h.2, cases abs_cases z.re; nlinarith, end /-- If `z ∈ 𝒟ᵒ`, and `n : ℤ`, then `|z + n| > 1`. -/ lemma one_lt_norm_sq_T_zpow_smul (hz : z ∈ 𝒟ᵒ) (n : ℤ) : 1 < norm_sq (((T^n) • z) : ℍ) := begin have hz₁ : 1 < z.re * z.re + z.im * z.im := hz.1, have hzn := int.nneg_mul_add_sq_of_abs_le_one n (abs_two_mul_re_lt_one_of_mem_fdo hz).le, have : 1 < (z.re + ↑n) * (z.re + ↑n) + z.im * z.im, { linarith, }, simpa [coe_T_zpow, norm_sq], end lemma eq_zero_of_mem_fdo_of_T_zpow_mem_fdo {n : ℤ} (hz : z ∈ 𝒟ᵒ) (hg : (T^n) • z ∈ 𝒟ᵒ) : n = 0 := begin suffices : |(n : ℝ)| < 1, { rwa [← int.cast_abs, ← int.cast_one, int.cast_lt, int.abs_lt_one_iff] at this, }, have h₁ := hz.2, have h₂ := hg.2, rw [re_T_zpow_smul] at h₂, calc |(n : ℝ)| ≤ |z.re| + |z.re + (n : ℝ)| : abs_add' (n : ℝ) z.re ... < 1/2 + 1/2 : add_lt_add h₁ h₂ ... = 1 : add_halves 1, end /-- Any `z : ℍ` can be moved to `𝒟` by an element of `SL(2,ℤ)` -/ lemma exists_smul_mem_fd (z : ℍ) : ∃ g : SL(2,ℤ), g • z ∈ 𝒟 := begin -- obtain a g₀ which maximizes im (g • z), obtain ⟨g₀, hg₀⟩ := exists_max_im z, -- then among those, minimize re obtain ⟨g, hg, hg'⟩ := exists_row_one_eq_and_min_re z (bottom_row_coprime g₀), refine ⟨g, _⟩, -- `g` has same max im property as `g₀` have hg₀' : ∀ (g' : SL(2,ℤ)), (g' • z).im ≤ (g • z).im, { have hg'' : (g • z).im = (g₀ • z).im, { rw [special_linear_group.im_smul_eq_div_norm_sq, special_linear_group.im_smul_eq_div_norm_sq, denom_apply, denom_apply, hg]}, simpa only [hg''] using hg₀ }, split, { -- Claim: `1 ≤ ⇑norm_sq ↑(g • z)`. If not, then `S•g•z` has larger imaginary part contrapose! hg₀', refine ⟨S * g, _⟩, rw mul_smul, exact im_lt_im_S_smul hg₀' }, { show |(g • z).re| ≤ 1 / 2, -- if not, then either `T` or `T'` decrease |Re|. rw abs_le, split, { contrapose! hg', refine ⟨T * g, (T_mul_apply_one _).symm, _⟩, rw [mul_smul, re_T_smul], cases abs_cases ((g • z).re + 1); cases abs_cases (g • z).re; linarith }, { contrapose! hg', refine ⟨T⁻¹ * g, (T_inv_mul_apply_one _).symm, _⟩, rw [mul_smul, re_T_inv_smul], cases abs_cases ((g • z).re - 1); cases abs_cases (g • z).re; linarith } } end section unique_representative variables {z} /-- An auxiliary result en route to `modular_group.c_eq_zero`. -/ lemma abs_c_le_one (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : |↑ₘg 1 0| ≤ 1 := begin let c' : ℤ := ↑ₘg 1 0, let c : ℝ := (c' : ℝ), suffices : 3 * c^2 < 4, { rw [← int.cast_pow, ← int.cast_three, ← int.cast_four, ← int.cast_mul, int.cast_lt] at this, replace this : c' ^ 2 ≤ 1 ^ 2, { linarith, }, rwa [sq_le_sq, abs_one] at this }, suffices : c ≠ 0 → 9 * c^4 < 16, { rcases eq_or_ne c 0 with hc | hc, { rw hc, norm_num, }, { refine (abs_lt_of_sq_lt_sq' _ (by norm_num)).2, specialize this hc, linarith, }, }, intros hc, replace hc : 0 < c^4, { rw pow_bit0_pos_iff; trivial, }, have h₁ := mul_lt_mul_of_pos_right (mul_lt_mul'' (three_lt_four_mul_im_sq_of_mem_fdo hg) (three_lt_four_mul_im_sq_of_mem_fdo hz) (by linarith) (by linarith)) hc, have h₂ : (c * z.im) ^ 4 / norm_sq (denom ↑g z) ^ 2 ≤ 1 := div_le_one_of_le (pow_four_le_pow_two_of_pow_two_le (upper_half_plane.c_mul_im_sq_le_norm_sq_denom z g)) (sq_nonneg _), let nsq := norm_sq (denom g z), calc 9 * c^4 < c^4 * z.im^2 * (g • z).im^2 * 16 : by linarith ... = c^4 * z.im^4 / nsq^2 * 16 : by { rw [special_linear_group.im_smul_eq_div_norm_sq, div_pow], ring, } ... ≤ 16 : by { rw ← mul_pow, linarith, }, end /-- An auxiliary result en route to `modular_group.eq_smul_self_of_mem_fdo_mem_fdo`. -/ lemma c_eq_zero (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : ↑ₘg 1 0 = 0 := begin have hp : ∀ {g' : SL(2, ℤ)} (hg' : g' • z ∈ 𝒟ᵒ), ↑ₘg' 1 0 ≠ 1, { intros, by_contra hc, let a := ↑ₘg' 0 0, let d := ↑ₘg' 1 1, have had : T^(-a) * g' = S * T^d, { rw g_eq_of_c_eq_one hc, group, }, let w := T^(-a) • (g' • z), have h₁ : w = S • (T^d • z), { simp only [w, ← mul_smul, had], }, replace h₁ : norm_sq w < 1 := h₁.symm ▸ norm_sq_S_smul_lt_one (one_lt_norm_sq_T_zpow_smul hz d), have h₂ : 1 < norm_sq w := one_lt_norm_sq_T_zpow_smul hg' (-a), linarith, }, have hn : ↑ₘg 1 0 ≠ -1, { intros hc, replace hc : ↑ₘ(-g) 1 0 = 1, { simp [← neg_eq_iff_eq_neg.mpr hc], }, replace hg : (-g) • z ∈ 𝒟ᵒ := (SL_neg_smul g z).symm ▸ hg, exact hp hg hc, }, specialize hp hg, rcases (int.abs_le_one_iff.mp $ abs_c_le_one hz hg); tauto, end /-- Second Main Fundamental Domain Lemma: if both `z` and `g • z` are in the open domain `𝒟ᵒ`, where `z : ℍ` and `g : SL(2,ℤ)`, then `z = g • z`. -/ lemma eq_smul_self_of_mem_fdo_mem_fdo (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : z = g • z := begin obtain ⟨n, hn⟩ := exists_eq_T_zpow_of_c_eq_zero (c_eq_zero hz hg), rw hn at hg ⊢, simp [eq_zero_of_mem_fdo_of_T_zpow_mem_fdo hz hg, one_smul], end end unique_representative end fundamental_domain end modular_group
e4254edbe2538f8c0b7a94a7f66b6b1128c25b4a
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/characteristic.lean
61867819de4fe18c4d54eb99ccf623aec8441739
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
2,992
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import measure_theory.measurable_space import measure_theory.measure_space import measure_theory.outer_measure import measure_theory.lebesgue_measure import measure_theory.integration import measure_theory.borel_space import data.set.countable import formal_ml.nnreal import formal_ml.ennreal import formal_ml.sum import formal_ml.lattice import formal_ml.measurable_space import formal_ml.classical import data.equiv.list noncomputable def set.characteristic {α:Type*} (S:set α):α → ennreal := S.indicator (λ _, (1:ennreal)) @[simp] lemma set.characteristic.of_mem {α:Type*} {S:set α} {a:α}:a∈ S → S.characteristic a = 1 := begin intros h, simp [set.characteristic, h], end @[simp] lemma set.characteristic.of_not_mem {α:Type*} {S:set α} {a:α}:a∉ S → S.characteristic a = 0 := begin intros h, simp [set.characteristic, h], end --α → ennreal := S.indicator (λ _, (1:ennreal)) lemma set.characteristic.subset {α:Type*} {S T:set α} (h:S⊆ T):S.characteristic ≤ T.characteristic := begin intros a, cases classical.em (a ∈ S) with h1 h1; cases classical.em (a ∈ T) with h2 h2; simp [h1, h2], { apply le_refl _ }, apply h2, apply h, apply h1, end lemma set.characteristic.prod {α β:Type*} {A:set α} {B:set β} {a:α} {b:β}: (A.prod B).characteristic (a, b) = (A.characteristic a) * (B.characteristic b) := begin cases classical.em (a ∈ A) with h1 h1; cases classical.em (b ∈ B) with h2 h2; simp [h1, h2], end lemma set.characteristic.Union {α:Type*} {S:ℕ → set α}: ((⋃ (n:ℕ), S n).characteristic) ≤ (∑' (n:ℕ), (S n).characteristic) := begin intro x, rw ennreal.tsum_apply, cases classical.em (x ∈ (⋃ (n:ℕ), S n)) with h1 h1; simp [h1], simp at h1, cases h1 with i h1, have h2 : (S i).characteristic x = 1, { simp [h1] }, rw ← h2, apply ennreal.le_tsum end lemma measure_theory.lintegral_characteristic {α:Type*} [Mα:measurable_space α] (μ:measure_theory.measure α) (S:set α): measurable_set S → (∫⁻ (a : α), S.characteristic a ∂μ) = μ S := begin intros h, simp [set.characteristic], rw measure_theory.lintegral_indicator, simp, apply h, end lemma measurable.characteristic {α:Type*} [Mα:measurable_space α] (S:set α): measurable_set S → measurable (S.characteristic) := begin intros h, simp [set.characteristic], apply measurable.indicator, simp, apply h, end
c86e2160e797912e650e590cbbf71421455c8862
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/group/units.lean
3dc905ce7430dc415478b0b171364b02d926dcda
[ "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
4,863
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes, Hölzl, Chris Hughes Units (i.e., invertible elements) of a multiplicative monoid. -/ import tactic.basic universe u variable {α : Type u} structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) namespace units variables [monoid α] {a b c : units α} instance : has_coe (units α) α := ⟨val⟩ @[extensionality] theorem ext : ∀ {a b : units α}, (a : α) = b → a = b | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := ⟨congr_arg _, ext⟩ instance [decidable_eq α] : decidable_eq (units α) | a b := decidable_of_iff' _ ext_iff protected def mul (u₁ u₂ : units α) : units α := ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, have u₁.val * (u₂.val * u₂.inv) * u₁.inv = 1, by rw [u₂.val_inv]; rw [mul_one, u₁.val_inv], by simpa only [mul_assoc], have u₂.inv * (u₁.inv * u₁.val) * u₂.val = 1, by rw [u₁.inv_val]; rw [mul_one, u₂.inv_val], by simpa only [mul_assoc]⟩ protected def inv' (u : units α) : units α := ⟨u.inv, u.val, u.inv_val, u.val_inv⟩ instance : has_mul (units α) := ⟨units.mul⟩ instance : has_one (units α) := ⟨⟨1, 1, mul_one 1, one_mul 1⟩⟩ instance : has_inv (units α) := ⟨units.inv'⟩ variables (a b) @[simp] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp] lemma coe_one : ((1 : units α) : α) = 1 := rfl lemma val_coe : (↑a : α) = a.val := rfl lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl @[simp] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[simp] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] instance : group (units α) := by refine {mul := (*), one := 1, inv := has_inv.inv, ..}; { intros, apply ext, simp only [coe_mul, coe_one, mul_assoc, one_mul, mul_one, inv_mul] } instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp] theorem mul_left_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp] theorem mul_right_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ end units theorem nat.units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_right_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_right_inj _ theorem divp_eq_one (a : α) (u : units α) : a /ₚ u = 1 ↔ a = u := (units.mul_right_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section group variables [group α] instance : has_lift α (units α) := ⟨λ a, ⟨a, a⁻¹, mul_inv_self _, inv_mul_self _⟩⟩ end group
f3aabc269700985b74df149bc0cd3257763f429b
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level17.lean
fdceea6b0f0a7b16a5e297101026a26a707befba
[ "Apache-2.0" ]
permissive
agusakov/mathematics_in_lean_game
76e455a688a8826b05160c16c0490b9e3d39f071
ad45fd42148f2203b973537adec7e8a48677ba2a
refs/heads/master
1,666,147,402,274
1,592,119,137,000
1,592,119,137,000
272,111,226
0
0
null
null
null
null
UTF-8
Lean
false
false
895
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- #Calculating ## Level 15: Rewriting at hypothesis, `exact` tactic We can also perform rewriting in an assumption in the context. For example, `rw mul_comm a b at hyp` replaces `a*b` by `b*a` in the assumption `hyp`. -/ variables a b c d : ℝ /- Lemma : no-side-bar For all natural numbers $a$, we have $$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$ -/ lemma example17 (a b c d : ℝ) (hyp : c = d * a + b) (hyp' : b = a * d) : c = 2 * a * d := begin [maths_in_lean_game] rw hyp' at hyp, rw mul_comm d a at hyp, rw ← two_mul (a*d) at hyp, rw ← mul_assoc 2 a d at hyp, exact hyp end /- In the last step, the `exact` tactic can use `hyp` to solve the goal because at that point `hyp` matches the goal exactly. -/ end calculating -- hide
cb3dc25292745bb1a1c0b0e85b65912b3c6329a3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/preserves/shapes/terminal_auto.lean
118369f6feb406dfadcdc4e920520df6ebf5ba7b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,603
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.preserves.limits import Mathlib.category_theory.limits.shapes.default import Mathlib.PostPort universes u₁ u₂ v namespace Mathlib /-! # Preserving terminal object Constructions to relate the notions of preserving terminal objects and reflecting terminal objects to concrete objects. In particular, we show that `terminal_comparison G` is an isomorphism iff `G` preserves terminal objects. -/ namespace category_theory.limits /-- The map of an empty cone is a limit iff the mapped object is terminal. -/ def is_limit_map_cone_empty_cone_equiv {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (X : C) : is_limit (functor.map_cone G (as_empty_cone X)) ≃ is_terminal (functor.obj G X) := equiv.trans (equiv.symm (is_limit.postcompose_hom_equiv (functor.empty_ext (functor.empty C ⋙ G) (functor.empty D)) (functor.map_cone G (as_empty_cone X)))) (is_limit.equiv_iso_limit (cones.ext (iso.refl (cone.X (functor.obj (cones.postcompose (iso.hom (functor.empty_ext (functor.empty C ⋙ G) (functor.empty D)))) (functor.map_cone G (as_empty_cone X))))) sorry)) /-- The property of preserving terminal objects expressed in terms of `is_terminal`. -/ def is_terminal_obj_of_is_terminal {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (X : C) [preserves_limit (functor.empty C) G] (l : is_terminal X) : is_terminal (functor.obj G X) := coe_fn (is_limit_map_cone_empty_cone_equiv G X) (preserves_limit.preserves l) /-- The property of reflecting terminal objects expressed in terms of `is_terminal`. -/ def is_terminal_of_is_terminal_obj {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (X : C) [reflects_limit (functor.empty C) G] (l : is_terminal (functor.obj G X)) : is_terminal X := reflects_limit.reflects (coe_fn (equiv.symm (is_limit_map_cone_empty_cone_equiv G X)) l) /-- If `G` preserves the terminal object and `C` has a terminal object, then the image of the terminal object is terminal. -/ def is_limit_of_has_terminal_of_preserves_limit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [preserves_limit (functor.empty C) G] : is_terminal (functor.obj G (⊤_C)) := is_terminal_obj_of_is_terminal G (⊤_C) terminal_is_terminal /-- If `C` has a terminal object and `G` preserves terminal objects, then `D` has a terminal object also. Note this property is somewhat unique to (co)limits of the empty diagram: for general `J`, if `C` has limits of shape `J` and `G` preserves them, then `D` does not necessarily have limits of shape `J`. -/ theorem has_terminal_of_has_terminal_of_preserves_limit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [preserves_limit (functor.empty C) G] : has_terminal D := has_limits_of_shape.mk fun (F : discrete pempty ⥤ D) => has_limit_of_iso (iso.symm (functor.unique_from_empty F)) /-- If the terminal comparison map for `G` is an isomorphism, then `G` preserves terminal objects. -/ def preserves_terminal.of_iso_comparison {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] [i : is_iso (terminal_comparison G)] : preserves_limit (functor.empty C) G := preserves_limit_of_preserves_limit_cone terminal_is_terminal (coe_fn (equiv.symm (is_limit_map_cone_empty_cone_equiv G (⊤_C))) (is_limit.of_point_iso (limit.is_limit (functor.empty D)))) /-- If there is any isomorphism `G.obj ⊤ ⟶ ⊤`, then `G` preserves terminal objects. -/ def preserves_terminal_of_is_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] (f : functor.obj G (⊤_C) ⟶ ⊤_D) [i : is_iso f] : preserves_limit (functor.empty C) G := preserves_terminal.of_iso_comparison G /-- If there is any isomorphism `G.obj ⊤ ≅ ⊤`, then `G` preserves terminal objects. -/ def preserves_terminal_of_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] (f : functor.obj G (⊤_C) ≅ ⊤_D) : preserves_limit (functor.empty C) G := preserves_terminal_of_is_iso G (iso.hom f) /-- If `G` preserves terminal objects, then the terminal comparison map for `G` an isomorphism. -/ def preserves_terminal.iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] [preserves_limit (functor.empty C) G] : functor.obj G (⊤_C) ≅ ⊤_D := is_limit.cone_point_unique_up_to_iso (is_limit_of_has_terminal_of_preserves_limit G) (limit.is_limit (functor.empty D)) @[simp] theorem preserves_terminal.iso_hom {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] [preserves_limit (functor.empty C) G] : iso.hom (preserves_terminal.iso G) = terminal_comparison G := rfl protected instance terminal_comparison.category_theory.is_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] [preserves_limit (functor.empty C) G] : is_iso (terminal_comparison G) := eq.mpr sorry (is_iso.of_iso (preserves_terminal.iso G)) end Mathlib
7a00bd1a3a4b2cbd7d6395bff65be273c31f16f3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/init/pathover.hlean
3eeb044323648c92fd3f71a08262146b6b75984d
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
12,971
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Basic theorems about pathovers -/ prelude import .path .equiv open equiv is_equiv function variables {A A' : Type} {B B' : A → Type} {B'' : A' → Type} {C : Π⦃a⦄, B a → Type} {a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄} {p₁₃ : a = a₃} {b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄} {c : C b} {c₂ : C b₂} namespace eq inductive pathover.{l} (B : A → Type.{l}) (b : B a) : Π{a₂ : A}, a = a₂ → B a₂ → Type.{l} := idpatho : pathover B b (refl a) b notation b ` =[`:50 p:0 `] `:0 b₂:50 := pathover _ b p b₂ definition idpo [reducible] [constructor] : b =[refl a] b := pathover.idpatho b /- equivalences with equality using transport -/ definition pathover_of_tr_eq [unfold 5 8] (r : p ▸ b = b₂) : b =[p] b₂ := by cases p; cases r; constructor definition pathover_of_eq_tr [unfold 5 8] (r : b = p⁻¹ ▸ b₂) : b =[p] b₂ := by cases p; cases r; constructor definition tr_eq_of_pathover [unfold 8] (r : b =[p] b₂) : p ▸ b = b₂ := by cases r; reflexivity definition eq_tr_of_pathover [unfold 8] (r : b =[p] b₂) : b = p⁻¹ ▸ b₂ := by cases r; reflexivity definition pathover_equiv_tr_eq [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂) : (b =[p] b₂) ≃ (p ▸ b = b₂) := begin fapply equiv.MK, { exact tr_eq_of_pathover}, { exact pathover_of_tr_eq}, { intro r, cases p, cases r, apply idp}, { intro r, cases r, apply idp}, end definition pathover_equiv_eq_tr [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂) : (b =[p] b₂) ≃ (b = p⁻¹ ▸ b₂) := begin fapply equiv.MK, { exact eq_tr_of_pathover}, { exact pathover_of_eq_tr}, { intro r, cases p, cases r, apply idp}, { intro r, cases r, apply idp}, end definition pathover_tr [unfold 5] (p : a = a₂) (b : B a) : b =[p] p ▸ b := by cases p;constructor definition tr_pathover [unfold 5] (p : a = a₂) (b : B a₂) : p⁻¹ ▸ b =[p] b := by cases p;constructor definition concato [unfold 12] (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) : b =[p ⬝ p₂] b₃ := pathover.rec_on r₂ r definition inverseo [unfold 8] (r : b =[p] b₂) : b₂ =[p⁻¹] b := pathover.rec_on r idpo definition apdo [unfold 6] (f : Πa, B a) (p : a = a₂) : f a =[p] f a₂ := eq.rec_on p idpo definition concato_eq [unfold 10] (r : b =[p] b₂) (q : b₂ = b₂') : b =[p] b₂' := eq.rec_on q r definition eq_concato [unfold 9] (q : b = b') (r : b' =[p] b₂) : b =[p] b₂ := by induction q;exact r definition change_path [unfold 9] (q : p = p') (r : b =[p] b₂) : b =[p'] b₂ := q ▸ r -- infix ` ⬝ ` := concato infix ` ⬝o `:72 := concato infix ` ⬝op `:73 := concato_eq infix ` ⬝po `:73 := eq_concato -- postfix `⁻¹` := inverseo postfix `⁻¹ᵒ`:(max+10) := inverseo definition pathover_cancel_right (q : b =[p ⬝ p₂] b₃) (r : b₃ =[p₂⁻¹] b₂) : b =[p] b₂ := change_path !con_inv_cancel_right (q ⬝o r) definition pathover_cancel_right' (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) (r : b₂ =[p₂] b₃) : b =[p₁₃] b₃ := change_path !inv_con_cancel_right (q ⬝o r) definition pathover_cancel_left (q : b₂ =[p⁻¹] b) (r : b =[p ⬝ p₂] b₃) : b₂ =[p₂] b₃ := change_path !inv_con_cancel_left (q ⬝o r) definition pathover_cancel_left' (q : b =[p] b₂) (r : b₂ =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ := change_path !con_inv_cancel_left (q ⬝o r) /- Some of the theorems analogous to theorems for = in init.path -/ definition cono_idpo (r : b =[p] b₂) : r ⬝o idpo =[con_idp p] r := pathover.rec_on r idpo definition idpo_cono (r : b =[p] b₂) : idpo ⬝o r =[idp_con p] r := pathover.rec_on r idpo definition cono.assoc' (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) : r ⬝o (r₂ ⬝o r₃) =[!con.assoc'] (r ⬝o r₂) ⬝o r₃ := pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo)) definition cono.assoc (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) : (r ⬝o r₂) ⬝o r₃ =[!con.assoc] r ⬝o (r₂ ⬝o r₃) := pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo)) definition cono.right_inv (r : b =[p] b₂) : r ⬝o r⁻¹ᵒ =[!con.right_inv] idpo := pathover.rec_on r idpo definition cono.left_inv (r : b =[p] b₂) : r⁻¹ᵒ ⬝o r =[!con.left_inv] idpo := pathover.rec_on r idpo definition eq_of_pathover {a' a₂' : A'} (q : a' =[p] a₂') : a' = a₂' := by cases q;reflexivity definition pathover_of_eq [unfold 5 8] {a' a₂' : A'} (q : a' = a₂') : a' =[p] a₂' := by cases p;cases q;constructor definition pathover_constant [constructor] (p : a = a₂) (a' a₂' : A') : a' =[p] a₂' ≃ a' = a₂' := begin fapply equiv.MK, { exact eq_of_pathover}, { exact pathover_of_eq}, { intro r, cases p, cases r, reflexivity}, { intro r, cases r, reflexivity}, end definition eq_of_pathover_idp [unfold 6] {b' : B a} (q : b =[idpath a] b') : b = b' := tr_eq_of_pathover q --should B be explicit in the next two definitions? definition pathover_idp_of_eq [unfold 6] {b' : B a} (q : b = b') : b =[idpath a] b' := pathover_of_tr_eq q definition pathover_idp [constructor] (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' := equiv.MK eq_of_pathover_idp (pathover_idp_of_eq) (to_right_inv !pathover_equiv_tr_eq) (to_left_inv !pathover_equiv_tr_eq) -- definition pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' := -- pathover_equiv_tr_eq idp b b' -- definition eq_of_pathover_idp [reducible] {b' : B a} (q : b =[idpath a] b') : b = b' := -- to_fun !pathover_idp q -- definition pathover_idp_of_eq [reducible] {b' : B a} (q : b = b') : b =[idpath a] b' := -- to_inv !pathover_idp q definition idp_rec_on [recursor] {P : Π⦃b₂ : B a⦄, b =[idpath a] b₂ → Type} {b₂ : B a} (r : b =[idpath a] b₂) (H : P idpo) : P r := have H2 : P (pathover_idp_of_eq (eq_of_pathover_idp r)), from eq.rec_on (eq_of_pathover_idp r) H, proof left_inv !pathover_idp r ▸ H2 qed definition rec_on_right [recursor] {P : Π⦃b₂ : B a₂⦄, b =[p] b₂ → Type} {b₂ : B a₂} (r : b =[p] b₂) (H : P !pathover_tr) : P r := by cases r; exact H definition rec_on_left [recursor] {P : Π⦃b : B a⦄, b =[p] b₂ → Type} {b : B a} (r : b =[p] b₂) (H : P !tr_pathover) : P r := by cases r; exact H --pathover with fibration B' ∘ f definition pathover_ap [unfold 10] (B' : A' → Type) (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : b =[ap f p] b₂ := by cases q; constructor definition pathover_of_pathover_ap (B' : A' → Type) (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : b =[p] b₂ := by cases p; apply (idp_rec_on q); apply idpo definition pathover_compose [constructor] (B' : A' → Type) (f : A → A') (p : a = a₂) (b : B' (f a)) (b₂ : B' (f a₂)) : b =[p] b₂ ≃ b =[ap f p] b₂ := begin fapply equiv.MK, { exact pathover_ap B' f}, { exact pathover_of_pathover_ap B' f}, { intro q, cases p, esimp, apply (idp_rec_on q), apply idp}, { intro q, cases q, reflexivity}, end definition apdo_con (f : Πa, B a) (p : a = a₂) (q : a₂ = a₃) : apdo f (p ⬝ q) = apdo f p ⬝o apdo f q := by cases p; cases q; reflexivity definition apdo_inv (f : Πa, B a) (p : a = a₂) : apdo f p⁻¹ = (apdo f p)⁻¹ᵒ := by cases p; reflexivity definition apdo_eq_pathover_of_eq_ap (f : A → A') (p : a = a₂) : apdo f p = pathover_of_eq (ap f p) := eq.rec_on p idp definition pathover_of_pathover_tr (q : b =[p ⬝ p₂] p₂ ▸ b₂) : b =[p] b₂ := pathover_cancel_right q !pathover_tr⁻¹ᵒ definition pathover_tr_of_pathover (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) : b =[p₁₃] p₂ ▸ b₂ := pathover_cancel_right' q !pathover_tr definition pathover_of_tr_pathover (q : p ▸ b =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ := pathover_cancel_left' !pathover_tr q definition tr_pathover_of_pathover (q : b =[p ⬝ p₂] b₃) : p ▸ b =[p₂] b₃ := pathover_cancel_left !pathover_tr⁻¹ᵒ q definition pathover_tr_of_eq (q : b = b') : b =[p] p ▸ b' := by cases q;apply pathover_tr definition tr_pathover_of_eq (q : b₂ = b₂') : p⁻¹ ▸ b₂ =[p] b₂' := by cases q;apply tr_pathover variable (C) definition transporto (r : b =[p] b₂) (c : C b) : C b₂ := by induction r;exact c infix ` ▸o `:75 := transporto _ definition fn_tro_eq_tro_fn (C' : Π ⦃a : A⦄, B a → Type) (q : b =[p] b₂) (f : Π(b : B a), C b → C' b) (c : C b) : f b (q ▸o c) = (q ▸o (f b c)) := by induction q;reflexivity variable {C} definition apo {f : A → A'} (g : Πa, B a → B'' (f a)) (q : b =[p] b₂) : g a b =[p] g a₂ b₂ := by induction q; constructor definition apo011 [unfold 10] (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) : f a b = f a₂ b₂ := by cases Hb; reflexivity definition apo0111 (f : Πa b, C b → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) (Hc : c =[apo011 C Ha Hb] c₂) : f a b c = f a₂ b₂ c₂ := by cases Hb; apply (idp_rec_on Hc); apply idp definition apod11 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p] g) {b : B a} {b₂ : B a₂} (q : b =[p] b₂) : f b =[apo011 C p q] g b₂ := by cases r; apply (idp_rec_on q); constructor definition apdo10 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p] g) (b : B a) : f b =[apo011 C p !pathover_tr] g (p ▸ b) := by cases r; constructor definition apo10 [unfold 9] {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p] g) (b : B a) : f b =[p] g (p ▸ b) := by cases r; constructor definition apo10_constant_right [unfold 9] {f : B a → A'} {g : B a₂ → A'} (r : f =[p] g) (b : B a) : f b = g (p ▸ b) := by cases r; constructor definition apo10_constant_left [unfold 9] {f : A' → B a} {g : A' → B a₂} (r : f =[p] g) (a' : A') : f a' =[p] g a' := by cases r; constructor definition apo11 {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p] g) (q : b =[p] b₂) : f b =[p] g b₂ := by induction q; exact apo10 r b definition apdo_compose1 (g : Πa, B a → B' a) (f : Πa, B a) (p : a = a₂) : apdo (g ∘' f) p = apo g (apdo f p) := by induction p; reflexivity definition apdo_compose2 (g : Πa', B'' a') (f : A → A') (p : a = a₂) : apdo (λa, g (f a)) p = pathover_of_pathover_ap B'' f (apdo g (ap f p)) := by induction p; reflexivity definition cono.right_inv_eq (q : b = b') : concato_eq (pathover_idp_of_eq q) q⁻¹ = (idpo : b =[refl a] b) := by induction q;constructor definition cono.right_inv_eq' (q : b = b') : eq_concato q (pathover_idp_of_eq q⁻¹) = (idpo : b =[refl a] b) := by induction q;constructor definition cono.left_inv_eq (q : b = b') : concato_eq (pathover_idp_of_eq q⁻¹) q = (idpo : b' =[refl a] b') := by induction q;constructor definition cono.left_inv_eq' (q : b = b') : eq_concato q⁻¹ (pathover_idp_of_eq q) = (idpo : b' =[refl a] b') := by induction q;constructor definition pathover_of_fn_pathover_fn (f : Π{a}, B a ≃ B' a) (r : f b =[p] f b₂) : b =[p] b₂ := (left_inv f b)⁻¹ ⬝po apo (λa, f⁻¹ᵉ) r ⬝op left_inv f b₂ definition change_path_of_pathover (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) (q : r =[s] r') : change_path s r = r' := by induction s; eapply idp_rec_on q; reflexivity definition pathover_of_change_path (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) (q : change_path s r = r') : r =[s] r' := by induction s; induction q; constructor definition pathover_pathover_path [constructor] (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) : (r =[s] r') ≃ change_path s r = r' := begin fapply equiv.MK, { apply change_path_of_pathover}, { apply pathover_of_change_path}, { intro q, induction s, induction q, reflexivity}, { intro q, induction s, eapply idp_rec_on q, reflexivity}, end definition inverseo2 [unfold 10] {r r' : b =[p] b₂} (s : r = r') : r⁻¹ᵒ = r'⁻¹ᵒ := by induction s; reflexivity definition concato2 [unfold 15 16] {r r' : b =[p] b₂} {r₂ r₂' : b₂ =[p₂] b₃} (s : r = r') (s₂ : r₂ = r₂') : r ⬝o r₂ = r' ⬝o r₂' := by induction s; induction s₂; reflexivity infixl ` ◾o `:75 := concato2 postfix [parsing_only] `⁻²ᵒ`:(max+10) := inverseo2 --this notation is abusive, should we use it? end eq
dbd003e2bedf818dfbfe9d32782aec7524e5cafb
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/init/axioms/ua.hlean
8f5a2f20f61b8994e47a3d397a9663ae12d92852
[ "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
1,361
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.axioms.ua Author: Jakob von Raumer Ported from Coq HoTT -/ prelude import ..path ..equiv open eq equiv is_equiv --Ensure that the types compared are in the same universe section universe variable l variables {A B : Type.{l}} definition is_equiv_tr_of_eq (H : A = B) : is_equiv (transport (λX:Type, X) H) := (@is_equiv_tr Type (λX, X) A B H) definition equiv_of_eq (H : A = B) : A ≃ B := equiv.mk _ (is_equiv_tr_of_eq H) end axiom univalence (A B : Type) : is_equiv (@equiv_of_eq A B) attribute univalence [instance] -- This is the version of univalence axiom we will probably use most often definition ua {A B : Type} : A ≃ B → A = B := (@equiv_of_eq A B)⁻¹ -- One consequence of UA is that we can transport along equivalencies of types namespace equiv universe variable l protected definition transport_of_equiv (P : Type → Type) {A B : Type.{l}} (H : A ≃ B) : P A → P B := eq.transport P (ua H) -- We can use this for calculation evironments calc_subst transport_of_equiv definition rec_on_of_equiv_of_eq {A B : Type} {P : (A ≃ B) → Type} (p : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q)) : P p := retr equiv_of_eq p ▹ H (ua p) end equiv
17b1204ebfd73ed626f625feda046130bcc8dd2b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/field_theory/galois.lean
64290030cb06d9d91498584bc445e296ba489478
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,218
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.normal import field_theory.primitive_element import field_theory.fixed import ring_theory.power_basis /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `is_galois F E` where `E` is an extension of `F` - `fixed_field H` where `H : subgroup (E ≃ₐ[F] E)` - `fixing_subgroup K` where `K : intermediate_field F E` - `galois_correspondence` where `E/F` is finite dimensional and Galois ## Main results - `fixing_subgroup_of_fixed_field` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixing_subgroup (fixed_field H) = H` - `fixed_field_of_fixing_subgroup`: If `E/F` is finite dimensional and Galois then `fixed_field (fixing_subgroup K) = K` Together, these two result prove the Galois correspondence - `is_galois.tfae` : Equivalent characterizations of a Galois extension of finite degree -/ noncomputable theory open_locale classical open finite_dimensional alg_equiv section variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-- A field extension E/F is galois if it is both separable and normal -/ class is_galois : Prop := [to_is_separable : is_separable F E] [to_normal : normal F E] variables {F E} theorem is_galois_iff : is_galois F E ↔ is_separable F E ∧ normal F E := ⟨λ h, ⟨h.1, h.2⟩, λ h, { to_is_separable := h.1, to_normal := h.2 }⟩ attribute [instance, priority 100] -- see Note [lower instance priority] is_galois.to_is_separable is_galois.to_normal variables (F E) namespace is_galois instance self : is_galois F F := ⟨⟩ variables (F) {E} lemma integral [is_galois F E] (x : E) : is_integral F x := normal.is_integral' x lemma separable [is_galois F E] (x : E) : (minpoly F x).separable := is_separable.separable F x lemma splits [is_galois F E] (x : E) : (minpoly F x).splits (algebra_map F E) := normal.splits' x variables (F E) instance of_fixed_field (G : Type*) [group G] [fintype G] [mul_semiring_action G E] : is_galois (fixed_points.subfield G E) E := ⟨⟩ lemma intermediate_field.adjoin_simple.card_aut_eq_finrank [finite_dimensional F E] {α : E} (hα : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F F⟮α⟯)) : fintype.card (F⟮α⟯ ≃ₐ[F] F⟮α⟯) = finrank F F⟮α⟯ := begin letI : fintype (F⟮α⟯ →ₐ[F] F⟮α⟯) := intermediate_field.fintype_of_alg_hom_adjoin_integral F hα, rw intermediate_field.adjoin.finrank hα, rw ← intermediate_field.card_alg_hom_adjoin_integral F hα h_sep h_splits, exact fintype.card_congr (alg_equiv_equiv_alg_hom F F⟮α⟯) end lemma card_aut_eq_finrank [finite_dimensional F E] [is_galois F E] : fintype.card (E ≃ₐ[F] E) = finrank F E := begin cases field.exists_primitive_element F E with α hα, let iso : F⟮α⟯ ≃ₐ[F] E := { to_fun := λ e, e.val, inv_fun := λ e, ⟨e, by { rw hα, exact intermediate_field.mem_top }⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, rfl, map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, commutes' := λ _, rfl }, have H : is_integral F α := is_galois.integral F α, have h_sep : (minpoly F α).separable := is_galois.separable F α, have h_splits : (minpoly F α).splits (algebra_map F E) := is_galois.splits F α, replace h_splits : polynomial.splits (algebra_map F F⟮α⟯) (minpoly F α), { have p : iso.symm.to_alg_hom.to_ring_hom.comp (algebra_map F E) = (algebra_map F ↥F⟮α⟯), { ext, simp, }, simpa [p] using polynomial.splits_comp_of_splits (algebra_map F E) iso.symm.to_alg_hom.to_ring_hom h_splits, }, rw ← linear_equiv.finrank_eq iso.to_linear_equiv, rw ← intermediate_field.adjoin_simple.card_aut_eq_finrank F E H h_sep h_splits, apply fintype.card_congr, apply equiv.mk (λ ϕ, iso.trans (trans ϕ iso.symm)) (λ ϕ, iso.symm.trans (trans ϕ iso)), { intro ϕ, ext1, simp only [trans_apply, apply_symm_apply] }, { intro ϕ, ext1, simp only [trans_apply, symm_apply_apply] }, end end is_galois end section is_galois_tower variables (F K E : Type*) [field F] [field K] [field E] {E' : Type*} [field E'] [algebra F E'] variables [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_galois.tower_top_of_is_galois [is_galois F E] : is_galois K E := { to_is_separable := is_separable_tower_top_of_is_separable F K E, to_normal := normal.tower_top_of_normal F K E } variables {F E} @[priority 100] -- see Note [lower instance priority] instance is_galois.tower_top_intermediate_field (K : intermediate_field F E) [h : is_galois F E] : is_galois K E := is_galois.tower_top_of_is_galois F K E lemma is_galois_iff_is_galois_bot : is_galois (⊥ : intermediate_field F E) E ↔ is_galois F E := begin split, { introI h, exact is_galois.tower_top_of_is_galois (⊥ : intermediate_field F E) F E }, { introI h, apply_instance }, end lemma is_galois.of_alg_equiv [h : is_galois F E] (f : E ≃ₐ[F] E') : is_galois F E' := { to_is_separable := is_separable.of_alg_hom F E f.symm, to_normal := normal.of_alg_equiv f } lemma alg_equiv.transfer_galois (f : E ≃ₐ[F] E') : is_galois F E ↔ is_galois F E' := ⟨λ h, by exactI is_galois.of_alg_equiv f, λ h, by exactI is_galois.of_alg_equiv f.symm⟩ lemma is_galois_iff_is_galois_top : is_galois F (⊤ : intermediate_field F E) ↔ is_galois F E := (intermediate_field.top_equiv).transfer_galois instance is_galois_bot : is_galois F (⊥ : intermediate_field F E) := (intermediate_field.bot_equiv F E).transfer_galois.mpr (is_galois.self F) end is_galois_tower section galois_correspondence variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] variables (H : subgroup (E ≃ₐ[F] E)) (K : intermediate_field F E) namespace intermediate_field /-- The intermediate_field fixed by a subgroup -/ def fixed_field : intermediate_field F E := { carrier := mul_action.fixed_points H E, zero_mem' := λ g, smul_zero g, add_mem' := λ a b hx hy g, by rw [smul_add g a b, hx, hy], neg_mem' := λ a hx g, by rw [smul_neg g a, hx], one_mem' := λ g, smul_one g, mul_mem' := λ a b hx hy g, by rw [smul_mul' g a b, hx, hy], inv_mem' := λ a hx g, by rw [smul_inv'' g a, hx], algebra_map_mem' := λ a g, commutes g a } lemma finrank_fixed_field_eq_card [finite_dimensional F E] : finrank (fixed_field H) E = fintype.card H := fixed_points.finrank_eq_card H E /-- The subgroup fixing an intermediate_field -/ def fixing_subgroup : subgroup (E ≃ₐ[F] E) := { carrier := λ ϕ, ∀ x : K, ϕ x = x, one_mem' := λ _, rfl, mul_mem' := λ _ _ hx hy _, (congr_arg _ (hy _)).trans (hx _), inv_mem' := λ _ hx _, (equiv.symm_apply_eq (to_equiv _)).mpr (hx _).symm } lemma le_iff_le : K ≤ fixed_field H ↔ H ≤ fixing_subgroup K := ⟨λ h g hg x, h (subtype.mem x) ⟨g, hg⟩, λ h x hx g, h (subtype.mem g) ⟨x, hx⟩⟩ /-- The fixing_subgroup of `K : intermediate_field F E` is isomorphic to `E ≃ₐ[K] E` -/ def fixing_subgroup_equiv : fixing_subgroup K ≃* (E ≃ₐ[K] E) := { to_fun := λ ϕ, of_bijective (alg_hom.mk ϕ (map_one ϕ) (map_mul ϕ) (map_zero ϕ) (map_add ϕ) (ϕ.mem)) (bijective ϕ), inv_fun := λ ϕ, ⟨of_bijective (alg_hom.mk ϕ (ϕ.map_one) (ϕ.map_mul) (ϕ.map_zero) (ϕ.map_add) (λ r, ϕ.commutes (algebra_map F K r))) (ϕ.bijective), ϕ.commutes⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl }, map_mul' := λ _ _, by { ext, refl } } theorem fixing_subgroup_fixed_field [finite_dimensional F E] : fixing_subgroup (fixed_field H) = H := begin have H_le : H ≤ (fixing_subgroup (fixed_field H)) := (le_iff_le _ _).mp (le_refl _), suffices : fintype.card H = fintype.card (fixing_subgroup (fixed_field H)), { exact set_like.coe_injective (set.eq_of_inclusion_surjective ((fintype.bijective_iff_injective_and_card (set.inclusion H_le)).mpr ⟨set.inclusion_injective H_le, this⟩).2).symm }, apply fintype.card_congr, refine (fixed_points.to_alg_hom_equiv H E).trans _, refine (alg_equiv_equiv_alg_hom (fixed_field H) E).symm.trans _, exact (fixing_subgroup_equiv (fixed_field H)).to_equiv.symm end instance fixed_field.algebra : algebra K (fixed_field (fixing_subgroup K)) := { smul := λ x y, ⟨x*y, λ ϕ, by rw [smul_mul', (show ϕ • ↑x = ↑x, by exact subtype.mem ϕ x), (show ϕ • ↑y = ↑y, by exact subtype.mem y ϕ)]⟩, to_fun := λ x, ⟨x, λ ϕ, subtype.mem ϕ x⟩, map_zero' := rfl, map_add' := λ _ _, rfl, map_one' := rfl, map_mul' := λ _ _, rfl, commutes' := λ _ _, mul_comm _ _, smul_def' := λ _ _, rfl } instance fixed_field.is_scalar_tower : is_scalar_tower K (fixed_field (fixing_subgroup K)) E := ⟨λ _ _ _, mul_assoc _ _ _⟩ end intermediate_field namespace is_galois theorem fixed_field_fixing_subgroup [finite_dimensional F E] [h : is_galois F E] : intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) = K := begin have K_le : K ≤ intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) := (intermediate_field.le_iff_le _ _).mpr (le_refl _), suffices : finrank K E = finrank (intermediate_field.fixed_field (intermediate_field.fixing_subgroup K)) E, { exact (intermediate_field.eq_of_le_of_finrank_eq' K_le this).symm }, rw [intermediate_field.finrank_fixed_field_eq_card, fintype.card_congr (intermediate_field.fixing_subgroup_equiv K).to_equiv], exact (card_aut_eq_finrank K E).symm, end lemma card_fixing_subgroup_eq_finrank [finite_dimensional F E] [is_galois F E] : fintype.card (intermediate_field.fixing_subgroup K) = finrank K E := by conv { to_rhs, rw [←fixed_field_fixing_subgroup K, intermediate_field.finrank_fixed_field_eq_card] } /-- The Galois correspondence from intermediate fields to subgroups -/ def intermediate_field_equiv_subgroup [finite_dimensional F E] [is_galois F E] : intermediate_field F E ≃o order_dual (subgroup (E ≃ₐ[F] E)) := { to_fun := intermediate_field.fixing_subgroup, inv_fun := intermediate_field.fixed_field, left_inv := λ K, fixed_field_fixing_subgroup K, right_inv := λ H, intermediate_field.fixing_subgroup_fixed_field H, map_rel_iff' := λ K L, by { rw [←fixed_field_fixing_subgroup L, intermediate_field.le_iff_le, fixed_field_fixing_subgroup L, ←order_dual.dual_le], refl } } /-- The Galois correspondence as a galois_insertion -/ def galois_insertion_intermediate_field_subgroup [finite_dimensional F E] : galois_insertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ K _, intermediate_field.fixing_subgroup K, gc := λ K H, (intermediate_field.le_iff_le H K).symm, le_l_u := λ H, le_of_eq (intermediate_field.fixing_subgroup_fixed_field H).symm, choice_eq := λ K _, rfl } /-- The Galois correspondence as a galois_coinsertion -/ def galois_coinsertion_intermediate_field_subgroup [finite_dimensional F E] [is_galois F E] : galois_coinsertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ H _, intermediate_field.fixed_field H, gc := λ K H, (intermediate_field.le_iff_le H K).symm, u_l_le := λ K, le_of_eq (fixed_field_fixing_subgroup K), choice_eq := λ H _, rfl } end is_galois end galois_correspondence section galois_equivalent_definitions variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] namespace is_galois lemma is_separable_splitting_field [finite_dimensional F E] [is_galois F E] : ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E := begin cases field.exists_primitive_element F E with α h1, use [minpoly F α, separable F α, is_galois.splits F α], rw [eq_top_iff, ←intermediate_field.top_to_subalgebra, ←h1], rw intermediate_field.adjoin_simple_to_subalgebra_of_integral F α (integral F α), apply algebra.adjoin_mono, rw [set.singleton_subset_iff, finset.mem_coe, multiset.mem_to_finset, polynomial.mem_roots], { dsimp only [polynomial.is_root], rw [polynomial.eval_map, ←polynomial.aeval_def], exact minpoly.aeval _ _ }, { exact polynomial.map_ne_zero (minpoly.ne_zero (integral F α)) } end lemma of_fixed_field_eq_bot [finite_dimensional F E] (h : intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥) : is_galois F E := begin rw [←is_galois_iff_is_galois_bot, ←h], exact is_galois.of_fixed_field E (⊤ : subgroup (E ≃ₐ[F] E)), end lemma of_card_aut_eq_finrank [finite_dimensional F E] (h : fintype.card (E ≃ₐ[F] E) = finrank F E) : is_galois F E := begin apply of_fixed_field_eq_bot, have p : 0 < finrank (intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E))) E := finrank_pos, rw [←intermediate_field.finrank_eq_one_iff, ←mul_left_inj' (ne_of_lt p).symm, finrank_mul_finrank, ←h, one_mul, intermediate_field.finrank_fixed_field_eq_card], apply fintype.card_congr, exact { to_fun := λ g, ⟨g, subgroup.mem_top g⟩, inv_fun := coe, left_inv := λ g, rfl, right_inv := λ _, by { ext, refl } }, end variables {F} {E} {p : polynomial F} lemma of_separable_splitting_field_aux [hFE : finite_dimensional F E] [sp : p.is_splitting_field F E] (hp : p.separable) (K : intermediate_field F E) {x : E} (hx : x ∈ (p.map (algebra_map F E)).roots) : fintype.card ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) = fintype.card (K →ₐ[F] E) * finrank K K⟮x⟯ := begin have h : is_integral K x := is_integral_of_is_scalar_tower x (is_integral_of_noetherian hFE x), have h1 : p ≠ 0 := λ hp, by rwa [hp, polynomial.map_zero, polynomial.roots_zero] at hx, have h2 : (minpoly K x) ∣ p.map (algebra_map F K), { apply minpoly.dvd, rw [polynomial.aeval_def, polynomial.eval₂_map, ←polynomial.eval_map], exact (polynomial.mem_roots (polynomial.map_ne_zero h1)).mp hx }, let key_equiv : ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) ≃ Σ (f : K →ₐ[F] E), @alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f) := equiv.trans (alg_equiv.arrow_congr (intermediate_field.lift2_alg_equiv K⟮x⟯) (alg_equiv.refl)) alg_hom_equiv_sigma, haveI : Π (f : K →ₐ[F] E), fintype (@alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f)) := λ f, by { apply fintype.of_injective (sigma.mk f) (λ _ _ H, eq_of_heq ((sigma.mk.inj H).2)), exact fintype.of_equiv _ key_equiv }, rw [fintype.card_congr key_equiv, fintype.card_sigma, intermediate_field.adjoin.finrank h], apply finset.sum_const_nat, intros f hf, rw ← @intermediate_field.card_alg_hom_adjoin_integral K _ E _ _ x E _ (ring_hom.to_algebra f) h, { apply fintype.card_congr, refl }, { exact polynomial.separable.of_dvd ((polynomial.separable_map (algebra_map F K)).mpr hp) h2 }, { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero h1) _ h2, rw [polynomial.splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact sp.splits }, end lemma of_separable_splitting_field [sp : p.is_splitting_field F E] (hp : p.separable) : is_galois F E := begin haveI hFE : finite_dimensional F E := polynomial.is_splitting_field.finite_dimensional E p, let s := (p.map (algebra_map F E)).roots.to_finset, have adjoin_root : intermediate_field.adjoin F ↑s = ⊤, { apply intermediate_field.to_subalgebra_injective, rw [intermediate_field.top_to_subalgebra, ←top_le_iff, ←sp.adjoin_roots], apply intermediate_field.algebra_adjoin_le_adjoin, }, let P : intermediate_field F E → Prop := λ K, fintype.card (K →ₐ[F] E) = finrank F K, suffices : P (intermediate_field.adjoin F ↑s), { rw adjoin_root at this, apply of_card_aut_eq_finrank, rw ← eq.trans this (linear_equiv.finrank_eq intermediate_field.top_equiv.to_linear_equiv), exact fintype.card_congr (equiv.trans (alg_equiv_equiv_alg_hom F E) (alg_equiv.arrow_congr intermediate_field.top_equiv.symm alg_equiv.refl)) }, apply intermediate_field.induction_on_adjoin_finset s P, { have key := intermediate_field.card_alg_hom_adjoin_integral F (show is_integral F (0 : E), by exact is_integral_zero), rw [minpoly.zero, polynomial.nat_degree_X] at key, specialize key polynomial.separable_X (polynomial.splits_X (algebra_map F E)), rw [←@subalgebra.finrank_bot F E _ _ _, ←intermediate_field.bot_to_subalgebra] at key, refine eq.trans _ key, apply fintype.card_congr, rw intermediate_field.adjoin_zero }, intros K x hx hK, simp only [P] at *, rw [of_separable_splitting_field_aux hp K (multiset.mem_to_finset.mp hx), hK, finrank_mul_finrank], exact (linear_equiv.finrank_eq (intermediate_field.lift2_alg_equiv K⟮x⟯).to_linear_equiv).symm, end /--Equivalent characterizations of a Galois extension of finite degree-/ theorem tfae [finite_dimensional F E] : tfae [is_galois F E, intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥, fintype.card (E ≃ₐ[F] E) = finrank F E, ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E] := begin tfae_have : 1 → 2, { exact λ h, order_iso.map_bot (@intermediate_field_equiv_subgroup F _ E _ _ _ h).symm }, tfae_have : 1 → 3, { introI _, exact card_aut_eq_finrank F E }, tfae_have : 1 → 4, { introI _, exact is_separable_splitting_field F E }, tfae_have : 2 → 1, { exact of_fixed_field_eq_bot F E }, tfae_have : 3 → 1, { exact of_card_aut_eq_finrank F E }, tfae_have : 4 → 1, { rintros ⟨h, hp1, _⟩, exactI of_separable_splitting_field hp1 }, tfae_finish, end end is_galois end galois_equivalent_definitions
553f54a04dfc1c110605e2d42ec2f7a9582e3c62
eb9357a70318e50e095b58730bebfe0cffee457f
/lean/love04_functional_programming_exercise_sheet.lean
c752bdd23a0eea76f31a3f1c679675974109f184
[]
no_license
Vierkantor/logical_verification_2021
7485dd916953131d501760f023d5b30fbb74d36a
9500b9c194e22a9ab4067321cfed7a1f445afcfc
refs/heads/main
1,692,560,845,086
1,624,721,275,000
1,624,721,275,000
416,354,079
0
0
null
null
null
null
UTF-8
Lean
false
false
5,455
lean
import .love03_forward_proofs_demo /-! # LoVe Exercise 4: Functional Programming -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /-! ## Question 1: Reverse of a List We define a new accumulator-based version of `reverse`. The first argument, `as`, serves as the accumulator. This definition is __tail-recursive__, meaning that compilers and interpreters can easily optimize the recursion away, resulting in more efficient code. -/ def accurev {α : Type} : list α → list α → list α | as [] := as | as (x :: xs) := accurev (x :: as) xs /-! 1.1. Our intention is that `accurev [] xs` should be equal to `reverse xs`. But if we start an induction, we quickly see that the induction hypothesis is not strong enough. Start by proving the following generalization (using the `induction'` tactic or pattern matching): -/ lemma accurev_eq_reverse_append {α : Type} : ∀as xs : list α, accurev as xs = reverse xs ++ as := sorry /-! 1.2. Derive the desired equation. -/ lemma accurev_eq_reverse {α : Type} (xs : list α) : accurev [] xs = reverse xs := sorry /-! 1.3. Prove the following property. Hint: A one-line inductionless proof is possible. -/ lemma accurev_accurev {α : Type} (xs : list α) : accurev [] (accurev [] xs) = xs := sorry /-! 1.4. Prove the following lemma by structural induction, as a "paper" proof. This is a good exercise to develop a deeper understanding of how structural induction works (and is good practice for the final exam). lemma accurev_eq_reverse_append {α : Type} : ∀as xs : list α, accurev as xs = reverse xs ++ as Guidelines for paper proofs: We expect detailed, rigorous, mathematical proofs. You are welcome to use standard mathematical notation or Lean structured commands (e.g., `assume`, `have`, `show`, `calc`). You can also use tactical proofs (e.g., `intro`, `apply`), but then please indicate some of the intermediate goals, so that we can follow the chain of reasoning. Major proof steps, including applications of induction and invocation of the induction hypothesis, must be stated explicitly. For each case of a proof by induction, you must list the inductive hypotheses assumed (if any) and the goal to be proved. Minor proof steps corresponding to `refl`, `simp`, or `cc` need not be justified if you think they are obvious (to humans), but you should say which key lemmas they depend on. You should be explicit whenever you use a function definition or an introduction rule for an inductive predicate. -/ -- enter your paper proof here /-! ## Question 2: Drop and Take The `drop` function removes the first `n` elements from the front of a list. -/ def drop {α : Type} : ℕ → list α → list α | 0 xs := xs | (_ + 1) [] := [] | (m + 1) (x :: xs) := drop m xs /-! 2.1. Define the `take` function, which returns a list consisting of the the first `n` elements at the front of a list. To avoid unpleasant surprises in the proofs, we recommend that you follow the same recursion pattern as for `drop` above. -/ def take {α : Type} : ℕ → list α → list α := sorry #eval take 0 [3, 7, 11] -- expected: [] #eval take 1 [3, 7, 11] -- expected: [3] #eval take 2 [3, 7, 11] -- expected: [3, 7] #eval take 3 [3, 7, 11] -- expected: [3, 7, 11] #eval take 4 [3, 7, 11] -- expected: [3, 7, 11] #eval take 2 ["a", "b", "c"] -- expected: ["a", "b"] /-! 2.2. Prove the following lemmas, using `induction'` or pattern matching. Notice that they are registered as simplification rules thanks to the `@[simp]` attribute. -/ @[simp] lemma drop_nil {α : Type} : ∀n : ℕ, drop n ([] : list α) = [] := sorry @[simp] lemma take_nil {α : Type} : ∀n : ℕ, take n ([] : list α) = [] := sorry /-! 2.3. Follow the recursion pattern of `drop` and `take` to prove the following lemmas. In other words, for each lemma, there should be three cases, and the third case will need to invoke the induction hypothesis. Hint: Note that there are three variables in the `drop_drop` lemma (but only two arguments to `drop`). For the third case, `←add_assoc` might be useful. -/ lemma drop_drop {α : Type} : ∀(m n : ℕ) (xs : list α), drop n (drop m xs) = drop (n + m) xs | 0 n xs := by refl -- supply the two missing cases here lemma take_take {α : Type} : ∀(m : ℕ) (xs : list α), take m (take m xs) = take m xs := sorry lemma take_drop {α : Type} : ∀(n : ℕ) (xs : list α), take n xs ++ drop n xs = xs := sorry /-! ## Question 3: A Type of λ-Terms 3.1. Define an inductive type corresponding to the untyped λ-terms, as given by the following context-free grammar: term ::= 'var' string -- variable (e.g., `x`) | 'lam' string term -- λ-expression (e.g., `λx, t`) | 'app' term term -- application (e.g., `t u`) -/ -- enter your definition here /-! 3.2. Register a textual representation of the type `term` as an instance of the `has_repr` type class. Make sure to supply enough parentheses to guarantee that the output is unambiguous. -/ def term.repr : term → string -- enter your answer here @[instance] def term.has_repr : has_repr term := { repr := term.repr } /-! 3.3. Test your textual representation. The following command should print something like `(λx, ((y x) x))`. -/ #eval (term.lam "x" (term.app (term.app (term.var "y") (term.var "x")) (term.var "x"))) end LoVe
a17e8e5749204b248353e4ba1aaaac750255bf21
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/meta/tactic.lean
024cc137abe86106346f8472c5ddb4c4aeda3a01
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
31,257
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic meta constant tactic_state : Type universe variables u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta inductive tactic_result (α : Type u) | success : α → tactic_state → tactic_result | exception : (unit → format) → option expr → tactic_state → tactic_result open tactic_result section variables {α : Type u} variables [has_to_string α] meta def tactic_result_to_string : tactic_result α → string | (success a s) := to_string a | (exception .α t ref s) := "Exception: " ++ to_string (t ()) meta instance : has_to_string (tactic_result α) := ⟨tactic_result_to_string⟩ end attribute [reducible] meta def tactic (α : Type u) := tactic_state → tactic_result α section variables {α : Type u} {β : Type v} @[inline] meta def tactic_fmap (f : α → β) (t : tactic α) : tactic β := λ s, tactic_result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception β e s') @[inline] meta def tactic_bind (t₁ : tactic α) (t₂ : α → tactic β) : tactic β := λ s, tactic_result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception β e s') @[inline] meta def tactic_return (a : α) : tactic α := λ s, success a s meta def tactic_orelse {α : Type u} (t₁ t₂ : tactic α) : tactic α := λ s, tactic_result.cases_on (t₁ s) success (λ e₁ ref₁ s', tactic_result.cases_on (t₂ s) success (exception α)) @[inline] meta def tactic_seq (t₁ : tactic α) (t₂ : tactic β) : tactic β := tactic_bind t₁ (λ a, t₂) infixl ` >>=[tactic] `:2 := tactic_bind infixl ` >>[tactic] `:2 := tactic_seq end meta instance : monad tactic := {map := @tactic_fmap, ret := @tactic_return, bind := @tactic_bind} meta def tactic.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := λ s, exception α (λ u, to_fmt msg) none s meta def tactic.failed {α : Type u} : tactic α := tactic.fail "failed" meta instance : alternative tactic := ⟨@tactic_fmap, (λ α a s, success a s), (@fapp _ _), @tactic.failed, @tactic_orelse⟩ meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception .α t ref s := exception (ulift α) t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception .(ulift α) t ref s := exception α t ref s end namespace tactic variables {α : Type u} meta def try (t : tactic α) : tactic unit := λ s, tactic_result.cases_on (t s) (λ a, success ()) (λ e ref s', success () s) meta def skip : tactic unit := success () meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, tactic_result.cases_on (t s) (λ a s, exception _ (λ _, to_fmt "fail_if_success combinator failed, given tactic succeeded") none s) (λ e ref s', success () s) open list meta def foreach : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, foreach es fn open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnex {α : Type 1} (e : exceptional α) : tactic α := λ s, match e with | (exceptional.success a) := tactic_result.success a s | (exceptional.exception .α f) := tactic_result.exception α (λ u, f options.mk) none s -- TODO(Leo): extract options from environment end meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := tactic_result.success a s | none := tactic_result.exception α (λ u, to_fmt "failed") none s end /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, tactic_result.cases_on (t s) success (λ e, exception α (λ u, msg ++ format.nest 2 (format.line ++ e u))) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta def list_to_tactic_format_aux {α : Type u} [has_to_tactic_format α] : bool → list α → tactic format | b [] := return $ to_fmt "" | b (x::xs) := do f₁ ← pp x, f₂ ← list_to_tactic_format_aux ff xs, return $ (if ¬ b then to_fmt "," ++ line else nil) ++ f₁ ++ f₂ meta def list_to_tactic_format {α : Type u} [has_to_tactic_format α] : list α → tactic format | [] := return $ to_fmt "[]" | (x::xs) := do f ← list_to_tactic_format_aux tt (x::xs), return $ to_fmt "[" ++ group (nest 1 f) ++ to_fmt "]" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨list_to_tactic_format⟩ meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, returnex $ environment.get (env s) n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := take state, trace_call_stack (λ u, success u state) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s meta def get_options : tactic options := do s ← read, return s^.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s^.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a inductive transparency | all | semireducible | reducible | none export transparency (reducible semireducible) /- (eval_expr α α_as_expr e) evaluates 'e' IF 'e' has type 'α'. 'α' must be a closed term. 'α_as_expr' is synthesized by the code generator. 'e' must be a closed expression at runtime. -/ meta constant eval_expr (α : Type u) {α_expr : pexpr} : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit meta constant rename : name → name → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat meta constant whnf_core : transparency → expr → tactic expr /- eta expand the given expression -/ meta constant eta_expand : expr → tactic expr /- beta reduction -/ meta constant beta : expr → tactic expr /- zeta reduction -/ meta constant zeta : expr → tactic expr /- eta reduction -/ meta constant eta : expr → tactic expr meta constant unify_core : transparency → expr → expr → tactic unit /- is_def_eq_core is similar to unify_core, but it treats metavariables as constants. -/ meta constant is_def_eq_core : transparency → expr → expr → tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic expr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type 1 real : Type 1 vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n then mk_app_core semireducible "rel" [f, g] returns the application rel.{1 2} nat (fun n : nat, vec real n) f g -/ meta constant mk_app_core : transparency → name → list expr → tactic expr /- Similar to mk_app, but allows to specify which arguments are explicit/implicit. Example, given a b : nat then mk_mapp_core semireducible "ite" [some (a > b), none, none, some a, some b] returns the application @ite.{1} (a > b) (nat.decidable_gt a b) nat a b -/ meta constant mk_mapp_core : transparency → name → list (option expr) → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit meta constant exact_core : transparency → expr → tactic unit /- Elaborate the given quoted expression with respect to the current main goal. If the boolean argument is tt, then metavariables are tolerated and become new goals. -/ meta constant to_expr_core : bool → pexpr → tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/ meta constant assert_core : name → expr → tactic unit /- (assertv_core H T P), change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/ meta constant define_core : name → expr → tactic unit /- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /- (apply_core t approx all insts e), apply the expression e to the main goal, the unification is performed using the given transparency mode. If approx is tt, then fallback to first-order unification, and approximate context during unification. If all is tt, then all unassigned meta-variables are added as new goals. If insts is tt, then use type class resolution to instantiate unassigned meta-variables. -/ meta constant apply_core : transparency → bool → bool → bool → expr → tactic unit /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- (induction_core m H rec ns) induction on H using recursor rec, names for the new hypotheses are retrieved from ns. If ns does not have sufficient names, then use the internal binder names in the recursor. -/ meta constant induction_core : transparency → expr → name → list name → tactic unit /- (cases_core m H ns) apply cases_on recursor, names for the new hypotheses are retrieved from ns. H must be a local constant -/ meta constant cases_core : transparency → expr → list name → tactic unit /- (destruct_core m e) similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct_core : transparency → expr → tactic unit /- (generalize_core m e n) -/ meta constant generalize_core : transparency → expr → name → tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit meta constant module_doc_strings : tactic (list (option name × string)) /- (set_basic_attribute_core attr_name c_name persistent prio) set attribute attr_name for constant c_name with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute_core : name → name → bool → option nat → tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat meta def set_basic_attribute : name → name → bool → tactic unit := λ a n p, set_basic_attribute_core a n p none /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute_core attr_name tgt p (some prio) /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info : expr → expr → tactic unit /- Return list of currently opened namespace -/ meta constant open_namespaces : tactic (list name) open list nat /- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (to_bool (t = expr.prop)) meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf : expr → tactic expr := whnf_core semireducible meta def whnf_no_delta : expr → tactic expr := whnf_core transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ /- Remark: the unit argument is a trick to allow us to write a recursive definition. Lean3 only allows recursive functions when "equations" are used. -/ meta def intros_core : unit → tactic (list expr) | u := do t ← target, match t with | (expr.pi n bi d b) := do H ← intro1, Hs ← intros_core u, return (H :: Hs) | (expr.elet n t v b) := do H ← intro1, Hs ← intros_core u, return (H :: Hs) | e := return [] end meta def intros : tactic (list expr) := intros_core () meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) meta def mk_app : name → list expr → tactic expr := mk_app_core semireducible meta def mk_mapp : name → list (option expr) → tactic expr := mk_mapp_core semireducible meta def to_expr : pexpr → tactic expr := to_expr_core tt meta def to_expr_strict : pexpr → tactic expr := to_expr_core ff meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def unify : expr → expr → tactic unit := unify_core semireducible meta def is_def_eq : expr → expr → tactic unit := is_def_eq_core semireducible meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e^.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def exact : expr → tactic unit := exact_core semireducible meta def rexact : expr → tactic unit := exact_core reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : tactic unit := assert_core h t >> swap >> intro h >> swap /- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic unit := assertv_core h t v >> intro h >> return () /- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : tactic unit := define_core h t >> swap >> intro h >> swap /- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic unit := definev_core h t v >> intro h >> return () /- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (pr : expr) : tactic unit := do t ← infer_type pr, definev h t pr /- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, assertv n t pr /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ gs ++ rs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] private meta def all_goals_core : tactic unit → list expr → list expr → tactic unit | tac [] ac := set_goals ac | tac (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core tac gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals | failed, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ /- Applies tac if c holds -/ meta def when (c : Prop) [decidable c] (tac : tactic unit) : tactic unit := if c then tac else skip meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def now : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "now tactic failed, there are unsolved goals") meta def apply : expr → tactic unit := apply_core semireducible tt ff tt meta def fapply : expr → tactic unit := apply_core semireducible tt tt tt /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← returnex (environment.get env c), num ← return (length (declaration.univ_params decl)), ls ← mk_num_meta_univs num, return (expr.const c ls) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, l ← return (expr.local_const m n bi d), new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : name) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", intro H meta def cases (H : expr) : tactic unit := cases_core semireducible H [] meta def cases_using : expr → list name → tactic unit := cases_core semireducible meta def induction : expr → name → list name → tactic unit := induction_core semireducible meta def destruct (e : expr) : tactic unit := destruct_core semireducible e meta def generalize : expr → name → tactic unit := generalize_core semireducible meta def generalizes : list expr → tactic unit | [] := skip | (e::es) := generalize e `x >> generalizes es meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr `((%%e : %%tgt)) >>= exact /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) end tactic open tactic meta def nat.to_expr : nat → tactic expr | n := if n = 0 then to_expr `(0) else if n = 1 then to_expr `(1) else do r : expr ← nat.to_expr (n / 2), if n % 2 = 0 then to_expr `(bit0 %%r) else to_expr `(bit1 %%r) meta def char.to_expr : char → tactic expr | ⟨n, pr⟩ := do e ← n^.to_expr, to_expr `(char.of_nat %%e) meta def string.to_expr : string → tactic expr | [] := to_expr `(string.empty) | (c::cs) := do e ← c^.to_expr, es ← string.to_expr cs, to_expr `(string.str %%e %%es) meta def unsigned.to_expr : unsigned → tactic expr | ⟨n, pr⟩ := do e ← n^.to_expr, to_expr `(unsigned.of_nat %%e) meta def name.to_expr : name → tactic expr | name.anonymous := to_expr `(name.anonymous) | (name.mk_string s n) := do es ← s^.to_expr, en ← name.to_expr n, to_expr `(name.mk_string %%es %%en) | (name.mk_numeral i n) := do is ← i^.to_expr, en ← name.to_expr n, to_expr `(name.mk_string %%is %%en) meta def list_name.to_expr : list name → tactic expr | [] := to_expr `(([] : list name)) | (h::t) := do eh ← h^.to_expr, et ← list_name.to_expr t, to_expr `(%%eh :: %%et) notation [parsing_only] `command`:max := tactic unit open tactic /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_command do l ← return $ level.param `l, Ty ← return $ expr.sort l, type ← to_expr `(Π (α : %%Ty), α → α), val ← to_expr `(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a := rfl
510ef54f052fa320eaa74c9cb10481ab6aece72d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/repr_issue.lean
a537d5b6b7eff972e282759463f6989669234255
[ "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
640
lean
-- def foo {m} [Monad m] [MonadExcept String m] [MonadState (Array Nat) m] : m Nat := tryCatch (do modify $ fun (a : Array Nat) => a.set! 0 33; throw "error") (fun _ => do let a ← get; pure $ a.get! 0) def ex₁ : StateT (Array Nat) (ExceptT String Id) Nat := foo def ex₂ : ExceptT String (StateT (Array Nat) Id) Nat := foo -- The following examples were producing an element of Type `id (Except String Nat)`. -- Type class resolution was failing to produce an instance for `Repr (id (Except String Nat))` because `id` is not transparent. #eval ex₁.run' (mkArray 10 1000) |>.run #eval ex₂.run' (mkArray 10 1000) |>.run
9dd073ac94e941867770df98d26ac354c7fdfde9
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/exfalso1.hlean
0a6df5836cbe260fed8c1e2ef7fe6bb3ffa62746
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
179
hlean
open nat example (a b : nat) : a = 0 → b = 1 → a = b → a + b * b ≤ 10000 := begin intro a0 b1 ab, exfalso, state, rewrite [a0 at ab, b1 at ab], contradiction end
c09ce015493087f1089ff898757efe82464fe106
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/sesquilinear_form_auto.lean
549d10725073408900d44c8aa1c552cc21849a28
[]
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
10,345
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.basic import Mathlib.ring_theory.ring_invo import Mathlib.PostPort universes u v l u_1 u_2 namespace Mathlib /-! # Sesquilinear form This file defines a sesquilinear form over a module. The definition requires a ring antiautomorphism on the scalar ring. Basic ideas such as orthogonality are also introduced. A sesquilinear form on an `R`-module `M`, is a function from `M × M` to `R`, that is linear in the first argument and antilinear in the second, with respect to an antiautomorphism on `R` (an antiisomorphism from `R` to `R`). ## Notations Given any term `S` of type `sesq_form`, due to a coercion, can use the notation `S x y` to refer to the function field, ie. `S x y = S.sesq x y`. ## References * <https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings> ## Tags Sesquilinear form, -/ /-- A sesquilinear form over a module -/ structure sesq_form (R : Type u) (M : Type v) [ring R] (I : R ≃+* (Rᵒᵖ)) [add_comm_group M] [module R M] where sesq : M → M → R sesq_add_left : ∀ (x y z : M), sesq (x + y) z = sesq x z + sesq y z sesq_smul_left : ∀ (a : R) (x y : M), sesq (a • x) y = a * sesq x y sesq_add_right : ∀ (x y z : M), sesq x (y + z) = sesq x y + sesq x z sesq_smul_right : ∀ (a : R) (x y : M), sesq x (a • y) = opposite.unop (coe_fn I a) * sesq x y namespace sesq_form protected instance has_coe_to_fun {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} : has_coe_to_fun (sesq_form R M I) := has_coe_to_fun.mk (fun (S : sesq_form R M I) => M → M → R) fun (S : sesq_form R M I) => sesq S theorem add_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S (x + y) z = coe_fn S x z + coe_fn S y z := sesq_add_left S x y z theorem smul_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (a : R) (x : M) (y : M) : coe_fn S (a • x) y = a * coe_fn S x y := sesq_smul_left S a x y theorem add_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S x (y + z) = coe_fn S x y + coe_fn S x z := sesq_add_right S x y z theorem smul_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (a : R) (x : M) (y : M) : coe_fn S x (a • y) = opposite.unop (coe_fn I a) * coe_fn S x y := sesq_smul_right S a x y theorem zero_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) : coe_fn S 0 x = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn S 0 x = 0)) (Eq.symm (zero_smul R 0)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn S (0 • 0) x = 0)) (smul_left 0 0 x))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 * coe_fn S 0 x = 0)) (zero_mul (coe_fn S 0 x)))) (Eq.refl 0))) theorem zero_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) : coe_fn S x 0 = 0 := sorry theorem neg_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) : coe_fn S (-x) y = -coe_fn S x y := sorry theorem neg_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) : coe_fn S x (-y) = -coe_fn S x y := sorry theorem sub_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S (x - y) z = coe_fn S x z - coe_fn S y z := sorry theorem sub_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S x (y - z) = coe_fn S x y - coe_fn S x z := sorry theorem ext {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} {D : sesq_form R M I} (H : ∀ (x y : M), coe_fn S x y = coe_fn D x y) : S = D := sorry protected instance add_comm_group {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} : add_comm_group (sesq_form R M I) := add_comm_group.mk (fun (S D : sesq_form R M I) => mk (fun (x y : M) => coe_fn S x y + coe_fn D x y) sorry sorry sorry sorry) sorry (mk (fun (x y : M) => 0) sorry sorry sorry sorry) sorry sorry (fun (S : sesq_form R M I) => mk (fun (x y : M) => -sesq S x y) sorry sorry sorry sorry) (add_group.sub._default (fun (S D : sesq_form R M I) => mk (fun (x y : M) => coe_fn S x y + coe_fn D x y) sorry sorry sorry sorry) sorry (mk (fun (x y : M) => 0) sorry sorry sorry sorry) sorry sorry fun (S : sesq_form R M I) => mk (fun (x y : M) => -sesq S x y) sorry sorry sorry sorry) sorry sorry protected instance inhabited {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} : Inhabited (sesq_form R M I) := { default := 0 } /-- The proposition that two elements of a sesquilinear form space are orthogonal -/ def is_ortho {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) (x : M) (y : M) := coe_fn S x y = 0 theorem ortho_zero {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) : is_ortho S 0 x := zero_left x theorem is_add_monoid_hom_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) (x : M) : is_add_monoid_hom fun (z : M) => coe_fn S z x := is_add_monoid_hom.mk (zero_left x) theorem is_add_monoid_hom_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) (x : M) : is_add_monoid_hom fun (z : M) => coe_fn S x z := is_add_monoid_hom.mk (zero_right x) theorem map_sum_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {α : Type u_1} (S : sesq_form R M I) (t : finset α) (g : α → M) (w : M) : coe_fn S (finset.sum t fun (i : α) => g i) w = finset.sum t fun (i : α) => coe_fn S (g i) w := Eq.symm (finset.sum_hom t fun (z : M) => coe_fn S z w) theorem map_sum_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {α : Type u_1} (S : sesq_form R M I) (t : finset α) (g : α → M) (w : M) : coe_fn S w (finset.sum t fun (i : α) => g i) = finset.sum t fun (i : α) => coe_fn S w (g i) := Eq.symm (finset.sum_hom t fun (z : M) => coe_fn S w z) protected instance to_module {R : Type u_1} [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {J : R ≃+* (Rᵒᵖ)} : module R (sesq_form R M J) := semimodule.mk sorry sorry theorem ortho_smul_left {R : Type u_1} [domain R] {M : Type v} [add_comm_group M] [module R M] {K : R ≃+* (Rᵒᵖ)} {G : sesq_form R M K} {x : M} {y : M} {a : R} (ha : a ≠ 0) : is_ortho G x y ↔ is_ortho G (a • x) y := sorry theorem ortho_smul_right {R : Type u_1} [domain R] {M : Type v} [add_comm_group M] [module R M] {K : R ≃+* (Rᵒᵖ)} {G : sesq_form R M K} {x : M} {y : M} {a : R} (ha : a ≠ 0) : is_ortho G x y ↔ is_ortho G x (a • y) := sorry end sesq_form namespace refl_sesq_form /-- The proposition that a sesquilinear form is reflexive -/ def is_refl {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) := ∀ (x y : M), coe_fn S x y = 0 → coe_fn S y x = 0 theorem eq_zero {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_refl S) {x : M} {y : M} : coe_fn S x y = 0 → coe_fn S y x = 0 := H x y theorem ortho_sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_refl S) {x : M} {y : M} : sesq_form.is_ortho S x y ↔ sesq_form.is_ortho S y x := { mp := eq_zero H, mpr := eq_zero H } end refl_sesq_form namespace sym_sesq_form /-- The proposition that a sesquilinear form is symmetric -/ def is_sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) := ∀ (x y : M), opposite.unop (coe_fn I (coe_fn S x y)) = coe_fn S y x theorem sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_sym S) (x : M) (y : M) : opposite.unop (coe_fn I (coe_fn S x y)) = coe_fn S y x := H x y theorem is_refl {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_sym S) : refl_sesq_form.is_refl S := sorry theorem ortho_sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_sym S) {x : M} {y : M} : sesq_form.is_ortho S x y ↔ sesq_form.is_ortho S y x := refl_sesq_form.ortho_sym (is_refl H) end sym_sesq_form namespace alt_sesq_form /-- The proposition that a sesquilinear form is alternating -/ def is_alt {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) := ∀ (x : M), coe_fn S x x = 0 theorem self_eq_zero {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_alt S) (x : M) : coe_fn S x x = 0 := H x theorem neg {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_alt S) (x : M) (y : M) : -coe_fn S x y = coe_fn S y x := sorry end Mathlib
0cd2155e8a64a8a18aa688aaf32ac6426233b6d8
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/basis.lean
7515962bc1b24ad7f6614a2d5aab88e2edabce4d
[ "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
53,665
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, Alexander Bentkamp -/ import linear_algebra.basic linear_algebra.finsupp order.zorn import data.fintype.card /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type*} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, s.sum (λ i, g i • v i) = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (s.sum $ λ i, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = s.sum (λ j, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j))) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = s.sum (λ j, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma ne_zero_of_linear_independent {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' l.support.to_set : set s) l.support.to_set, { apply bij_on.mk, { unfold maps_to }, { apply subtype.val_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_val], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' finset.to_set (l.support)) (finset.to_set (l.support)), { apply bij_on.mk, { unfold maps_to }, { apply (linear_independent.injective zero_eq_one hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ subtype.val : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent_union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin haveI := classical.dec (nonempty η), by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], apply linear_independent_union, { apply hl }, { apply ih }, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' s.to_set), exact finite_preimage (assume i j _ _, plift.up.inj) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim (ne_zero_of_linear_independent zero_eq_one (hindep x₁) h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent_inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin apply linear_independent_union, exact (hs.image_subtype $ by simp), exact (ht.image_subtype $ by simp), rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact injective_comp prod.injective_inl inj_v }, { exact injective_comp prod.injective_inr inj_v' }, { intros, simp [ne_zero_of_linear_independent zero_eq_one hv] } }, { rw sum.elim_range, apply linear_independent_union, { apply linear_independent.to_subtype_range, apply linear_independent.image hv, simp [ker_inl] }, { apply linear_independent.to_subtype_range, apply linear_independent.image hv', simp [ker_inr] }, { apply disjoint_inl_inr.mono _ _, { rw [set.range_comp, span_image], apply linear_map.map_le_range }, { rw [set.range_comp, span_image], apply linear_map.map_le_range } } } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. s.sum (λ i, ((g i * i x - g i * a x) • i : G → L)) y = s.sum (λ i, (g i * i x - g i * a x) * i y) : pi.finset_sum_apply _ _ _ ... = s.sum (λ i, g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = s.sum (λ i, g i * i x * i y) - s.sum (λ i, g i * a x * i y) : finset.sum_sub_distrib ... = (g a * a x * a y + s.sum (λ i, g i * i x * i y)) - (g a * a x * a y + s.sum (λ i, g i * a x * i y)) : by rw add_sub_add_left_eq_sub ... = (insert a s).sum (λ i, g i * i x * i y) - (insert a s).sum (λ i, g i * a x * i y) : by rw [finset.sum_insert has, finset.sum_insert has] ... = (insert a s).sum (λ i, g i * i (x * y)) - (insert a s).sum (λ i, a x * (g i * i y)) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (insert a s).sum (λ i, (g i • i : G → L)) (x * y) - a x * (insert a s).sum (λ i, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (insert a s).sum (λ i, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} {f : M → M'} {g : M' → M} (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, add := λ x y, by ext; exact finsupp.add_apply, smul := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) : (equiv_fun_basis h).symm x = finset.sum finset.univ (λi, x i • v i) := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = finset.sum finset.univ (λi, x i • v i), dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section set_option class.instance_max_depth 36 lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply linear_independent_union hs (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, haveI := classical.dec (x ∈ span K b), by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (λ i : b, i.val) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i : b, i.val) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one K _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin letI := classical.dec_pred (λx, x ∈ s), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp *, finish }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : V →ₗ[K] V'} (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), have h₂ : range (λ (i : B), i.val) = B := subtype.range_val B, rwa h₂ at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hB, intros b, rw image_subset_iff at BC, simp, have := BC (subtype.mem b), rw mem_preimage at this, have : f (b.val) = (subtype.mk (f ↑b) (begin rw ←mem_preimage, exact BC (subtype.mem b) end) : C).val, by simp; unfold_coes, rw this, rw [constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _, end lemma exists_right_inverse_linear_map_of_surjective {f : V →ₗ[K] V'} (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hC, intros c, simp [constr_basis hC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end set_option class.instance_max_depth 49 open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := begin haveI := classical.dec_eq (quotient p), rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.coprod p.subtype) (p.mkq.prod (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa [sub_eq_add_neg, add_left_comm] using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end open fintype theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := begin apply exists.elim (exists_is_basis K V), intros b hb, haveI := classical.dec_pred (λ x, x ∈ b), use card b, exact module.card_fintype hb, end end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), (λ _, unit) j), (std_basis R (λ (i : η), R) (ji.fst)) 1) := begin haveI := classical.dec_eq, apply @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _), end lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply is_basis.comp (is_basis_fun₀ R η) (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use (λ x, x.1), simp [function.left_inverse, function.right_inverse], intros _ b, rw [unique.eq_default b, unique.eq_default punit.star] end end end module end pi
8499bfc37a45f6203f5f305643312a442f31925d
0d9b0a832bc57849732c5bd008a7a142f7e49656
/src/show_sokolevel.lean
870b14ff6860beddfc9b98dddd129fd6c8d8c69e
[]
no_license
mirefek/sokoban.lean
bb9414af67894e4d8ce75f8c8d7031df02d371d0
451c92308afb4d3f8e566594b9751286f93b899b
refs/heads/master
1,681,025,245,267
1,618,997,832,000
1,618,997,832,000
359,491,681
10
0
null
null
null
null
UTF-8
Lean
false
false
2,293
lean
import .sokolevel @[reducible] meta def show_sokolevel := tactic @[reducible] meta def show_sokolevel_w := tactic open tactic -- The following two functions are taken from the natural number game and are written by Rob Lewis meta def copy_decl (prfx : name) (d : declaration) : tactic unit := add_decl $ d.update_name $ d.to_name.update_prefix prfx meta def copy_decls (prfx : name) : tactic unit := do env ← get_env, let ls := env.fold [] list.cons, ls.mmap' $ λ dec, when (dec.to_name.get_prefix = `tactic.interactive) (copy_decl prfx dec) namespace show_sokolevel meta def step {α : Type} (t : show_sokolevel α) : show_sokolevel unit := t >> return () meta def istep := @tactic.istep meta def solve1 := @tactic.solve1 meta def get_soko_format : tactic format := do `(sokolevel.solvable %%lev_e) ← tactic.target, lev ← tactic.eval_expr sokolevel lev_e, return (format.compose "⊢ solvable" (to_string lev)) meta def save_info (p : pos) : show_sokolevel unit := do s ← tactic.read, lev ← get_soko_format <|> return format.nil, tactic.save_info_thunk p (λ _, format.compose lev (tactic_state.to_format s)) end show_sokolevel namespace show_sokolevel_w meta def step {α : Type} (t : show_sokolevel_w α) : show_sokolevel_w unit := t >> return () meta def istep := @tactic.istep meta def solve1 := @tactic.solve1 #check tactic.read meta def get_soko_widget (s : tactic_state) (lev : sokolevel) : widget.tc unit empty := widget.tc.stateless $ λ _, do return [ widget.h "div" [] [lev.to_html], widget.h "hr" [] [], widget.h "div" [] [widget.html.of_component s widget.tactic_state_widget] ] #check tactic.save_widget meta def save_info (p : pos) : show_sokolevel_w unit := do s ← tactic.read, tactic.save_info_thunk p (λ _, tactic_state.to_format s), tactic.try (do `(sokolevel.solvable %%lev_e) ← tactic.target, lev ← tactic.eval_expr sokolevel lev_e, s ← tactic.read, tactic.save_widget p (widget.tc.to_component (get_soko_widget s lev)) ), return () --meta def save_info (p : pos) : show_sokolevel_w unit := end show_sokolevel_w -- maybe, the copying of other tactics is unnecessary... --run_cmd copy_decls `show_sokolevel.interactive --run_cmd copy_decls `show_sokolevel_w.interactive
afb6c5b7280955ab9b9c37d2290c929a39e41535
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/synthPending1.lean
d0acc0580c6c7944d52ae56dfca95ca14f1dcb2d
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
62
lean
new_frontend theorem ex : Not (1 = 2) := ofDecideEqFalse rfl
8de8d4f2e2ba3115491dde17f343ba84fe2de244
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/linear/linear_functor.lean
18abc87553050ce224463df35c41bcedb3d069ce
[ "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,042
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.preadditive.additive_functor import category_theory.linear /-! # Linear Functors An additive functor between two `R`-linear categories is called *linear* if the induced map on hom types is a morphism of `R`-modules. # Implementation details `functor.linear` is a `Prop`-valued class, defined by saying that for every two objects `X` and `Y`, the map `F.map : (X ⟶ Y) → (F.obj X ⟶ F.obj Y)` is a morphism of `R`-modules. -/ namespace category_theory variables (R : Type*) [semiring R] /-- An additive functor `F` is `R`-linear provided `F.map` is an `R`-module morphism. -/ class functor.linear {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] [linear R C] [linear R D] (F : C ⥤ D) [F.additive] : Prop := (map_smul' : Π {X Y : C} {f : X ⟶ Y} {r : R}, F.map (r • f) = r • F.map f . obviously) section linear namespace functor section variables {R} {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] [category_theory.linear R C] [category_theory.linear R D] (F : C ⥤ D) [additive F] [linear R F] @[simp] lemma map_smul {X Y : C} (r : R) (f : X ⟶ Y) : F.map (r • f) = r • F.map f := functor.linear.map_smul' instance : linear R (𝟭 C) := {} instance {E : Type*} [category E] [preadditive E] [category_theory.linear R E] (G : D ⥤ E) [additive G] [linear R G]: linear R (F ⋙ G) := {} variables (R) /-- `F.map_linear_map` is an `R`-linear map whose underlying function is `F.map`. -/ @[simps] def map_linear_map {X Y : C} : (X ⟶ Y) →ₗ[R] (F.obj X ⟶ F.obj Y) := { map_smul' := λ r f, F.map_smul r f, ..F.map_add_hom } lemma coe_map_linear_map {X Y : C} : ⇑(F.map_linear_map R : (X ⟶ Y) →ₗ[R] _) = @map C _ D _ F X Y := rfl end section induced_category variables {C : Type*} {D : Type*} [category D] [preadditive D] [category_theory.linear R D] (F : C → D) instance induced_functor_linear : functor.linear R (induced_functor F) := {} end induced_category section variables {R} {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) [additive F] instance nat_linear : F.linear ℕ := { map_smul' := λ X Y f r, F.map_add_hom.map_nsmul f r, } instance int_linear : F.linear ℤ := { map_smul' := λ X Y f r, F.map_add_hom.map_zsmul f r, } variables [category_theory.linear ℚ C] [category_theory.linear ℚ D] instance rat_linear : F.linear ℚ := { map_smul' := λ X Y f r, F.map_add_hom.to_rat_linear_map.map_smul r f, } end end functor namespace equivalence variables {C D : Type*} [category C] [category D] [preadditive C] [linear R C] [preadditive D] [linear R D] instance inverse_linear (e : C ≌ D) [e.functor.additive] [e.functor.linear R] : e.inverse.linear R := { map_smul' := λ X Y r f, by { apply e.functor.map_injective, simp, }, } end equivalence end linear end category_theory
65375d0f6ce70d119c35138ecf3a0eec6b6fbb14
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/compatible_sheafification.lean
23051dd93fe7dc1724681f7a38042a46629c939a
[ "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
5,944
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.sites.compatible_plus import category_theory.sites.sheafification /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we prove that sheafification is compatible with functors which preserve the correct limits and colimits. -/ namespace category_theory.grothendieck_topology open category_theory open category_theory.limits open opposite universes w₁ w₂ v u variables {C : Type u} [category.{v} C] (J : grothendieck_topology C) variables {D : Type w₁} [category.{max v u} D] variables {E : Type w₂} [category.{max v u} E] variables (F : D ⥤ E) noncomputable theory variables [∀ (α β : Type (max v u)) (fst snd : β → α), has_limits_of_shape (walking_multicospan fst snd) D] variables [∀ (α β : Type (max v u)) (fst snd : β → α), has_limits_of_shape (walking_multicospan fst snd) E] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ E] variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] variables [∀ (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] variables (P : Cᵒᵖ ⥤ D) /-- The isomorphism between the sheafification of `P` composed with `F` and the sheafification of `P ⋙ F`. Use the lemmas `whisker_right_to_sheafify_sheafify_comp_iso_hom`, `to_sheafify_comp_sheafify_comp_iso_inv` and `sheafify_comp_iso_inv_eq_sheafify_lift` to reduce the components of this isomorphisms to a state that can be handled using the universal property of sheafification. -/ def sheafify_comp_iso : J.sheafify P ⋙ F ≅ J.sheafify (P ⋙ F) := J.plus_comp_iso _ _ ≪≫ (J.plus_functor _).map_iso (J.plus_comp_iso _ _) /-- The isomorphism between the sheafification of `P` composed with `F` and the sheafification of `P ⋙ F`, functorially in `F`. -/ def sheafification_whisker_left_iso (P : Cᵒᵖ ⥤ D) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (whiskering_left _ _ E).obj (J.sheafify P) ≅ (whiskering_left _ _ _).obj P ⋙ J.sheafification E := begin refine J.plus_functor_whisker_left_iso _ ≪≫ _ ≪≫ functor.associator _ _ _, refine iso_whisker_right _ _, refine J.plus_functor_whisker_left_iso _, end @[simp] lemma sheafification_whisker_left_iso_hom_app (P : Cᵒᵖ ⥤ D) (F : D ⥤ E) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (sheafification_whisker_left_iso J P).hom.app F = (J.sheafify_comp_iso F P).hom := begin dsimp [sheafification_whisker_left_iso, sheafify_comp_iso], rw category.comp_id, end @[simp] lemma sheafification_whisker_left_iso_inv_app (P : Cᵒᵖ ⥤ D) (F : D ⥤ E) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (sheafification_whisker_left_iso J P).inv.app F = (J.sheafify_comp_iso F P).inv := begin dsimp [sheafification_whisker_left_iso, sheafify_comp_iso], erw category.id_comp, end /-- The isomorphism between the sheafification of `P` composed with `F` and the sheafification of `P ⋙ F`, functorially in `P`. -/ def sheafification_whisker_right_iso : J.sheafification D ⋙ (whiskering_right _ _ _).obj F ≅ (whiskering_right _ _ _).obj F ⋙ J.sheafification E := begin refine functor.associator _ _ _ ≪≫ _, refine iso_whisker_left (J.plus_functor D) (J.plus_functor_whisker_right_iso _) ≪≫ _, refine _ ≪≫ functor.associator _ _ _, refine (functor.associator _ _ _).symm ≪≫ _, exact iso_whisker_right (J.plus_functor_whisker_right_iso _) (J.plus_functor E), end @[simp] lemma sheafification_whisker_right_iso_hom_app : (J.sheafification_whisker_right_iso F).hom.app P = (J.sheafify_comp_iso F P).hom := begin dsimp [sheafification_whisker_right_iso, sheafify_comp_iso], simp only [category.id_comp, category.comp_id], erw category.id_comp, end @[simp] lemma sheafification_whisker_right_iso_inv_app : (J.sheafification_whisker_right_iso F).inv.app P = (J.sheafify_comp_iso F P).inv := begin dsimp [sheafification_whisker_right_iso, sheafify_comp_iso], simp only [category.id_comp, category.comp_id], erw category.id_comp, end @[simp, reassoc] lemma whisker_right_to_sheafify_sheafify_comp_iso_hom : whisker_right (J.to_sheafify _) _ ≫ (J.sheafify_comp_iso F P).hom = J.to_sheafify _ := begin dsimp [sheafify_comp_iso], erw [whisker_right_comp, category.assoc], slice_lhs 2 3 { rw plus_comp_iso_whisker_right }, rw [category.assoc, ← J.plus_map_comp, whisker_right_to_plus_comp_plus_comp_iso_hom, ← category.assoc, whisker_right_to_plus_comp_plus_comp_iso_hom], refl, end @[simp, reassoc] lemma to_sheafify_comp_sheafify_comp_iso_inv : J.to_sheafify _ ≫ (J.sheafify_comp_iso F P).inv = whisker_right (J.to_sheafify _) _ := by { rw iso.comp_inv_eq, simp } section -- We will sheafify `D`-valued presheaves in this section. variables [concrete_category.{max v u} D] [preserves_limits (forget D)] [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)] [reflects_isomorphisms (forget D)] @[simp] lemma sheafify_comp_iso_inv_eq_sheafify_lift : (J.sheafify_comp_iso F P).inv = J.sheafify_lift (whisker_right (J.to_sheafify _) _) ((J.sheafify_is_sheaf _).comp _) := begin apply J.sheafify_lift_unique, rw iso.comp_inv_eq, simp, end end end category_theory.grothendieck_topology
79f2676f92c669cb23a14ac8a36c414878d249ab
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/analysis/normed_space/basic.lean
9a1194e72413bd922f5a96344d0289ff348b98e0
[ "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
24,413
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric local notation f `→_{`:50 a `}`:0 b := tendsto f (nhds a) (nhds b) class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_triangle_sum {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_triangle lemma norm_pos_iff (g : α) : 0 < ∥ g ∥ ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma norm_reverse_triangle' (a b : α) : ∥a∥ - ∥b∥ ≤ ∥a - b∥ := by simpa using add_le_add (norm_triangle (a - b) (b)) (le_refl (-∥b∥)) lemma norm_reverse_triangle (a b : α) : abs(∥a∥ - ∥b∥) ≤ ∥a - b∥ := suffices -(∥a∥ - ∥b∥) ≤ ∥a - b∥, from abs_le_of_le_of_neg_le (norm_reverse_triangle' a b) this, calc -(∥a∥ - ∥b∥) = ∥b∥ - ∥a∥ : by abel ... ≤ ∥b - a∥ : norm_reverse_triangle' b a ... = ∥a - b∥ : by rw ← norm_neg (a - b); simp lemma norm_triangle_sub {a b : α} : ∥a - b∥ ≤ ∥a∥ + ∥b∥ := by simpa only [sub_eq_add_neg, norm_neg] using norm_triangle a (-b) lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by rw ←norm_neg; simp lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp theorem normed_space.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (nhds 0) ↔ ∀ ε > 0, { x | ∥ f x ∥ < ε } ∈ l := begin rw [metric.tendsto_nhds], simp only [normed_group.dist_eq, sub_zero], split, { intros h ε εgt0, rcases h ε εgt0 with ⟨s, ssets, hs⟩, exact mem_sets_of_superset ssets hs }, intros h ε εgt0, exact ⟨_, h ε εgt0, set.subset.refl _⟩ end section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group [normed_group β] : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : α → Type*} [fintype α] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero [normed_group α] [normed_group β] {f : γ → β} {a : filter γ} : tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e ∥) a (nhds 0) := have tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (nhds 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm] ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_triangle_sub ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end instance normed_top_monoid : topological_add_monoid α := by apply_instance instance normed_top_group : topological_add_group α := by apply_instance end normed_group section normed_ring class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, n > 0 → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_triangle }, { rw ←zero_add (0 : ℝ), apply tendsto_add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto_mul, { apply continuous_iff_continuous_at.1, apply continuous.comp, { apply continuous_fst }, { apply continuous_norm }}, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto_mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section normed_field class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) = norm a * norm b) class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul], ..i } @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (finset.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } lemma real.norm_eq_abs (r : ℝ): norm r = abs r := rfl end normed_field @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] section normed_space class normed_space (α : Type*) (β : Type*) [normed_field α] extends normed_group β, vector_space α β := (norm_smul : ∀ (a:α) b, norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] instance normed_field.to_normed_space : normed_space α α := { dist_eq := normed_field.dist_eq, norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp limg (continuous_iff_continuous_at.1 continuous_norm _), have lim1 := tendsto_mul limf' limg', simp only [zero_mul, sub_eq_add_neg] at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := tendsto_mul (tendsto_const_nhds : tendsto _ _ (nhds ∥ s ∥)) limg3, simp only [sub_eq_add_neg, mul_zero] at lim2, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end lemma tendsto_smul_const {g : γ → F} {e : filter γ} (s : α) {b : F} : (tendsto g e (nhds b)) → tendsto (λ x, s • (g x)) e (nhds (s • b)) := tendsto_smul tendsto_const_nhds lemma continuous_smul [topological_space γ] {f : γ → α} {g : γ → E} (hf : continuous f) (hg : continuous g) : continuous (λc, f c • g c) := continuous_iff_continuous_at.2 $ assume c, tendsto_smul (continuous_iff_continuous_at.1 hf _) (continuous_iff_continuous_at.1 hg _) /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos ((norm_pos_iff _).2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {ι : Type*} {E : ι → Type*} [fintype ι] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm := λf, ((finset.univ.sup (λb, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume f g, congr_arg coe $ congr_arg (finset.sup finset.univ) $ by funext i; exact nndist_eq_nnnorm _ _, norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul], ..metric_space_pi, ..pi.vector_space α } /-- A normed space can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_space.core (α : Type*) (β : Type*) [normed_field α] [add_comm_group β] [has_scalar α β] [has_norm β] := (norm_eq_zero_iff : ∀ x : β, ∥x∥ = 0 ↔ x = 0) (norm_smul : ∀ c : α, ∀ x : β, ∥c • x∥ = ∥c∥ * ∥x∥) (triangle : ∀ x y : β, ∥x + y∥ ≤ ∥x∥ + ∥y∥) noncomputable def normed_space.of_core (α : Type*) (β : Type*) [normed_field α] [add_comm_group β] [vector_space α β] [has_norm β] (C : normed_space.core α β) : normed_space α β := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(1 : α) • (y - x)∥ : by simp ... = ∥y - x∥ : begin rw[C.norm_smul], simp end, norm_smul := C.norm_smul } end normed_space section summable local attribute [instance] classical.prop_decidable open finset filter variables [normed_group α] [complete_space α] lemma summable_iff_vanishing_norm {f : ι → α} : summable f ↔ ∀ε>0, (∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε) := begin simp only [summable_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hf : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := summable_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hf ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.zero_le_sum (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_triangle_sum t f) $ lt_of_le_of_lt (finset.sum_le_sum $ assume i _, h i) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (nhds ∥(∑ i, f i)∥) := (has_sum_tsum $ summable_of_summable_norm hf).comp (continuous_norm.tendsto _), have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (nhds (∑ i, ∥f i∥)) := has_sum_tsum hf, le_of_tendsto_of_tendsto at_top_ne_bot h₁ h₂ $ univ_mem_sets' $ assume s, norm_triangle_sum _ _ end summable namespace complex instance : normed_field ℂ := { norm := complex.abs, dist_eq := λ _ _, rfl, norm_mul := complex.abs_mul, .. complex.discrete_field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := complex.abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := complex.abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : n ≥ 0) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn end complex
f0ac397312e9339db37b65bf7ed9d9e09244259f
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Tactic.lean
52b74be90c06782e0f43ae531d96499ac83a92ce
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
651
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.Elab.Term import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Induction import Lean.Elab.Tactic.Generalize import Lean.Elab.Tactic.Injection import Lean.Elab.Tactic.Match import Lean.Elab.Tactic.Rewrite import Lean.Elab.Tactic.Location import Lean.Elab.Tactic.Simp import Lean.Elab.Tactic.BuiltinTactic import Lean.Elab.Tactic.Split import Lean.Elab.Tactic.Conv import Lean.Elab.Tactic.Delta import Lean.Elab.Tactic.Meta
d06bec14ad0f616e06281f8c071b8a522339ab1e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/integral/integrable_on.lean
dca0a9e1719a11f860a33e7992bc1ec57c270388
[ "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
21,536
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.function.l1_space import analysis.normed_space.indicator_function /-! # Functions integrable on a set and at a filter We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section variables [topological_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is strongly measurable at a filter `l` w.r.t. a measure `μ` if it is ae strongly measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def strongly_measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_strongly_measurable f (μ.restrict s) @[simp] lemma strongly_measurable_at_bot {f : α → β} : strongly_measurable_at_filter f ⊥ μ := ⟨∅, mem_bot, by simp⟩ protected lemma strongly_measurable_at_filter.eventually (h : strongly_measurable_at_filter f l μ) : ∀ᶠ s in l.small_sets, ae_strongly_measurable f (μ.restrict s) := (eventually_small_sets' $ λ s t, ae_strongly_measurable.mono_set).2 h protected lemma strongly_measurable_at_filter.filter_mono (h : strongly_measurable_at_filter f l μ) (h' : l' ≤ l) : strongly_measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma measure_theory.ae_strongly_measurable.strongly_measurable_at_filter (h : ae_strongly_measurable f μ) : strongly_measurable_at_filter f l μ := ⟨univ, univ_mem, by rwa measure.restrict_univ⟩ lemma ae_strongly_measurable.strongly_measurable_at_filter_of_mem {s} (h : ae_strongly_measurable f (μ.restrict s)) (hl : s ∈ l) : strongly_measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measure_theory.strongly_measurable.strongly_measurable_at_filter (h : strongly_measurable f) : strongly_measurable_at_filter f l μ := h.ae_strongly_measurable.strongly_measurable_at_filter end namespace measure_theory section normed_add_comm_group lemma has_finite_integral_restrict_of_bounded [normed_add_comm_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ‖f x‖ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : is_finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_add_comm_group E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is almost everywhere strongly measurable on `s` and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ @[simp] lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst le_rfl lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ measure.restrict_mono_ae hst lemma integrable_on.congr_set_ae (h : integrable_on f t μ) (hst : s =ᵐ[μ] t) : integrable_on f s μ := h.mono_set_ae hst.le lemma integrable_on.congr_fun' (h : integrable_on f s μ) (hst : f =ᵐ[μ.restrict s] g) : integrable_on g s μ := integrable.congr h hst lemma integrable_on.congr_fun (h : integrable_on f s μ) (hst : eq_on f g s) (hs : measurable_set s) : integrable_on g s μ := h.congr_fun' ((ae_restrict_iff' hs).2 (eventually_of_forall hst)) lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) : integrable_on f s (μ.restrict t) := by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) } lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α] : integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ := begin have : f =ᵐ[μ.restrict {x}] (λ y, f x), { filter_upwards [ae_restrict_mem (measurable_set_singleton x)] with _ ha, simp only [mem_singleton_iff.1 ha], }, rw [integrable_on, integrable_congr this, integrable_const_iff], simp, end @[simp] lemma integrable_on_finite_bUnion {s : set β} (hs : s.finite) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_Union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_bUnion s.finite_to_set @[simp] lemma integrable_on_finite_Union [finite β] {t : β → set α} : integrable_on f (⋃ i, t i) μ ↔ ∀ i, integrable_on f (t i) μ := by { casesI nonempty_fintype β, simpa using @integrable_on_finset_Union _ _ _ _ _ f μ finset.univ t } lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right le_rfl), h.mono_measure (measure.le_add_left le_rfl)⟩, λ h, h.1.add_measure h.2⟩ lemma _root_.measurable_embedding.integrable_on_map_iff [measurable_space β] {e : α → β} (he : measurable_embedding e) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, he.restrict_map, he.integrable_map_iff] lemma integrable_on_map_equiv [measurable_space β] (e : α ≃ᵐ β) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, e.restrict_map, integrable_map_equiv e] lemma measure_preserving.integrable_on_comp_preimage [measurable_space β] {e : α → β} {ν} (h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set β} : integrable_on (f ∘ e) (e ⁻¹' s) μ ↔ integrable_on f s ν := (h₁.restrict_preimage_emb h₂ s).integrable_comp_emb h₂ lemma measure_preserving.integrable_on_image [measurable_space β] {e : α → β} {ν} (h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set α} : integrable_on f (e '' s) ν ↔ integrable_on (f ∘ e) s μ := ((h₁.restrict_image_emb h₂ s).integrable_comp_emb h₂).symm lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_strongly_measurable_indicator_iff hs] lemma integrable_on.integrable_indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.integrable_indicator hs lemma integrable_on.indicator (h : integrable_on f s μ) (ht : measurable_set t) : integrable_on (indicator t f) s μ := integrable.indicator h ht lemma integrable_indicator_const_Lp {E} [normed_add_comm_group E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : integrable (indicator_const_Lp p hs hμs c) μ := begin rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on, integrable_const_iff, lt_top_iff_ne_top], right, simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs, end lemma integrable_on_iff_integable_of_support_subset {f : α → E} {s : set α} (h1s : support f ⊆ s) (h2s : measurable_set s) : integrable_on f s μ ↔ integrable f μ := begin refine ⟨λ h, _, λ h, h.integrable_on⟩, rwa [← indicator_eq_self.2 h1s, integrable_indicator_iff h2s] end lemma integrable_on_Lp_of_measure_ne_top {E} [normed_add_comm_group E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) : integrable_on f s μ := begin refine mem_ℒp_one_iff_integrable.mp _, have hμ_restrict_univ : (μ.restrict s) set.univ < ∞, by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top], haveI hμ_finite : is_finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩, exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp, end lemma integrable.lintegral_lt_top {f : α → ℝ} (hf : integrable f μ) : ∫⁻ x, ennreal.of_real (f x) ∂μ < ∞ := calc ∫⁻ x, ennreal.of_real (f x) ∂μ ≤ ∫⁻ x, ↑‖f x‖₊ ∂μ : lintegral_of_real_le_lintegral_nnnorm f ... < ∞ : hf.2 lemma integrable_on.set_lintegral_lt_top {f : α → ℝ} {s : set α} (hf : integrable_on f s μ) : ∫⁻ x in s, ennreal.of_real (f x) ∂μ < ∞ := integrable.lintegral_lt_top hf /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.small_sets`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.small_sets, integrable_on f s μ := iff.mpr (eventually_small_sets' $ λ s t hst ht, ht.mono_set hst) h lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in l.small_sets, ∀ x ∈ s, ‖f x‖ ≤ C, from hf.imp (λ C hC, eventually_small_sets.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_small_sets with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← _root_.filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← _root_.filter.tendsto.integrable_at_filter lemma integrable_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : strongly_measurable f) (hg : strongly_measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator hf.measurable_set_support }, { rw ← indicator_add_eq_right h, exact hfg.indicator hg.measurable_set_support } end end normed_add_comm_group end measure_theory open measure_theory variables [normed_add_comm_group E] /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin nontriviality α, inhabit α, have : piecewise s f (λ _, f default) =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs, refine ⟨piecewise s f (λ _, f default), _, this.symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [piecewise_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_const ht.measurable_set).diff hs) end /-- A function which is continuous on a separable set `s` is almost everywhere strongly measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_strongly_measurable_of_is_separable [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (h's : topological_space.is_separable s) : ae_strongly_measurable f (μ.restrict s) := begin letI := pseudo_metrizable_space_pseudo_metric α, borelize β, rw ae_strongly_measurable_iff_ae_measurable_separable, refine ⟨hf.ae_measurable hs, f '' s, hf.is_separable_image h's, _⟩, exact mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _), end /-- A function which is continuous on a set `s` is almost everywhere strongly measurable with respect to `μ.restrict s` when either the source space or the target space is second-countable. -/ lemma continuous_on.ae_strongly_measurable [topological_space α] [topological_space β] [h : second_countable_topology_either α β] [opens_measurable_space α] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_strongly_measurable f (μ.restrict s) := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨hf.ae_measurable hs, f '' s, _, mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _)⟩, casesI h.out, { let f' : s → β := s.restrict f, have A : continuous f' := continuous_on_iff_continuous_restrict.1 hf, have B : is_separable (univ : set s) := is_separable_of_separable_space _, convert is_separable.image B A using 1, ext x, simp }, { exact is_separable_of_separable_space _ } end lemma continuous_on.integrable_at_nhds_within_of_is_separable [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (h't : topological_space.is_separable t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := begin haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _, exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable_of_is_separable ht h't⟩ (μ.finite_at_nhds_within _ _), end lemma continuous_on.integrable_at_nhds_within [topological_space α] [second_countable_topology_either α E] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := begin haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _, exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩ (μ.finite_at_nhds_within _ _), end /-- If a function is continuous on an open set `s`, then it is strongly measurable at the filter `𝓝 x` for all `x ∈ s` if either the source space or the target space is second-countable. -/ lemma continuous_on.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α} (hs : is_open s) (hf : continuous_on f s) : ∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ := λ x hx, ⟨s, is_open.mem_nhds hs hx, hf.ae_strongly_measurable hs.measurable_set⟩ lemma continuous_at.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [second_countable_topology_either α E] {f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : ∀ x ∈ s, continuous_at f x) : ∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ := continuous_on.strongly_measurable_at_filter hs $ continuous_at.continuous_on hf lemma continuous.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} (hf : continuous f) (μ : measure α) (l : filter α) : strongly_measurable_at_filter f l μ := hf.strongly_measurable.strongly_measurable_at_filter /-- If a function is continuous on a measurable set `s`, then it is measurable at the filter `𝓝[s] x` for all `x`. -/ lemma continuous_on.strongly_measurable_at_filter_nhds_within {α β : Type*} [measurable_space α] [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (x : α) : strongly_measurable_at_filter f (𝓝[s] x) μ := ⟨s, self_mem_nhds_within, hf.ae_strongly_measurable hs⟩
0592a5594c4866017d241b0fbd83a73002cde985
05b503addd423dd68145d68b8cde5cd595d74365
/src/data/real/ennreal.lean
8c66a9f0054fc0cfa2cd06f138d1c0f8d2229d8f
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,341
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov Extended non-negative reals -/ import data.real.nnreal order.bounds data.set.intervals tactic.norm_num noncomputable theory open classical set open_locale classical variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered] def ennreal := with_top nnreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} instance : inhabited ennreal := ⟨0⟩ instance : has_coe nnreal ennreal := ⟨ option.some ⟩ instance : can_lift ennreal nnreal := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = (⊤ : ennreal) := rfl @[simp] lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → nnreal | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, elim_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : real} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : nnreal) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : real} (h : 0 ≤ x) : ennreal.of_real x = @coe nnreal ennreal _ (⟨x, h⟩ : nnreal) := by { rw [coe_nnreal_eq], refl } @[simp, elim_cast] lemma coe_zero : ↑(0 : nnreal) = (0 : ennreal) := rfl @[simp, elim_cast] lemma coe_one : ↑(1 : nnreal) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma coe_to_real (r : nnreal) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:nnreal, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ⊤ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:nnreal) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ⊤ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, elim_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, elim_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, elim_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : nnreal → ennreal) := λ _ _, coe_le_coe.2 @[simp, elim_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, elim_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, elim_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, elim_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, elim_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, elim_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, move_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, move_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, move_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, move_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:nnreal) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1:ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast one_lt_two @[simp] lemma two_pos : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := ne_of_gt two_pos lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add instance : is_semiring_hom (coe : nnreal → ennreal) := by refine_struct {..}; simp @[simp, move_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := is_monoid_hom.map_pow coe r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top _ _ lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top _ _ lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ⊤, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top {a b : ennreal} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top {a b : ennreal} : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top {a b : ennreal} : a < ⊤ → b < ⊤ → a * b < ⊤ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, move_cast] lemma coe_finset_sum {s : finset α} {f : α → nnreal} : ↑(s.sum f) = (s.sum (λa, f a) : ennreal) := (s.sum_hom coe).symm @[simp, move_cast] lemma coe_finset_prod {s : finset α} {f : α → nnreal} : ↑(s.prod f) = (s.prod (λa, f a) : ennreal) := (s.prod_hom coe).symm section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ (⊤:ennreal) ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, elim_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, elim_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, elim_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, elim_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, squash_cast] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ⊤ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : (⊤ : ennreal) ≠ n := with_top.top_ne_nat n lemma le_coe_iff : a ≤ ↑r ↔ (∃p:nnreal, a = p ∧ p ≤ r) := with_top.le_coe_iff r a lemma coe_le_iff : ↑r ≤ a ↔ (∀p:nnreal, a = p → r ≤ p) := with_top.coe_le_iff r a lemma lt_iff_exists_coe : a < b ↔ (∃p:nnreal, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe a b @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ⊤ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ⊤ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ⊤) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:nnreal, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have (⊤:ennreal) ≤ ↑a + ↑(1:nnreal), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases dense h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:nnreal, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : nnreal, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : nnreal := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[elim_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[elim_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ⊤) : ∃n:ℕ, r < n := begin rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with ⟨r, rfl, hb⟩, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases dense ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases dense bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add' (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end @[move_cast] lemma coe_min : ((min r p:nnreal):ennreal) = min r p := coe_mono.map_min @[move_cast] lemma coe_max : ((max r p:nnreal):ennreal) = max r p := coe_mono.map_max end order section complete_lattice lemma coe_Sup {s : set nnreal} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set nnreal} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set nnreal} : ↑r ∈ upper_bounds ((coe : nnreal → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅n, f n) = (⨅n:nnreal, f n) ⊓ f ⊤ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left lemma mul_eq_zero {a b : ennreal} : a * b = 0 ↔ a = 0 ∨ b = 0 := canonically_ordered_comm_semiring.mul_eq_zero_iff _ _ end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[move_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le _) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add' (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_left_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_right_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_left_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right' h) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ⊤ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_of_nonneg_right' $ zero_le _ @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left' le_sub_add_self ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_right_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_left_inj {a b c : ennreal} (ha : a < ⊤) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- sum of finte numbers is still finite -/ lemma sum_lt_top [decidable_eq α] {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := with_top.sum_lt_top /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff [decidable_eq α] {s : finset α} {f : α → ennreal} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := with_top.sum_lt_top_iff /-- seeing `ennreal` as `nnreal` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum [decidable_eq α] {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_nnreal (s.sum f) = s.sum (λa, ennreal.to_nnreal (f a)) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, rw coe_to_nnreal, rw ← ennreal.lt_top_iff_ne_top, exact hf x hx }, { rw ← ennreal.lt_top_iff_ne_top, exact sum_lt_top hf } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum [decidable_eq α] {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_real (s.sum f) = s.sum (λa, ennreal.to_real (f a)) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ⊤ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ⊤ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_right_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : (∞ : ennreal)⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[elim_cast] lemma coe_inv_two : ((2⁻¹:nnreal):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt zero_lt_two), coe_two] @[simp, elim_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [div_def, top_mul, *] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ⊤ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ⊤ ∧ b ≠ ⊤) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ⊤ = ⊤, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ⊤, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ⊤) (hbt : b ≠ ⊤ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ⊤, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ⊤ → a ≠ 0) → (a = ⊤ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ⊤) : a * a⁻¹ = 1 := begin lift a to nnreal using ht, norm_cast at h0, rw [← coe_inv h0], norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ⊤) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : nnreal) : ennreal) * ⊤ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : nnreal) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), exact div_pos zero_lt_one _root_.two_pos end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff {a b : ennreal} : a / b = 0 ↔ a = 0 ∨ b = ⊤ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff {a b : ennreal} : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ⊤ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin lift a to nnreal using ht, norm_cast at *, rw [← coe_div _root_.two_ne_zero'], -- `norm_cast` fails to apply `coe_div` norm_cast, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to nnreal using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] end inv section real lemma to_real_add (ha : a ≠ ⊤) (hb : b ≠ ⊤) : (a+b).to_real = a.to_real + b.to_real := begin lift a to nnreal using ha, lift b to nnreal using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ⊤ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ⊤ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] @[simp] lemma to_real_le_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real < b.to_real ↔ a < b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end lemma to_real_max (hr : a ≠ ⊤) (hp : b ≠ ⊤) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ⊤) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ⊤) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ⊤, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ⊤) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_real] }, { rw [mul_top, if_neg h, top_to_real] } end @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (⊤ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real {a b : ennreal} (ha : a < ⊤) (hb : b < ⊤) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin rw ennreal.lt_top_iff_ne_top at *, split, { assume h, apply le_antisymm, rw ← to_real_le_to_real ha hb, exact le_of_eq h, rw ← to_real_le_to_real hb ha, exact le_of_eq h.symm }, { assume h, rw h } end lemma to_real_mul_to_real {a b : ennreal} : (ennreal.to_real a) * (ennreal.to_real b) = ennreal.to_real (a * b) := begin by_cases ha : a = ⊤, { rw ha, simp }, by_cases hb : b = ⊤, { rw hb, simp }, have ha : ennreal.of_real (ennreal.to_real a) = a := of_real_to_real ha, have hb : ennreal.of_real (ennreal.to_real b) = b := of_real_to_real hb, conv_rhs { rw [← ha, ← hb, ← of_real_mul to_real_nonneg] }, rw [to_real_of_real (mul_nonneg to_real_nonneg to_real_nonneg)] end end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add' (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add' (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, s.sum (f i)) = s.sum (λa, ⨅i, f i a) := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + s.sum (f k) ≤ f i a + s.sum (f j), from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add' (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ⊤ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
2ec46a023447fd4e6d7fc0f576bc19c26c2254e6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/mulcommErrorMessage.lean
f338ffafca42365e833073a70deefd4348fdf67b
[ "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
442
lean
class MulComm (α : Type u) [Mul α] : Prop where mulComm : {a b : α} → a * b = b * a instance : Mul Bool where mul := and instance : MulComm Bool where mulComm := fun a b => match a, b with | true, true => rfl | true, false => rfl | false, true => rfl | false, false => rfl instance : MulComm Bool := ⟨λ a b => Bool.casesOn a (Bool.casesOn b _ _) (Bool.casesOn b _ _)⟩
aed18c407b51a928fc5827790ef2a7a827649ea6
675b8263050a5d74b89ceab381ac81ce70535688
/src/ring_theory/power_series/basic.lean
8281a6f546cfc9f33dbc622fe9123490c615c6b1
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,791
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.mv_polynomial import ring_theory.ideal.operations import ring_theory.multiplicity import ring_theory.algebra_tower import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default _⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [semimodule R A] : semimodule R (mv_power_series σ A) := pi.semimodule _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [semimodule R A] [semimodule S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma coeff_monomial (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same _ _ _ _ lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne _ _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in (finsupp.antidiagonal n).support, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in (finsupp.antidiagonal n).support, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ (antidiagonal m).support, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_support_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ (antidiagonal m).support, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_support_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, nat_add_sub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, nat_add_sub_cancel], exact le_add_left le_rfl end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal_support, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_support_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, nat_sub_add_cancel h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, nat_add_sub_cancel] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map' (constant_coeff σ R) @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [X] end map instance {A} [comm_semiring R] [semiring A] [algebra R A] : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.semimodule } section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff R m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff R m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : mv_polynomial.coeff m (trunc R n φ) = if m ≤ n then coeff R m φ else 0 := rfl @[simp] lemma trunc_one : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, simp, cc }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal.support, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal.support, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal.support, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : units R) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : units R) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance is_local_ring [local_ring R] : local_ring (mv_power_series σ R) := { is_local := by { intro φ, rcases local_ring.is_local (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) (is_unit_unit ψ), rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ variables [local_ring R] [local_ring S] instance : local_ring (mv_power_series σ R) := { is_local := local_ring.is_local } end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal.support, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ R) : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end mv_polynomial /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [semimodule R A] : semimodule R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [semimodule R A] [semimodule S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance [comm_ring R] : algebra R (power_series R) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := calc coeff R n (1 : power_series R) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (a • φ) = a * coeff R n φ := rfl @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring R] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : polynomial R := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff R m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff R m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series R) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff R m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : R) : trunc n (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : units R) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : units R) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : units R) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain R] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nontrivial, .. power_series.comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end end integral_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring R] /-- The order of a formal power series `φ` is the greatest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series R) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series R) (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series R) (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := multiplicity.zero _ /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply nat_le_order, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [comm_semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial R) (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, norm_cast] lemma coe_zero : ((0 : polynomial R) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add (φ ψ : polynomial R) : ((φ + ψ : polynomial R) : power_series R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) : ((φ * ψ : polynomial R) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : polynomial R) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_X : ((X : polynomial R) : power_series R) = power_series.X := coe_monomial _ _ /-- The coercion from polynomials to power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_power_series.ring_hom : polynomial R →+* power_series R := { to_fun := (coe : polynomial R → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end polynomial
21dade6d3eed73c174d0e935e6bacead28720fba
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/lie/engel.lean
23045db7fcb71dd78bed56c204cd3fa9bd1382fe
[ "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
13,503
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.nilpotent import algebra.lie.normalizer /-! # Engel's theorem This file contains a proof of Engel's theorem providing necessary and sufficient conditions for Lie algebras and Lie modules to be nilpotent. The key result `lie_module.is_nilpotent_iff_forall` says that if `M` is a Lie module of a Noetherian Lie algebra `L`, then `M` is nilpotent iff the image of `L → End(M)` consists of nilpotent elements. In the special case that we have the adjoint representation `M = L`, this says that a Lie algebra is nilpotent iff `ad x : End(L)` is nilpotent for all `x : L`. Engel's theorem is true for any coefficients (i.e., it is really a theorem about Lie rings) and so we work with coefficients in any commutative ring `R` throughout. On the other hand, Engel's theorem is not true for infinite-dimensional Lie algebras and so a finite-dimensionality assumption is required. We prove the theorem subject to the the assumption that the Lie algebra is Noetherian as an `R`-module, though actually we only need the slightly weaker property that the relation `>` is well-founded on the complete lattice of Lie subalgebras. ## Remarks about the proof Engel's theorem is usually proved in the special case that the coefficients are a field, and uses an inductive argument on the dimension of the Lie algebra. One begins by choosing either a maximal proper Lie subalgebra (in some proofs) or a maximal nilpotent Lie subalgebra (in other proofs, at the cost of obtaining a weaker end result). Since we work with general coefficients, we cannot induct on dimension and an alternate approach must be taken. The key ingredient is the concept of nilpotency, not just for Lie algebras, but for Lie modules. Using this concept, we define an _Engelian Lie algebra_ `lie_algebra.is_engelian` to be one for which a Lie module is nilpotent whenever the action consists of nilpotent endomorphisms. The argument then proceeds by selecting a maximal Engelian Lie subalgebra and showing that it cannot be proper. The first part of the traditional statement of Engel's theorem consists of the statement that if `M` is a non-trivial `R`-module and `L ⊆ End(M)` is a finite-dimensional Lie subalgebra of nilpotent elements, then there exists a non-zero element `m : M` that is annihilated by every element of `L`. This follows trivially from the result established here `lie_module.is_nilpotent_iff_forall`, that `M` is a nilpotent Lie module over `L`, since the last non-zero term in the lower central series will consist of such elements `m` (see: `lie_module.nontrivial_max_triv_of_is_nilpotent`). It seems that this result has not previously been established at this level of generality. The second part of the traditional statement of Engel's theorem concerns nilpotency of the Lie algebra and a proof of this for general coefficients appeared in the literature as long ago [as 1937](zorn1937). This also follows trivially from `lie_module.is_nilpotent_iff_forall` simply by taking `M = L`. It is pleasing that the two parts of the traditional statements of Engel's theorem are thus unified into a single statement about nilpotency of Lie modules. This is not usually emphasised. ## Main definitions * `lie_algebra.is_engelian` * `lie_algebra.is_engelian_of_is_noetherian` * `lie_module.is_nilpotent_iff_forall` * `lie_algebra.is_nilpotent_iff_forall` -/ universes u₁ u₂ u₃ u₄ variables {R : Type u₁} {L : Type u₂} {L₂ : Type u₃} {M : Type u₄} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L₂] [lie_algebra R L₂] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] include R L namespace lie_submodule open lie_module variables {I : lie_ideal R L} {x : L} (hxI : (R ∙ x) ⊔ I = ⊤) include hxI lemma exists_smul_add_of_span_sup_eq_top (y : L) : ∃ (t : R) (z ∈ I), y = t • x + z := begin have hy : y ∈ (⊤ : submodule R L) := submodule.mem_top, simp only [← hxI, submodule.mem_sup, submodule.mem_span_singleton] at hy, obtain ⟨-, ⟨t, rfl⟩, z, hz, rfl⟩ := hy, exact ⟨t, z, hz, rfl⟩, end lemma lie_top_eq_of_span_sup_eq_top (N : lie_submodule R L M) : (↑⁅(⊤ : lie_ideal R L), N⁆ : submodule R M) = (N : submodule R M).map (to_endomorphism R L M x) ⊔ (↑⁅I, N⁆ : submodule R M) := begin simp only [lie_ideal_oper_eq_linear_span', submodule.sup_span, mem_top, exists_prop, exists_true_left, submodule.map_coe, to_endomorphism_apply_apply], refine le_antisymm (submodule.span_le.mpr _) (submodule.span_mono (λ z hz, _)), { rintros z ⟨y, n, hn : n ∈ N, rfl⟩, obtain ⟨t, z, hz, rfl⟩ := exists_smul_add_of_span_sup_eq_top hxI y, simp only [set_like.mem_coe, submodule.span_union, submodule.mem_sup], exact ⟨t • ⁅x, n⁆, submodule.subset_span ⟨t • n, N.smul_mem' t hn, lie_smul t x n⟩, ⁅z, n⁆, submodule.subset_span ⟨z, hz, n, hn, rfl⟩, by simp⟩, }, { rcases hz with ⟨m, hm, rfl⟩ | ⟨y, hy, m, hm, rfl⟩, exacts [⟨x, m, hm, rfl⟩, ⟨y, m, hm, rfl⟩], }, end lemma lcs_le_lcs_of_is_nilpotent_span_sup_eq_top {n i j : ℕ} (hxn : (to_endomorphism R L M x)^n = 0) (hIM : lower_central_series R L M i ≤ I.lcs M j) : lower_central_series R L M (i + n) ≤ I.lcs M (j + 1) := begin suffices : ∀ l, ((⊤ : lie_ideal R L).lcs M (i + l) : submodule R M) ≤ (I.lcs M j : submodule R M).map ((to_endomorphism R L M x)^l) ⊔ (I.lcs M (j + 1) : submodule R M), { simpa only [bot_sup_eq, lie_ideal.incl_coe, submodule.map_zero, hxn] using this n, }, intros l, induction l with l ih, { simp only [add_zero, lie_ideal.lcs_succ, pow_zero, linear_map.one_eq_id, submodule.map_id], exact le_sup_of_le_left hIM, }, { simp only [lie_ideal.lcs_succ, i.add_succ l, lie_top_eq_of_span_sup_eq_top hxI, sup_le_iff], refine ⟨(submodule.map_mono ih).trans _, le_sup_of_le_right _⟩, { rw [submodule.map_sup, ← submodule.map_comp, ← linear_map.mul_eq_comp, ← pow_succ, ← I.lcs_succ], exact sup_le_sup_left coe_map_to_endomorphism_le _, }, { refine le_trans (mono_lie_right _ _ I _) (mono_lie_right _ _ I hIM), exact antitone_lower_central_series R L M le_self_add, }, }, end lemma is_nilpotent_of_is_nilpotent_span_sup_eq_top (hnp : is_nilpotent $ to_endomorphism R L M x) (hIM : is_nilpotent R I M) : is_nilpotent R L M := begin obtain ⟨n, hn⟩ := hnp, unfreezingI { obtain ⟨k, hk⟩ := hIM, }, have hk' : I.lcs M k = ⊥, { simp only [← coe_to_submodule_eq_iff, I.coe_lcs_eq, hk, bot_coe_submodule], }, suffices : ∀ l, lower_central_series R L M (l * n) ≤ I.lcs M l, { use k * n, simpa [hk'] using this k, }, intros l, induction l with l ih, { simp, }, { exact (l.succ_mul n).symm ▸ lcs_le_lcs_of_is_nilpotent_span_sup_eq_top hxI hn ih, }, end end lie_submodule section lie_algebra open lie_module (hiding is_nilpotent) variables (R L) /-- A Lie algebra `L` is said to be Engelian if a sufficient condition for any `L`-Lie module `M` to be nilpotent is that the image of the map `L → End(M)` consists of nilpotent elements. Engel's theorem `lie_algebra.is_engelian_of_is_noetherian` states that any Noetherian Lie algebra is Engelian. -/ def lie_algebra.is_engelian : Prop := ∀ (M : Type u₄) [add_comm_group M], by exactI ∀ [module R M] [lie_ring_module L M], by exactI ∀ [lie_module R L M], by exactI ∀ (h : ∀ (x : L), is_nilpotent (to_endomorphism R L M x)), lie_module.is_nilpotent R L M variables {R L} lemma lie_algebra.is_engelian_of_subsingleton [subsingleton L] : lie_algebra.is_engelian R L := begin intros M _i1 _i2 _i3 _i4 h, use 1, suffices : (⊤ : lie_ideal R L) = ⊥, { simp [this], }, haveI := (lie_submodule.subsingleton_iff R L L).mpr infer_instance, apply subsingleton.elim, end lemma function.surjective.is_engelian {f : L →ₗ⁅R⁆ L₂} (hf : function.surjective f) (h : lie_algebra.is_engelian.{u₁ u₂ u₄} R L) : lie_algebra.is_engelian.{u₁ u₃ u₄} R L₂ := begin introsI M _i1 _i2 _i3 _i4 h', letI : lie_ring_module L M := lie_ring_module.comp_lie_hom M f, letI : lie_module R L M := comp_lie_hom M f, have hnp : ∀ x, is_nilpotent (to_endomorphism R L M x) := λ x, h' (f x), have surj_id : function.surjective (linear_map.id : M →ₗ[R] M) := function.surjective_id, haveI : lie_module.is_nilpotent R L M := h M hnp, apply hf.lie_module_is_nilpotent surj_id, simp, end lemma lie_equiv.is_engelian_iff (e : L ≃ₗ⁅R⁆ L₂) : lie_algebra.is_engelian.{u₁ u₂ u₄} R L ↔ lie_algebra.is_engelian.{u₁ u₃ u₄} R L₂ := ⟨e.surjective.is_engelian, e.symm.surjective.is_engelian⟩ lemma lie_algebra.exists_engelian_lie_subalgebra_of_lt_normalizer {K : lie_subalgebra R L} (hK₁ : lie_algebra.is_engelian.{u₁ u₂ u₄} R K) (hK₂ : K < K.normalizer) : ∃ (K' : lie_subalgebra R L) (hK' : lie_algebra.is_engelian.{u₁ u₂ u₄} R K'), K < K' := begin obtain ⟨x, hx₁, hx₂⟩ := set_like.exists_of_lt hK₂, let K' : lie_subalgebra R L := { lie_mem' := λ y z, lie_subalgebra.lie_mem_sup_of_mem_normalizer hx₁, .. (R ∙ x) ⊔ (K : submodule R L) }, have hxK' : x ∈ K' := submodule.mem_sup_left (submodule.subset_span (set.mem_singleton _)), have hKK' : K ≤ K' := (lie_subalgebra.coe_submodule_le_coe_submodule K K').mp le_sup_right, have hK' : K' ≤ K.normalizer, { rw ← lie_subalgebra.coe_submodule_le_coe_submodule, exact sup_le ((submodule.span_singleton_le_iff_mem _ _).mpr hx₁) hK₂.le, }, refine ⟨K', _, lt_iff_le_and_ne.mpr ⟨hKK', λ contra, hx₂ (contra.symm ▸ hxK')⟩⟩, introsI M _i1 _i2 _i3 _i4 h, obtain ⟨I, hI₁ : (I : lie_subalgebra R K') = lie_subalgebra.of_le hKK'⟩ := lie_subalgebra.exists_nested_lie_ideal_of_le_normalizer hKK' hK', have hI₂ : (R ∙ (⟨x, hxK'⟩ : K')) ⊔ I = ⊤, { rw [← lie_ideal.coe_to_lie_subalgebra_to_submodule R K' I, hI₁], apply submodule.map_injective_of_injective (K' : submodule R L).injective_subtype, simpa, }, have e : K ≃ₗ⁅R⁆ I := (lie_subalgebra.equiv_of_le hKK').trans (lie_equiv.of_eq _ _ ((lie_subalgebra.coe_set_eq _ _).mpr hI₁.symm)), have hI₃ : lie_algebra.is_engelian R I := e.is_engelian_iff.mp hK₁, exact lie_submodule.is_nilpotent_of_is_nilpotent_span_sup_eq_top hI₂ (h _) (hI₃ _ (λ x, h x)), end local attribute [instance] lie_subalgebra.subsingleton_bot variables [is_noetherian R L] /-- *Engel's theorem*. Note that this implies all traditional forms of Engel's theorem via `lie_module.nontrivial_max_triv_of_is_nilpotent`, `lie_module.is_nilpotent_iff_forall`, `lie_algebra.is_nilpotent_iff_forall`. -/ lemma lie_algebra.is_engelian_of_is_noetherian : lie_algebra.is_engelian R L := begin introsI M _i1 _i2 _i3 _i4 h, rw ← is_nilpotent_range_to_endomorphism_iff, let L' := (to_endomorphism R L M).range, replace h : ∀ (y : L'), is_nilpotent (y : module.End R M), { rintros ⟨-, ⟨y, rfl⟩⟩, simp [h], }, change lie_module.is_nilpotent R L' M, let s := { K : lie_subalgebra R L' | lie_algebra.is_engelian R K }, have hs : s.nonempty := ⟨⊥, lie_algebra.is_engelian_of_subsingleton⟩, suffices : ⊤ ∈ s, { rw ← is_nilpotent_of_top_iff, apply this M, simp [lie_subalgebra.to_endomorphism_eq, h], }, have : ∀ (K ∈ s), K ≠ ⊤ → ∃ (K' ∈ s), K < K', { rintros K (hK₁ : lie_algebra.is_engelian R K) hK₂, apply lie_algebra.exists_engelian_lie_subalgebra_of_lt_normalizer hK₁, apply lt_of_le_of_ne K.le_normalizer, rw [ne.def, eq_comm, K.normalizer_eq_self_iff, ← ne.def, ← lie_submodule.nontrivial_iff_ne_bot R K], haveI : nontrivial (L' ⧸ K.to_lie_submodule), { replace hK₂ : K.to_lie_submodule ≠ ⊤ := by rwa [ne.def, ← lie_submodule.coe_to_submodule_eq_iff, K.coe_to_lie_submodule, lie_submodule.top_coe_submodule, ← lie_subalgebra.top_coe_submodule, K.coe_to_submodule_eq_iff], exact submodule.quotient.nontrivial_of_lt_top _ hK₂.lt_top, }, haveI : lie_module.is_nilpotent R K (L' ⧸ K.to_lie_submodule), { refine hK₁ _ (λ x, _), have hx := lie_algebra.is_nilpotent_ad_of_is_nilpotent (h x), exact module.End.is_nilpotent.mapq _ hx, }, exact nontrivial_max_triv_of_is_nilpotent R K (L' ⧸ K.to_lie_submodule), }, haveI _i5 : is_noetherian R L' := is_noetherian_of_surjective L _ (linear_map.range_range_restrict (to_endomorphism R L M)), obtain ⟨K, hK₁, hK₂⟩ := (lie_subalgebra.well_founded_of_noetherian R L').has_min s hs, have hK₃ : K = ⊤, { by_contra contra, obtain ⟨K', hK'₁, hK'₂⟩ := this K hK₁ contra, exact hK₂ K' hK'₁ hK'₂, }, exact hK₃ ▸ hK₁, end /-- Engel's theorem. -/ lemma lie_module.is_nilpotent_iff_forall : lie_module.is_nilpotent R L M ↔ ∀ x, is_nilpotent $ to_endomorphism R L M x := ⟨begin introsI h, obtain ⟨k, hk⟩ := nilpotent_endo_of_nilpotent_module R L M, exact λ x, ⟨k, hk x⟩, end, λ h, lie_algebra.is_engelian_of_is_noetherian M h⟩ /-- Engel's theorem. -/ lemma lie_algebra.is_nilpotent_iff_forall : lie_algebra.is_nilpotent R L ↔ ∀ x, is_nilpotent $ lie_algebra.ad R L x := lie_module.is_nilpotent_iff_forall end lie_algebra
2014c27092959255ccac34acf117932bd09b1dbd
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/vector_bundle/hom.lean
a21c54f6ffe811e93a1dc0049434ef23c6f80837
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
14,397
lean
/- Copyright © 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Floris van Doorn -/ import topology.vector_bundle.basic import analysis.normed_space.operator_norm /-! # The topological vector bundle of continuous (semi)linear maps We define the topological vector bundle of continuous (semi)linear maps between two vector bundles over the same base. Given bundles `E₁ E₂ : B → Type*`, we define `bundle.continuous_linear_map 𝕜 E₁ E₂ := λ x, E₁ x →SL[𝕜] E₂ x`. If the `E₁` and `E₂` are topological vector bundles with fibers `F₁` and `F₂`, then this will be a topological vector bundle with fiber `F₁ →SL[𝕜] F₂`. The topology is inherited from the norm-topology on, without the need to define the strong topology on continuous linear maps between general topological vector spaces. ## Main Definitions * `bundle.continuous_linear_map.topological_vector_bundle`: continuous semilinear maps between vector bundles form a vector bundle. -/ noncomputable theory open bundle set continuous_linear_map section defs variables {𝕜₁ 𝕜₂ : Type*} [normed_field 𝕜₁] [normed_field 𝕜₂] variables (σ : 𝕜₁ →+* 𝕜₂) variables {B : Type*} variables (F₁ : Type*) (E₁ : B → Type*) [Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜₁ (E₁ x)] variables [Π x : B, topological_space (E₁ x)] variables (F₂ : Type*) (E₂ : B → Type*) [Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜₂ (E₂ x)] variables [Π x : B, topological_space (E₂ x)] include F₁ F₂ -- In this definition we require the scalar rings `𝕜₁` and `𝕜₂` to be normed fields, although -- something much weaker (maybe `comm_semiring`) would suffice mathematically -- this is because of -- a typeclass inference bug with pi-types: -- https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/vector.20bundles.20--.20typeclass.20inference.20issue /-- The bundle of continuous `σ`-semilinear maps between the topological vector bundles `E₁` and `E₂`. This is a type synonym for `λ x, E₁ x →SL[σ] E₂ x`. We intentionally add `F₁` and `F₂` as arguments to this type, so that instances on this type (that depend on `F₁` and `F₂`) actually refer to `F₁` and `F₂`. -/ @[derive inhabited, nolint unused_arguments] def bundle.continuous_linear_map (x : B) : Type* := E₁ x →SL[σ] E₂ x instance bundle.continuous_linear_map.add_monoid_hom_class (x : B) : add_monoid_hom_class (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) (E₁ x) (E₂ x) := by delta_instance bundle.continuous_linear_map variables [Π x, has_continuous_add (E₂ x)] instance (x : B) : add_comm_monoid (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) := by delta_instance bundle.continuous_linear_map variables [∀ x, has_continuous_smul 𝕜₂ (E₂ x)] instance (x : B) : module 𝕜₂ (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) := by delta_instance bundle.continuous_linear_map end defs variables {𝕜₁ : Type*} [nontrivially_normed_field 𝕜₁] {𝕜₂ : Type*} [nontrivially_normed_field 𝕜₂] (σ : 𝕜₁ →+* 𝕜₂) variables {B : Type*} [topological_space B] variables (F₁ : Type*) [normed_add_comm_group F₁] [normed_space 𝕜₁ F₁] (E₁ : B → Type*) [Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜₁ (E₁ x)] [topological_space (total_space E₁)] variables (F₂ : Type*) [normed_add_comm_group F₂][normed_space 𝕜₂ F₂] (E₂ : B → Type*) [Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜₂ (E₂ x)] [topological_space (total_space E₂)] namespace topological_vector_bundle variables {F₁ E₁ F₂ E₂} (e₁ e₁' : trivialization 𝕜₁ F₁ E₁) (e₂ e₂' : trivialization 𝕜₂ F₂ E₂) variables [ring_hom_isometric σ] namespace pretrivialization /-- Assume `eᵢ` and `eᵢ'` are trivializations of the bundles `Eᵢ` over base `B` with fiber `Fᵢ` (`i ∈ {1,2}`), then `continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂'` is the coordinate change function between the two induced (pre)trivializations `pretrivialization.continuous_linear_map σ e₁ e₂` and `pretrivialization.continuous_linear_map σ e₁' e₂'` of `bundle.continuous_linear_map`. -/ def continuous_linear_map_coord_change (b : B) : (F₁ →SL[σ] F₂) →L[𝕜₂] F₁ →SL[σ] F₂ := ((e₁'.coord_change e₁ b).symm.arrow_congrSL (e₂.coord_change e₂' b) : (F₁ →SL[σ] F₂) ≃L[𝕜₂] F₁ →SL[σ] F₂) variables {σ e₁ e₁' e₂ e₂'} variables [Π x : B, topological_space (E₁ x)] [topological_vector_bundle 𝕜₁ F₁ E₁] variables [Π x : B, topological_space (E₂ x)] [topological_vector_bundle 𝕜₂ F₂ E₂] lemma continuous_on_continuous_linear_map_coord_change (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₁' : e₁' ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) (he₂' : e₂' ∈ trivialization_atlas 𝕜₂ F₂ E₂) : continuous_on (continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂') ((e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) := begin have h₁ := (compSL F₁ F₂ F₂ σ (ring_hom.id 𝕜₂)).continuous, have h₂ := (continuous_linear_map.flip (compSL F₁ F₁ F₂ (ring_hom.id 𝕜₁) σ)).continuous, have h₃ := (continuous_on_coord_change e₁' he₁' e₁ he₁), have h₄ := (continuous_on_coord_change e₂ he₂ e₂' he₂'), refine ((h₁.comp_continuous_on (h₄.mono _)).clm_comp (h₂.comp_continuous_on (h₃.mono _))).congr _, { mfld_set_tac }, { mfld_set_tac }, { intros b hb, ext L v, simp only [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, comp_apply, function.comp, compSL_apply, flip_apply, continuous_linear_equiv.symm_symm] }, end variables (σ e₁ e₁' e₂ e₂') variables [Π x, has_continuous_add (E₂ x)] [Π x, has_continuous_smul 𝕜₂ (E₂ x)] /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, `pretrivialization.continuous_linear_map σ e₁ e₂` is the induced pretrivialization for the continuous `σ`-semilinear maps from `E₁` to `E₂`. That is, the map which will later become a trivialization, after the bundle of continuous semilinear maps is equipped with the right topological vector bundle structure. -/ def continuous_linear_map : pretrivialization 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := { to_fun := λ p, ⟨p.1, (e₂.continuous_linear_map_at p.1).comp $ p.2.comp $ e₁.symmL p.1⟩, inv_fun := λ p, ⟨p.1, (e₂.symmL p.1).comp $ p.2.comp $ e₁.continuous_linear_map_at p.1⟩, source := (bundle.total_space.proj) ⁻¹' (e₁.base_set ∩ e₂.base_set), target := (e₁.base_set ∩ e₂.base_set) ×ˢ set.univ, map_source' := λ ⟨x, L⟩ h, ⟨h, set.mem_univ _⟩, map_target' := λ ⟨x, f⟩ h, h.1, left_inv' := λ ⟨x, L⟩ ⟨h₁, h₂⟩, begin simp_rw [sigma.mk.inj_iff, eq_self_iff_true, heq_iff_eq, true_and], ext v, simp only [comp_apply, trivialization.symmL_continuous_linear_map_at, h₁, h₂] end, right_inv' := λ ⟨x, f⟩ ⟨⟨h₁, h₂⟩, _⟩, begin simp_rw [prod.mk.inj_iff, eq_self_iff_true, true_and], ext v, simp only [comp_apply, trivialization.continuous_linear_map_at_symmL, h₁, h₂] end, open_target := (e₁.open_base_set.inter e₂.open_base_set).prod is_open_univ, base_set := e₁.base_set ∩ e₂.base_set, open_base_set := e₁.open_base_set.inter e₂.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := λ ⟨x, f⟩ h, rfl, linear' := λ x h, { map_add := λ L L', by simp_rw [add_comp, comp_add], map_smul := λ c L, by simp_rw [smul_comp, comp_smulₛₗ, ring_hom.id_apply] } } lemma continuous_linear_map_apply (p : total_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂)) : (continuous_linear_map σ e₁ e₂) p = ⟨p.1, (e₂.continuous_linear_map_at p.1).comp $ p.2.comp $ e₁.symmL p.1⟩ := rfl lemma continuous_linear_map_symm_apply (p : B × (F₁ →SL[σ] F₂)) : (continuous_linear_map σ e₁ e₂).to_local_equiv.symm p = ⟨p.1, (e₂.symmL p.1).comp $ p.2.comp $ e₁.continuous_linear_map_at p.1⟩ := rfl lemma continuous_linear_map_symm_apply' {b : B} (hb : b ∈ e₁.base_set ∩ e₂.base_set) (L : F₁ →SL[σ] F₂) : (continuous_linear_map σ e₁ e₂).symm b L = (e₂.symmL b).comp (L.comp $ e₁.continuous_linear_map_at b) := begin rw [symm_apply], refl, exact hb end lemma continuous_linear_map_coord_change_apply (b : B) (hb : b ∈ (e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) (L : F₁ →SL[σ] F₂) : continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂' b L = (continuous_linear_map σ e₁' e₂' (total_space_mk b ((continuous_linear_map σ e₁ e₂).symm b L))).2 := begin ext v, simp_rw [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, continuous_linear_map_apply, continuous_linear_map_symm_apply' σ e₁ e₂ hb.1, comp_apply, continuous_linear_equiv.coe_coe, continuous_linear_equiv.symm_symm, trivialization.continuous_linear_map_at_apply, trivialization.symmL_apply], dsimp only [total_space_mk], rw [e₂.coord_change_apply e₂', e₁'.coord_change_apply e₁, e₁.coe_linear_map_at_of_mem hb.1.1, e₂'.coe_linear_map_at_of_mem hb.2.2], exacts [⟨hb.2.1, hb.1.1⟩, ⟨hb.1.2, hb.2.2⟩] end end pretrivialization open pretrivialization variables (F₁ E₁ F₂ E₂) variables [Π x : B, topological_space (E₁ x)] [topological_vector_bundle 𝕜₁ F₁ E₁] variables [Π x : B, topological_space (E₂ x)] [topological_vector_bundle 𝕜₂ F₂ E₂] variables [Π x, has_continuous_add (E₂ x)] [Π x, has_continuous_smul 𝕜₂ (E₂ x)] /-- The continuous `σ`-semilinear maps between two topological vector bundles form a `topological_vector_prebundle` (this is an auxiliary construction for the `topological_vector_bundle` instance, in which the pretrivializations are collated but no topology on the total space is yet provided). -/ def _root_.bundle.continuous_linear_map.topological_vector_prebundle : topological_vector_prebundle 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := { pretrivialization_atlas := image2 (λ e₁ e₂, pretrivialization.continuous_linear_map σ e₁ e₂) (trivialization_atlas 𝕜₁ F₁ E₁) (trivialization_atlas 𝕜₂ F₂ E₂), pretrivialization_at := λ x, pretrivialization.continuous_linear_map σ (trivialization_at 𝕜₁ F₁ E₁ x) (trivialization_at 𝕜₂ F₂ E₂ x), mem_base_pretrivialization_at := λ x, ⟨mem_base_set_trivialization_at 𝕜₁ F₁ E₁ x, mem_base_set_trivialization_at 𝕜₂ F₂ E₂ x⟩, pretrivialization_mem_atlas := λ x, ⟨_, _, trivialization_mem_atlas 𝕜₁ F₁ E₁ x, trivialization_mem_atlas 𝕜₂ F₂ E₂ x, rfl⟩, exists_coord_change := by { rintro _ ⟨e₁, e₂, he₁, he₂, rfl⟩ _ ⟨e₁', e₂', he₁', he₂', rfl⟩, exact ⟨continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂', continuous_on_continuous_linear_map_coord_change he₁ he₁' he₂ he₂', continuous_linear_map_coord_change_apply σ e₁ e₁' e₂ e₂'⟩ } } /-- Topology on the continuous `σ`-semilinear_maps between the respective fibers at a point of two "normable" vector bundles over the same base. Here "normable" means that the bundles have fibers modelled on normed spaces `F₁`, `F₂` respectively. The topology we put on the continuous `σ`-semilinear_maps is the topology coming from the operator norm on maps from `F₁` to `F₂`. -/ instance (x : B) : topological_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂).fiber_topology x /-- Topology on the total space of the continuous `σ`-semilinear_maps between two "normable" vector bundles over the same base. -/ instance : topological_space (total_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂)) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂).total_space_topology /-- The continuous `σ`-semilinear_maps between two vector bundles form a vector bundle. -/ instance _root_.bundle.continuous_linear_map.topological_vector_bundle : topological_vector_bundle 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂).to_topological_vector_bundle variables {F₁ E₁ F₂ E₂} /-- Given trivializations `e₁`, `e₂` in the atlas for vector bundles `E₁`, `E₂` over a base `B`, the induced trivialization for the continuous `σ`-semilinear maps from `E₁` to `E₂`, whose base set is `e₁.base_set ∩ e₂.base_set`. -/ def trivialization.continuous_linear_map (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) : trivialization 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂) .trivialization_of_mem_pretrivialization_atlas (mem_image2_of_mem he₁ he₂) variables {e₁ e₂} @[simp] lemma trivialization.base_set_continuous_linear_map (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) : (e₁.continuous_linear_map σ e₂ he₁ he₂).base_set = e₁.base_set ∩ e₂.base_set := rfl lemma trivialization.continuous_linear_map_apply (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) (p : total_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂)) : e₁.continuous_linear_map σ e₂ he₁ he₂ p = ⟨p.1, (e₂.continuous_linear_map_at p.1).comp $ p.2.comp $ e₁.symmL p.1⟩ := rfl end topological_vector_bundle
61a446a35415b2a785093b9aa4583219916a40ca
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/nat/neg_elim.lean
78029323c88239f25e2b6692317b82a8331dcc20
[ "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
4,192
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Negation elimination. -/ import tactic.omega.nat.form namespace omega namespace nat open_locale omega.nat /-- push_neg p returns the result of normalizing ¬ p by pushing the outermost negation all the way down, until it reaches either a negation or an atom -/ @[simp] def push_neg : preform → preform | (p ∨* q) := (push_neg p) ∧* (push_neg q) | (p ∧* q) := (push_neg p) ∨* (push_neg q) | (¬*p) := p | p := ¬* p lemma push_neg_equiv : ∀ {p : preform}, preform.equiv (push_neg p) (¬* p) := begin preform.induce `[intros v; try {refl}], { simp only [classical.not_not, preform.holds, push_neg] }, { simp only [preform.holds, push_neg, not_or_distrib, ihp v, ihq v] }, { simp only [preform.holds, push_neg, classical.not_and_distrib, ihp v, ihq v] } end /-- NNF transformation -/ def nnf : preform → preform | (¬* p) := push_neg (nnf p) | (p ∨* q) := (nnf p) ∨* (nnf q) | (p ∧* q) := (nnf p) ∧* (nnf q) | a := a /-- Asserts that the given preform is in NNF -/ def is_nnf : preform → Prop | (t =* s) := true | (t ≤* s) := true | ¬*(t =* s) := true | ¬*(t ≤* s) := true | (p ∨* q) := is_nnf p ∧ is_nnf q | (p ∧* q) := is_nnf p ∧ is_nnf q | _ := false lemma is_nnf_push_neg : ∀ p : preform, is_nnf p → is_nnf (push_neg p) := begin preform.induce `[intro h1; try {trivial}], { cases p; try {cases h1}; trivial }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption } end lemma is_nnf_nnf : ∀ p : preform, is_nnf (nnf p) := begin preform.induce `[try {trivial}], { apply is_nnf_push_neg _ ih }, { constructor; assumption }, { constructor; assumption } end lemma nnf_equiv : ∀ {p : preform}, preform.equiv (nnf p) p := begin preform.induce `[intros v; try {refl}; simp only [nnf]], { rw push_neg_equiv, apply not_iff_not_of_iff, apply ih }, { apply pred_mono_2' (ihp v) (ihq v) }, { apply pred_mono_2' (ihp v) (ihq v) } end @[simp] def neg_elim_core : preform → preform | (¬* (t =* s)) := (t.add_one ≤* s) ∨* (s.add_one ≤* t) | (¬* (t ≤* s)) := s.add_one ≤* t | (p ∨* q) := (neg_elim_core p) ∨* (neg_elim_core q) | (p ∧* q) := (neg_elim_core p) ∧* (neg_elim_core q) | p := p lemma neg_free_neg_elim_core : ∀ p, is_nnf p → (neg_elim_core p).neg_free := begin preform.induce `[intro h1, try {simp only [neg_free, neg_elim_core]}, try {trivial}], { cases p; try {cases h1}; try {trivial}, constructor; trivial }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption } end lemma le_and_le_iff_eq {α : Type} [partial_order α] {a b : α} : (a ≤ b ∧ b ≤ a) ↔ a = b := begin constructor; intro h1, { cases h1, apply le_antisymm; assumption }, { constructor; apply le_of_eq; rw h1 } end lemma implies_neg_elim_core : ∀ {p : preform}, preform.implies p (neg_elim_core p) := begin preform.induce `[intros v h, try {apply h}], { cases p with t s t s; try {apply h}, { have : preterm.val v (preterm.add_one t) ≤ preterm.val v s ∨ preterm.val v (preterm.add_one s) ≤ preterm.val v t, { rw or.comm, simpa only [preform.holds, le_and_le_iff_eq.symm, classical.not_and_distrib, not_le] using h }, simpa only [form.holds, neg_elim_core, int.add_one_le_iff] }, simpa only [preform.holds, not_le, int.add_one_le_iff] using h }, { simp only [neg_elim_core], cases h; [{left, apply ihp}, {right, apply ihq}]; assumption }, apply and.imp (ihp _) (ihq _) h end /-- Eliminate all negations in a preform -/ def neg_elim : preform → preform := neg_elim_core ∘ nnf lemma neg_free_neg_elim {p : preform} : (neg_elim p).neg_free := neg_free_neg_elim_core _ (is_nnf_nnf _) lemma implies_neg_elim {p : preform} : preform.implies p (neg_elim p) := begin intros v h1, apply implies_neg_elim_core, apply (nnf_equiv v).elim_right h1 end end nat end omega
d21b238523d4482548ff0a50e4055bbb3dd363eb
9338c56dfd6ceacc3e5e63e32a7918cfec5d5c69
/src/Kenny/sheaf_of_rings_on_opens.lean
7a3ad99e3e3bfab6ec4d8b124c1510b31f1a36d8
[]
no_license
Project-Reykjavik/lean-scheme
7322eefce504898ba33737970be89dc751108e2b
6d3ec18fecfd174b79d0ce5c85a783f326dd50f6
refs/heads/master
1,669,426,172,632
1,578,284,588,000
1,578,284,588,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,837
lean
import sheaves.sheaf_of_rings Kenny.sheaf_on_opens ring_theory.subring universes v w u₁ v₁ u open topological_space lattice def sheaf_of_rings_on_opens (X : Type u) [topological_space X] (U : opens X) : Type (max u (v+1)) := sheaf_of_rings.{u v} X namespace sheaf_of_rings_on_opens variables {X : Type u} [topological_space X] {U : opens X} def to_sheaf_on_opens (F : sheaf_of_rings_on_opens X U) : sheaf_on_opens X U := { locality := F.2, gluing := F.3, .. F.F } -- def eval (F : sheaf_of_rings_on_opens X U) : Π (V : opens X), V ≤ U → Type v := -- F.to_sheaf_on_opens.eval instance comm_ring_eval (F : sheaf_of_rings_on_opens X U) (V HVU) : comm_ring (F.to_sheaf_on_opens.eval V HVU) := F.1.2 V -- def res (F : sheaf_of_rings_on_opens X U) : Π (V : opens X) (HVU : V ≤ U) (W : opens X) (HWU : W ≤ U) (HWV : W ≤ V), F.to_sheaf_on_opens.eval V HVU → F.to_sheaf_on_opens.eval W HWU := -- F.to_sheaf_on_opens.res instance is_ring_hom_res (F : sheaf_of_rings_on_opens X U) (V HVU W HWU HWV) : is_ring_hom (F.to_sheaf_on_opens.res V HVU W HWU HWV) := F.1.3 V W HWV section variables (F : sheaf_of_rings_on_opens X U) (V : opens X) (HVU : V ≤ U) (W : opens X) (HWU : W ≤ U) (HWV : W ≤ V) variables (x y : F.to_sheaf_on_opens.eval V HVU) (n : ℕ) @[simp] lemma res_add : F.to_sheaf_on_opens.res V HVU W HWU HWV (x + y) = F.to_sheaf_on_opens.res V HVU W HWU HWV x + F.to_sheaf_on_opens.res V HVU W HWU HWV y := is_ring_hom.map_add _ @[simp] lemma res_zero : F.to_sheaf_on_opens.res V HVU W HWU HWV 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma res_neg : F.to_sheaf_on_opens.res V HVU W HWU HWV (-x) = -F.to_sheaf_on_opens.res V HVU W HWU HWV x := is_ring_hom.map_neg _ @[simp] lemma res_sub : F.to_sheaf_on_opens.res V HVU W HWU HWV (x - y) = F.to_sheaf_on_opens.res V HVU W HWU HWV x - F.to_sheaf_on_opens.res V HVU W HWU HWV y := is_ring_hom.map_sub _ @[simp] lemma res_mul : F.to_sheaf_on_opens.res V HVU W HWU HWV (x * y) = F.to_sheaf_on_opens.res V HVU W HWU HWV x * F.to_sheaf_on_opens.res V HVU W HWU HWV y := is_ring_hom.map_mul _ @[simp] lemma res_one : F.to_sheaf_on_opens.res V HVU W HWU HWV 1 = 1 := is_ring_hom.map_one _ @[simp] lemma res_pow : F.to_sheaf_on_opens.res V HVU W HWU HWV (x^n) = (F.to_sheaf_on_opens.res V HVU W HWU HWV x)^n := is_semiring_hom.map_pow _ x n end theorem res_self (F : sheaf_of_rings_on_opens X U) (V HVU HV x) : F.to_sheaf_on_opens.res V HVU V HVU HV x = x := F.to_sheaf_on_opens.res_self V HVU HV x theorem res_res (F : sheaf_of_rings_on_opens X U) (V HVU W HWU HWV S HSU HSW x) : F.to_sheaf_on_opens.res W HWU S HSU HSW (F.to_sheaf_on_opens.res V HVU W HWU HWV x) = F.to_sheaf_on_opens.res V HVU S HSU (le_trans HSW HWV) x := F.to_sheaf_on_opens.res_res V HVU W HWU HWV S HSU HSW x theorem locality (F : sheaf_of_rings_on_opens X U) (V HVU s t) (OC : covering V) (H : ∀ i : OC.γ, F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) s = F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) t) : s = t := F.locality OC s t H -- noncomputable def glue (F : sheaf_of_rings_on_opens X U) (V HVU) (OC : covering V) -- (s : Π i : OC.γ, F.to_sheaf_on_opens.eval (OC.Uis i) (le_trans (subset_covering i) HVU)) -- (H : ∀ i j : OC.γ, F.to_sheaf_on_opens.res _ _ (OC.Uis i ⊓ OC.Uis j) (le_trans inf_le_left (le_trans (subset_covering i) HVU)) inf_le_left (s i) = -- F.to_sheaf_on_opens.res _ _ (OC.Uis i ⊓ OC.Uis j) (le_trans inf_le_left (le_trans (subset_covering i) HVU)) inf_le_right (s j)) : -- F.to_sheaf_on_opens.eval V HVU := -- classical.some $ F.gluing OC s H -- theorem res_glue (F : sheaf_of_rings_on_opens X U) (V HVU) (OC : covering V) (s H i) : -- F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) (F.glue V HVU OC s H) = s i := -- classical.some_spec (F.gluing OC s H) i -- theorem eq_glue (F : sheaf_of_rings_on_opens X U) (V HVU) (OC : covering V) -- (s : Π i : OC.γ, F.to_sheaf_on_opens.eval (OC.Uis i) (le_trans (subset_covering i) HVU)) (H t) -- (ht : ∀ i, F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) t = s i) : -- F.glue V HVU OC s H = t := -- F.locality V HVU _ _ OC $ λ i, by rw [res_glue, ht] def res_subset (F : sheaf_of_rings_on_opens X U) (V : opens X) (HVU : V ≤ U) : sheaf_of_rings_on_opens X V := F theorem res_res_subset (F : sheaf_of_rings_on_opens X U) (V HVU S HSV T HTV HTS x) : (F.to_sheaf_on_opens.res_subset V HVU).res S HSV T HTV HTS x = F.to_sheaf_on_opens.res S (le_trans HSV HVU) T (le_trans HTV HVU) HTS x := rfl -- def stalk (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) : Type (max u v) := -- stalk_of_rings F.1 x instance comm_ring_stalk (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) : comm_ring (F.to_sheaf_on_opens.stalk x hx) := stalk_of_rings_is_comm_ring F.1 x -- def to_stalk (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) (V : opens X) (hxV : x ∈ V) (HVU : V ≤ U) (s : F.to_sheaf_on_opens.eval V HVU) : F.to_sheaf_on_opens.stalk x hx := -- F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s instance is_ring_hom_to_stalk (F : sheaf_of_rings_on_opens X U) (x hx V hxV HVU) : is_ring_hom (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU) := to_stalk.is_ring_hom _ _ _ _ section variables (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) (V : opens X) (hxV : x ∈ V) (HVU : V ≤ U) variables (s t : F.to_sheaf_on_opens.eval V HVU) (n : ℕ) @[simp] lemma to_stalk_add : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s + t) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s + F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t := is_ring_hom.map_add _ @[simp] lemma to_stalk_zero : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma to_stalk_neg : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (-s) = -F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s := is_ring_hom.map_neg _ @[simp] lemma to_stalk_sub : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s - t) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s - F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t := is_ring_hom.map_sub _ @[simp] lemma to_stalk_mul : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s * t) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s * F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t := is_ring_hom.map_mul _ @[simp] lemma to_stalk_one : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU 1 = 1 := is_ring_hom.map_one _ @[simp] lemma to_stalk_pow : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s^n) = (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s)^n := is_semiring_hom.map_pow _ s n end @[simp] lemma to_stalk_res (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) (V : opens X) (hxV : x ∈ V) (HVU : V ≤ U) (W : opens X) (hxW : x ∈ W) (HWV : W ≤ V) (s : F.to_sheaf_on_opens.eval V HVU) : F.to_sheaf_on_opens.to_stalk x hx W hxW (le_trans HWV HVU) (F.to_sheaf_on_opens.res _ _ _ _ HWV s) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s := to_stalk_res _ _ _ _ _ _ _ _ @[elab_as_eliminator] theorem stalk.induction_on {F : sheaf_of_rings_on_opens X U} {x : X} {hx : x ∈ U} {C : F.to_sheaf_on_opens.stalk x hx → Prop} (g : F.to_sheaf_on_opens.stalk x hx) (H : ∀ V : opens X, ∀ hxV : x ∈ V, ∀ HVU : V ≤ U, ∀ s : F.to_sheaf_on_opens.eval V HVU, C (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s)) : C g := quotient.induction_on g $ λ e, have (⟦e⟧ : F.to_sheaf_on_opens.stalk x hx) = ⟦⟨e.1 ⊓ U, ⟨e.2, hx⟩, F.F.res _ _ (set.inter_subset_left _ _) e.3⟩⟧, from quotient.sound ⟨e.1 ⊓ U, ⟨e.2, hx⟩, set.inter_subset_left _ _, set.subset.refl _, by dsimp only [to_sheaf_on_opens]; rw ← presheaf.Hcomp'; refl⟩, this.symm ▸ H (e.1 ⊓ U) ⟨e.2, hx⟩ inf_le_right _ @[elab_as_eliminator] theorem stalk.induction_on₂ {F : sheaf_of_rings_on_opens X U} {x : X} {hx : x ∈ U} {C : F.to_sheaf_on_opens.stalk x hx → F.to_sheaf_on_opens.stalk x hx → Prop} (g1 g2 : F.to_sheaf_on_opens.stalk x hx) (H : ∀ V : opens X, ∀ hxV : x ∈ V, ∀ HVU : V ≤ U, ∀ s t : F.to_sheaf_on_opens.eval V HVU, C (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s) (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t)) : C g1 g2 := quotient.induction_on₂ g1 g2 $ λ e1 e2, have h1 : (⟦e1⟧ : F.to_sheaf_on_opens.stalk x hx) = _root_.to_stalk F.F x (e1.1 ⊓ e2.1 ⊓ U) ⟨⟨e1.2, e2.2⟩, hx⟩ (F.F.res _ _ (λ p hp, hp.1.1) e1.3), by erw [_root_.to_stalk_res]; cases e1; refl, have h2 : (⟦e2⟧ : F.to_sheaf_on_opens.stalk x hx) = _root_.to_stalk F.F x (e1.1 ⊓ e2.1 ⊓ U) ⟨⟨e1.2, e2.2⟩, hx⟩ (F.F.res _ _ (λ p hp, hp.1.2) e2.3), by erw [_root_.to_stalk_res]; cases e2; refl, h1.symm ▸ h2.symm ▸ H _ _ inf_le_right _ _ structure morphism (F : sheaf_of_rings_on_opens.{v} X U) (G : sheaf_of_rings_on_opens.{w} X U) : Type (max u v w) := (η : F.to_sheaf_on_opens.morphism G.to_sheaf_on_opens) [hom : ∀ V HV, is_ring_hom (η.map V HV)] attribute [instance] morphism.hom namespace morphism section variables {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} variables (η : F.morphism G) (V : opens X) (HVU : V ≤ U) (x y : F.to_sheaf_on_opens.eval V HVU) (n : ℕ) @[simp] lemma map_add : η.1.map V HVU (x + y) = η.1.map V HVU x + η.1.map V HVU y := is_ring_hom.map_add _ @[simp] lemma map_zero : η.1.map V HVU 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma map_neg : η.1.map V HVU (-x) = -η.1.map V HVU x := is_ring_hom.map_neg _ @[simp] lemma map_sub : η.1.map V HVU (x - y) = η.1.map V HVU x - η.1.map V HVU y := is_ring_hom.map_sub _ @[simp] lemma map_mul : η.1.map V HVU (x * y) = η.1.map V HVU x * η.1.map V HVU y := is_ring_hom.map_mul _ @[simp] lemma map_one : η.1.map V HVU 1 = 1 := is_ring_hom.map_one _ @[simp] lemma map_pow : η.1.map V HVU (x^n) = (η.1.map V HVU x)^n := is_semiring_hom.map_pow _ x n end protected def id (F : sheaf_of_rings_on_opens.{v} X U) : F.morphism F := { η := sheaf_on_opens.morphism.id _, hom := λ _ _, is_ring_hom.id } def comp {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} (η : G.morphism H) (ξ : F.morphism G) : F.morphism H := { η := η.1.comp ξ.1, hom := λ _ _, is_ring_hom.comp _ _ } @[simp] lemma comp_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} (η : G.morphism H) (ξ : F.morphism G) (V HV s) : (η.comp ξ).1.1 V HV s = η.1.1 V HV (ξ.1.1 V HV s) := rfl @[ext] lemma ext {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {η ξ : F.morphism G} (H : ∀ V HV x, η.1.map V HV x = ξ.1.map V HV x) : η = ξ := by cases η; cases ξ; congr; ext; apply H @[simp] lemma id_comp {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) : (morphism.id G).comp η = η := ext $ λ V HV x, rfl @[simp] lemma comp_id {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) : η.comp (morphism.id F) = η := ext $ λ V HV x, rfl @[simp] lemma comp_assoc {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} {I : sheaf_of_rings_on_opens.{v₁} X U} (η : H.morphism I) (ξ : G.morphism H) (χ : F.morphism G) : (η.comp ξ).comp χ = η.comp (ξ.comp χ) := rfl def res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (V : opens X) (HVU : V ≤ U) : (F.res_subset V HVU).morphism (G.res_subset V HVU) := { η := η.1.res_subset V HVU, hom := λ _ _, η.2 _ _ } @[simp] lemma res_subset_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (V : opens X) (HVU : V ≤ U) (W HWV s) : (η.res_subset V HVU).1.1 W HWV s = η.1.1 W (le_trans HWV HVU) s := rfl @[simp] lemma comp_res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} (η : G.morphism H) (ξ : F.morphism G) (V : opens X) (HVU : V ≤ U) : (η.res_subset V HVU).comp (ξ.res_subset V HVU) = (η.comp ξ).res_subset V HVU := rfl @[simp] lemma id_res_subset {F : sheaf_of_rings_on_opens.{v} X U} (V : opens X) (HVU : V ≤ U) : (morphism.id F).res_subset V HVU = morphism.id (F.res_subset V HVU) := rfl -- def stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U) -- (s : F.to_sheaf_on_opens.stalk x hx) : G.to_sheaf_on_opens.stalk x hx := -- quotient.lift_on s (λ g, ⟦(⟨g.1 ⊓ U, (⟨g.2, hx⟩ : x ∈ g.1 ⊓ U), -- η.1.map _ inf_le_right (presheaf.res F.1.1 _ _ (set.inter_subset_left _ _) g.3)⟩ : stalk.elem _ _)⟧) $ -- λ g₁ g₂ ⟨V, hxV, HV1, HV2, hg⟩, quotient.sound ⟨V ⊓ U, ⟨hxV, hx⟩, set.inter_subset_inter_left _ HV1, set.inter_subset_inter_left _ HV2, -- calc G.to_sheaf_on_opens.res _ _ (V ⊓ U) inf_le_right (inf_le_inf HV1 (le_refl _)) (η.1.map (g₁.U ⊓ U) inf_le_right ((F.F).res (g₁.U) (g₁.U ⊓ U) (set.inter_subset_left _ _) (g₁.s))) -- = η.1.map (V ⊓ U) inf_le_right ((F.F).res V (V ⊓ U) (set.inter_subset_left _ _) ((F.F).res (g₁.U) V HV1 (g₁.s))) : -- by rw ← η.3; dsimp only [sheaf_on_opens.res, sheaf_of_rings_on_opens.to_sheaf_on_opens]; rw [← presheaf.Hcomp', ← presheaf.Hcomp'] -- ... = G.to_sheaf_on_opens.res _ _ (V ⊓ U) _ _ (η.1.map (g₂.U ⊓ U) inf_le_right ((F.F).res (g₂.U) (g₂.U ⊓ U) _ (g₂.s))) : -- by erw [hg, ← η.3]; dsimp only [sheaf_on_opens.res, sheaf_of_rings_on_opens.to_sheaf_on_opens]; rw [← presheaf.Hcomp', ← presheaf.Hcomp']⟩ -- @[simp] lemma stalk_to_stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U) -- (V : opens X) (HVU : V ≤ U) (hxV : x ∈ V) (s : F.to_sheaf_on_opens.eval V HVU) : -- η.stalk x hx (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s) = -- G.to_sheaf_on_opens.to_stalk x hx V hxV HVU (η.1.map V HVU s) := -- quotient.sound ⟨V, hxV, set.subset_inter (set.subset.refl _) HVU, set.subset.refl _, -- calc G.to_sheaf_on_opens.res (V ⊓ U) inf_le_right V HVU (le_inf (le_refl V) HVU) (η.1.map (V ⊓ U) inf_le_right (F.to_sheaf_on_opens.res V HVU (V ⊓ U) inf_le_right inf_le_left s)) -- = G.to_sheaf_on_opens.res V HVU V HVU (le_refl V) (η.1.map V HVU s) : by rw [η.3, res_res]⟩ instance is_ring_hom_stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U) : is_ring_hom (η.1.stalk x hx) := { map_one := quotient.sound ⟨U, hx, set.subset_inter (set.subset_univ U.1) (set.subset.refl U.1), set.subset_univ U.1, by dsimp only; erw [_root_.res_one, η.map_one, _root_.res_one, _root_.res_one]⟩, map_mul := λ y z, stalk.induction_on₂ y z $ λ V hxV HVU s t, by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, ← to_stalk_mul, sheaf_on_opens.morphism.stalk_to_stalk, η.map_mul, to_stalk_mul], map_add := λ y z, stalk.induction_on₂ y z $ λ V hxV HVU s t, by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, ← to_stalk_add, sheaf_on_opens.morphism.stalk_to_stalk, η.map_add, to_stalk_add] } section variables {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U) variables (s t : F.to_sheaf_on_opens.stalk x hx) (n : ℕ) @[simp] lemma stalk_add : η.1.stalk x hx (s + t) = η.1.stalk x hx s + η.1.stalk x hx t := is_ring_hom.map_add _ @[simp] lemma stalk_zero : η.1.stalk x hx 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma stalk_neg : η.1.stalk x hx (-s) = -η.1.stalk x hx s := is_ring_hom.map_neg _ @[simp] lemma stalk_sub : η.1.stalk x hx (s - t) = η.1.stalk x hx s - η.1.stalk x hx t := is_ring_hom.map_sub _ @[simp] lemma stalk_mul : η.1.stalk x hx (s * t) = η.1.stalk x hx s * η.1.stalk x hx t := is_ring_hom.map_mul _ @[simp] lemma stalk_one : η.1.stalk x hx 1 = 1 := is_ring_hom.map_one _ @[simp] lemma stalk_pow : η.1.stalk x hx (s^n) = (η.1.stalk x hx s)^n := is_semiring_hom.map_pow _ s n end end morphism structure equiv (F : sheaf_of_rings_on_opens.{v} X U) (G : sheaf_of_rings_on_opens.{w} X U) : Type (max u v w) := (to_fun : F.morphism G) (inv_fun : G.to_sheaf_on_opens.morphism F.to_sheaf_on_opens) (left_inv : ∀ V HVU s, inv_fun.1 V HVU (to_fun.1.1 V HVU s) = s) (right_inv : ∀ V HVU s, to_fun.1.1 V HVU (inv_fun.1 V HVU s) = s) namespace equiv def to_sheaf_on_opens {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : F.equiv G) : F.to_sheaf_on_opens.equiv G.to_sheaf_on_opens := { to_fun := e.1.1, .. e } def to_ring_equiv {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} (e : equiv F G) (V HVU) : F.to_sheaf_on_opens.eval V HVU ≃+* G.to_sheaf_on_opens.eval V HVU := ring_equiv.of' { to_fun := e.1.1.1 V HVU, inv_fun := e.2.1 V HVU, left_inv := e.3 V HVU, right_inv := e.4 V HVU } def refl (F : sheaf_of_rings_on_opens.{v} X U) : equiv F F := ⟨morphism.id F, sheaf_on_opens.morphism.id F.to_sheaf_on_opens, λ _ _ _, rfl, λ _ _ _, rfl⟩ @[simp] lemma refl_apply (F : sheaf_of_rings_on_opens.{v} X U) (V HV s) : (refl F).1.1.1 V HV s = s := rfl def symm {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} (e : equiv F G) : equiv G F := ⟨{ η := e.2, hom := λ V HVU, (ring_equiv.symm (e.to_ring_equiv V HVU)).hom }, e.1.1, e.4, e.3⟩ def trans {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} (e₁ : equiv F G) (e₂ : equiv G H) : equiv F H := ⟨e₂.1.comp e₁.1, e₁.2.comp e₂.2, λ _ _ _, by rw [morphism.comp_apply, sheaf_on_opens.morphism.comp_apply, e₂.3, e₁.3], λ _ _ _, by rw [morphism.comp_apply, sheaf_on_opens.morphism.comp_apply, e₁.4, e₂.4]⟩ @[simp] lemma trans_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} (e₁ : equiv F G) (e₂ : equiv G H) (V HV s) : (e₁.trans e₂).1.1.1 V HV s = e₂.1.1.1 V HV (e₁.1.1.1 V HV s) := rfl def res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : equiv F G) (V : opens X) (HVU : V ≤ U) : equiv (F.res_subset V HVU) (G.res_subset V HVU) := ⟨e.1.res_subset V HVU, e.2.res_subset V HVU, λ _ _ _, by rw [morphism.res_subset_apply, sheaf_on_opens.morphism.res_subset_apply, e.3], λ _ _ _, by rw [morphism.res_subset_apply, sheaf_on_opens.morphism.res_subset_apply, e.4]⟩ @[simp] lemma res_subset_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : equiv F G) (V : opens X) (HVU : V ≤ U) (W HW s) : (e.res_subset V HVU).1.1.1 W HW s = e.1.1.1 W (le_trans HW HVU) s := rfl -- def stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : equiv F G) (x : X) (hx : x ∈ U) : -- F.to_sheaf_on_opens.stalk x hx ≃ G.to_sheaf_on_opens.stalk x hx := -- { to_fun := e.1.1.stalk x hx, -- inv_fun := e.2.stalk x hx, -- left_inv := λ g, stalk.induction_on g $ λ V hxV HVU s, -- by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, e.3]; refl, -- right_inv := λ g, stalk.induction_on g $ λ V hxV HVU s, -- by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, e.4]; refl } end equiv def sheaf_glue {I : Type u} (S : I → opens X) (F : Π (i : I), sheaf_of_rings_on_opens.{v} X (S i)) (φ : Π i j, equiv ((F i).res_subset ((S i) ⊓ (S j)) inf_le_left) ((F j).res_subset ((S i) ⊓ (S j)) inf_le_right)) : sheaf_of_rings_on_opens.{max u v} X (⋃S) := { F := { Fring := λ U, @subtype.comm_ring (Π (i : I), (F i).to_sheaf_on_opens.eval (S i ⊓ U) inf_le_left) _ { f | ∀ (i j : I), (φ i j).1.1.1 (S i ⊓ S j ⊓ U) inf_le_left ((F i).to_sheaf_on_opens.res (S i ⊓ U) inf_le_left (S i ⊓ S j ⊓ U) (le_trans inf_le_left inf_le_left) (le_inf (le_trans inf_le_left inf_le_left) inf_le_right) (f i)) = (F j).to_sheaf_on_opens.res (S j ⊓ U) inf_le_left (S i ⊓ S j ⊓ U) (le_trans inf_le_left inf_le_right) (by rw inf_assoc; exact inf_le_right) (f j) } { add_mem := λ f g hf hg i j, by erw [res_add, morphism.map_add, res_add, hf i j, hg i j], zero_mem := λ i j, by erw [res_zero, morphism.map_zero, res_zero]; refl, neg_mem := λ f hf i j, by erw [res_neg, morphism.map_neg, res_neg, hf i j], one_mem := λ i j, by erw [res_one, morphism.map_one, res_one]; refl, mul_mem := λ f g hf hg i j, by erw [res_mul, morphism.map_mul, res_mul, hf i j, hg i j] }, res_is_ring_hom := λ U V HVU, { map_one := subtype.eq $ funext $ λ i, res_one _ _ _ _ _ _, map_mul := λ f g, subtype.eq $ funext $ λ i, res_mul _ _ _ _ _ _ _ _, map_add := λ f g, subtype.eq $ funext $ λ i, res_add _ _ _ _ _ _ _ _ }, .. sheaf_on_opens.sheaf_glue S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) } .. sheaf_on_opens.sheaf_glue S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) } @[simp] lemma sheaf_glue_res_val {I : Type u} (S : I → opens X) (F : Π (i : I), sheaf_of_rings_on_opens.{v} X (S i)) (φ : Π i j, equiv ((F i).res_subset ((S i) ⊓ (S j)) inf_le_left) ((F j).res_subset ((S i) ⊓ (S j)) inf_le_right)) (U HU V HV HVU s i) : ((sheaf_glue S F φ).to_sheaf_on_opens.res U HU V HV HVU s).1 i = (F i).to_sheaf_on_opens.res _ _ _ _ (inf_le_inf (le_refl _) HVU) (s.1 i) := rfl def universal_property (I : Type u) (S : I → opens X) (F : Π (i : I), sheaf_of_rings_on_opens.{v} X (S i)) (φ : Π i j, equiv ((F i).res_subset ((S i) ⊓ (S j)) inf_le_left) ((F j).res_subset ((S i) ⊓ (S j)) inf_le_right)) (Hφ1 : ∀ i V HV s, (φ i i).1.1.1 V HV s = s) (Hφ2 : ∀ i j k V HV1 HV2 HV3 s, (φ j k).1.1.1 V HV1 ((φ i j).1.1.1 V HV2 s) = (φ i k).1.1.1 V HV3 s) (i : I) : equiv (res_subset (sheaf_glue S F φ) (S i) (le_supr S i)) (F i) := { to_fun := { η := (sheaf_on_opens.universal_property I S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) Hφ1 Hφ2 i).1, hom := λ U HU, { map_one := res_one _ _ _ _ _ _, map_mul := λ x y, res_mul _ _ _ _ _ _ _ _, map_add := λ x y, res_add _ _ _ _ _ _ _ _ } }, .. sheaf_on_opens.universal_property I S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) Hφ1 Hφ2 i } end sheaf_of_rings_on_opens